File size: 9,469 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
"""One-pass HF probability backend for a matched causal/bidirectional reference.

No autoregressive generation; only candidate logits from the final prompt row.
This backend is experimental until full-model parity and batching checks pass.
"""
import argparse
import asyncio
import hashlib
import json
import os
import time
import traceback
import concurrent.futures
from pathlib import Path

p=argparse.ArgumentParser();p.add_argument('--model',required=True);p.add_argument('--port',type=int,required=True)
p.add_argument('--attention',choices=['causal','bidirectional_prompt'],default='causal')
p.add_argument('--max-context',type=int,default=65536);p.add_argument('--batch-size',type=int,default=8)
p.add_argument('--batch-tokens',type=int,default=16384);a=p.parse_args()

import torch
from transformers import AutoModelForImageTextToText,AutoTokenizer
from transformers.models.qwen3_5 import modeling_qwen3_5 as hf_qwen
from fla.modules import FusedRMSNormGated
from fla.ops.gated_delta_rule import chunk_gated_delta_rule,fused_recurrent_gated_delta_rule
from fastapi import FastAPI,Request,HTTPException
import uvicorn

def torch_flash_readout(module,query,key,value,attention_mask,dropout=0.0,scaling=None,**kwargs):
    """Unpadded per-case SDPA; avoids this environment's FA2 varlen fault.

    Each case retains every real token. Causal/bidirectional semantics are
    taken from the trained full-attention module, with no cross-case mask.
    """
    if attention_mask is not None and attention_mask.ndim!=2:
        raise ValueError('Expected native FA2 two-dimensional padding mask')
    result=torch.zeros_like(query)
    for i in range(query.shape[0]):
        length=query.shape[-2] if attention_mask is None else int(attention_mask[i].sum().item())
        if length<=0:raise ValueError('Empty attention sequence')
        q=query[i:i+1,:,-length:,:].contiguous()
        k=key[i:i+1,:,-length:,:].contiguous();v=value[i:i+1,:,-length:,:].contiguous()
        if q.shape[1]!=k.shape[1]:
            if q.shape[1]%k.shape[1]:raise ValueError('Invalid grouped-query heads')
            repeats=q.shape[1]//k.shape[1];k=k.repeat_interleave(repeats,dim=1);v=v.repeat_interleave(repeats,dim=1)
        with torch.nn.attention.sdpa_kernel([torch.nn.attention.SDPBackend.FLASH_ATTENTION]):
            y=torch.nn.functional.scaled_dot_product_attention(q,k,v,dropout_p=dropout,
                is_causal=module.is_causal,scale=scaling)
        result[i:i+1,:,-length:,:]=y
    return result.transpose(1,2).contiguous(),None

# Keep HF's padding-mask preparation contract, but explicitly replace only
# this process's full-attention implementation. Health reports the real op.
hf_qwen.ALL_ATTENTION_FUNCTIONS.register('flash_attention_2',torch_flash_readout)

torch.set_num_threads(8)
descriptor=Path(a.model)/'decision-inference.json'
if descriptor.exists() and json.loads(descriptor.read_text())['attention_mode']!=a.attention:
    raise ValueError('Requested attention mode differs from the verified model descriptor')
# The environment has working FLA operators, while Transformers' optional
# distribution-metadata detection misses this installation. Bind the installed
# kernels explicitly; use the model's vectorized torch conv when causal-conv1d
# is absent. No weights or model equations are changed by these bindings.
hf_qwen.chunk_gated_delta_rule=chunk_gated_delta_rule
hf_qwen.fused_recurrent_gated_delta_rule=fused_recurrent_gated_delta_rule
# Retain HF's FP32-accumulating gated norm for this reference. Binding a new
# norm class during meta construction is not needed to accelerate recurrence.
hf_qwen.FusedRMSNormGated=None
tokenizer=AutoTokenizer.from_pretrained(a.model)
model=AutoModelForImageTextToText.from_pretrained(a.model,dtype=torch.bfloat16,
    attn_implementation='flash_attention_2',device_map={'':0}).eval()
torch.cuda.synchronize()
patched=[]
linear_kernels=[]
for name,module in model.named_modules():
    if module.__class__.__name__=='Qwen3_5Attention':
        if not hasattr(module,'is_causal'):raise ValueError('Unknown HF attention contract')
        module.is_causal=a.attention=='causal'
        patched.append(name)
    if module.__class__.__name__=='Qwen3_5GatedDeltaNet':
        if not module.chunk_gated_delta_rule.__module__.startswith('fla.'):
            raise ValueError('Slow/unverified torch recurrence path is not admitted')
        linear_kernels.append(module.chunk_gated_delta_rule.__module__)
if len(patched)!=16:raise ValueError(f'Expected 16 HF full-attention modules, found {len(patched)}')
if len(linear_kernels)!=48:raise ValueError('Expected 48 FLA linear-attention modules')
if os.environ.get('JEV_HF_DEBUG_NAN')=='1':
    def finite_hook(name):
        def hook(module,inputs,output):
            values=output if isinstance(output,tuple) else (output,)
            for value in values:
                if isinstance(value,torch.Tensor) and not torch.isfinite(value).all():
                    print('HF_NONFINITE_LAYER',name,flush=True)
                    raise RuntimeError('nonfinite HF layer '+name)
        return hook
    for name,module in model.named_modules():
        if module.__class__.__name__ in ['Qwen3_5GatedDeltaNet','Qwen3_5RMSNormGated','Qwen3_5Attention']:
            module.register_forward_hook(finite_hook(name))
print('HF_DIRECT_MODEL_READY',json.dumps({'model':a.model,'attention':a.attention,'layers':patched}),flush=True)
queue=asyncio.Queue();app=FastAPI();worker_task=None
gpu_executor=concurrent.futures.ThreadPoolExecutor(max_workers=1)
first_failure=True

@torch.inference_mode()
def predict(items):
    prompts=[item[0]['prompt'] for item in items]
    longest=max(map(len,prompts))
    ids=torch.zeros((len(prompts),longest),dtype=torch.long,device='cuda')
    mask=torch.zeros_like(ids)
    for i,row in enumerate(prompts):
        ids[i,-len(row):]=torch.tensor(row,device='cuda');mask[i,-len(row):]=1
    positions=(mask.cumsum(-1)-1).clamp_min(0)
    begin=time.monotonic()
    output=model(input_ids=ids,attention_mask=mask,position_ids=positions,use_cache=False,logits_to_keep=1)
    logits=output.logits[:,-1,:].float()
    if not torch.isfinite(logits).all():raise RuntimeError('Nonfinite HF readout logits')
    results=[]
    for i,(body,_) in enumerate(items):
        support=body['allowed_token_ids']
        scores=logits[i,support].log_softmax(-1).cpu().tolist()
        best=max(range(len(scores)),key=scores.__getitem__)
        results.append({'model':'jev-policy','choices':[{'index':0,'text':tokenizer.decode([support[best]]),
            'finish_reason':'length','logprobs':{'tokens':['token_id:'+str(support[best])],
             'token_logprobs':[scores[best]],'top_logprobs':[{f'token_id:{t}':s for t,s in zip(support,scores)}]}}],
            'usage':{'prompt_tokens':len(prompts[i]),'completion_tokens':1,'total_tokens':len(prompts[i])+1},
            'direct_backend':{'attention':a.attention,'batch_size':len(items),'seconds':time.monotonic()-begin}})
    return results

async def worker():
    global first_failure
    pending=None
    while True:
        first=pending or await queue.get();pending=None;items=[first]
        while len(items)<a.batch_size:
            try:item=await asyncio.wait_for(queue.get(),timeout=.003)
            except asyncio.TimeoutError:break
            padded=max(len(x[0]['prompt']) for x in [*items,item])*(len(items)+1)
            if padded>a.batch_tokens:pending=item;break
            items.append(item)
        try:
            outputs=await asyncio.get_running_loop().run_in_executor(gpu_executor,predict,items)
            for (_,f),output in zip(items,outputs):
                if not f.done():f.set_result(output)
        except Exception as error:
            if first_failure:
                first_failure=False;traceback.print_exc()
                folder=Path(os.environ.get('JEV_HF_FAILURE_DIR','/tmp/jev-a100/hf-failures'));folder.mkdir(parents=True,exist_ok=True)
                (folder/f'failure-{a.port}-{time.time_ns()}.json').write_text(json.dumps({'error':repr(error),'batch':[body for body,_ in items],
                    'attention':a.attention,'model':a.model})+'\n')
            for _,f in items:
                if not f.done():f.set_exception(error)

@app.on_event('startup')
async def startup():
    global worker_task
    worker_task=asyncio.create_task(worker())

@app.get('/health')
async def health():
    return {'status':'ok','backend':'HF Torch-SDPA flash + FLA direct-only','model_path':a.model,
            'attention':a.attention,'full_layers':len(patched),'linear_fla_layers':len(linear_kernels),
            'linear_kernel':linear_kernels[0],'torch':torch.__version__}

@app.post('/v1/completions')
async def completions(request:Request):
    body=await request.json();prompt=body.get('prompt');support=body.get('allowed_token_ids')
    if (body.get('max_tokens')!=1 or not isinstance(prompt,list) or not prompt or
        len(prompt)+1>a.max_context or not isinstance(support,list) or not support or
        len(support)!=len(set(support)) or any(type(t)is not int or t<0 for t in prompt+support)):
        raise HTTPException(422,'Only complete one-pass token-array probability readouts are supported')
    future=asyncio.get_running_loop().create_future();await queue.put((body,future))
    try:return await future
    except Exception as error:raise HTTPException(500,repr(error))

uvicorn.run(app,host='0.0.0.0',port=a.port,log_level='warning')