File size: 12,294 Bytes
ac63d99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Verified local aggregate-response replay. No network calls, pickle or executable Hub code.

The caller must obtain expected_manifest_sha256 from a trusted pinned portfolio
registry. A manifest supplied by an untrusted party does not authenticate itself.
"""
from pathlib import Path
import hashlib,json,math,re

SHA=re.compile(r'[a-f0-9]{64}')
IDENTIFIER=re.compile(r'[A-Za-z0-9][A-Za-z0-9._:-]{0,127}')
CELLS=[f'a{a}-e{e}' for a in range(4) for e in range(3)]
MODES={'known_item_json':{'known-item'},'encoder_safetensors':{'encoder-research'},'cross_wave_json':{'2022-historical','2024-development-calibrated'}}
class RequestFailure(ValueError):
 def __init__(self,code,message,status='abstained'):super().__init__(message);self.code=code;self.status=status

def _hash(path):
 with path.open('rb') as stream:return hashlib.file_digest(stream,'sha256').hexdigest()
def _file(root,name):
 if not isinstance(name,str) or not name or Path(name).is_absolute():raise ValueError('Invalid artifact path')
 result=(root/name).resolve()
 if not result.is_relative_to(root):raise ValueError('Artifact path escapes model directory')
 if not result.is_file() or result.stat().st_size>512*1024*1024:raise ValueError('Artifact missing or oversized')
 return result

def _object_pairs(pairs):
 result={}
 for k,v in pairs:
  if k in result:raise ValueError('Duplicate JSON key')
  result[k]=v
 return result

def _read(path):
 if path.stat().st_size>32*1024*1024:raise ValueError('JSON artifact oversized')
 return json.loads(path.read_text('utf-8'),object_pairs_hook=_object_pairs,parse_constant=lambda _:(_ for _ in ()).throw(ValueError('Nonfinite JSON number')))

def _softmax(logits):
 if not logits or not all(isinstance(v,(int,float)) and not isinstance(v,bool) and math.isfinite(v) for v in logits):raise ValueError('Invalid model logits')
 z=[math.exp(v-max(logits)) for v in logits];total=math.fsum(z);return [v/total for v in z]

def _probabilities(p,options):
 if len(p)!=len(options) or len(set(options))!=len(options) or len(options)<2:raise ValueError('Invalid output option mapping')
 if not all(isinstance(v,(int,float)) and not isinstance(v,bool) and math.isfinite(v) and v>=0 for v in p) or not math.isclose(math.fsum(p),1,abs_tol=1e-5):raise ValueError('Invalid probability distribution')
 return dict(zip(options,p,strict=True))

def _linear(item,features,offset=None):
 rows=item['coefficients'];intercepts=item['intercepts'];offset=offset or [0.]*len(intercepts)
 if len(rows)!=len(intercepts) or len(offset)!=len(intercepts):raise ValueError('Invalid coefficient dimensions')
 logits=[]
 for row,bias,shift in zip(rows,intercepts,offset,strict=True):
  if len(row)!=len(features):raise ValueError('Invalid feature dimensions')
  logits.append(bias+shift+math.fsum(a*b for a,b in zip(row,features,strict=True)))
 return _softmax(logits)

def predict(model_dir:Path,request:dict)->dict:
 """Return option-ID probabilities or explicit abstention for one exact instrument.

 request = {question_id, instrument_hash, cell_id, mode,
            expected_manifest_sha256, request_id?}
 """
 result={'schema_version':'windtunnel-local-result-v1','request_id':None,'status':'error','prediction':None,'reason':None}
 try:
  required={'question_id','instrument_hash','cell_id','mode','expected_manifest_sha256'}
  if not isinstance(request,dict) or not required.issubset(request) or set(request)-required-{'request_id'}:raise RequestFailure('invalid_request','Use the documented exact-instrument fields.', 'error')
  if 'request_id' in request:
   if not isinstance(request['request_id'],str) or not IDENTIFIER.fullmatch(request['request_id']):raise RequestFailure('invalid_request_id','Use an opaque request identifier.','error')
   result['request_id']=request['request_id']
  for field in ['question_id','cell_id']:
   if not isinstance(request[field],str) or not IDENTIFIER.fullmatch(request[field]):raise RequestFailure('invalid_request',field+' is invalid.','error')
  if not isinstance(request['instrument_hash'],str) or not SHA.fullmatch(request['instrument_hash']):raise RequestFailure('invalid_instrument_hash','Expected an exact lowercase instrument SHA-256.','error')
  expected=request['expected_manifest_sha256']
  if not isinstance(expected,str) or not SHA.fullmatch(expected):raise RequestFailure('unverified_manifest','Provide the trusted manifest checksum from the pinned portfolio.','error')
  root=Path(model_dir).resolve();manifest_path=_file(root,'runtime-manifest.json')
  if _hash(manifest_path)!=expected:raise RequestFailure('manifest_checksum_mismatch','The local manifest differs from the trusted checksum.','error')
  manifest=_read(manifest_path);architecture=manifest['architecture']
  if manifest['schema_version']!='windtunnel-runtime-v1' or architecture not in MODES:raise ValueError('Unsupported runtime architecture')
  mode=request['mode']
  if not isinstance(mode,str) or mode not in MODES[architecture]:raise RequestFailure('unsupported_mode','Select the documented mode for this architecture.')
  files=manifest['files']
  if not isinstance(files,dict) or not 1<=len(files)<=20:raise ValueError('Invalid artifact manifest')
  for name,sha in files.items():
   if not isinstance(sha,str) or not SHA.fullmatch(sha) or _hash(_file(root,name))!=sha:raise RequestFailure('artifact_checksum_mismatch','A pinned model, registry or base artifact changed.','error')
  for field in ['model_file','questions_file']:
   if manifest[field] not in files:raise ValueError('Unpinned inference artifact')
  questions=_read(_file(root,manifest['questions_file']))
  if not isinstance(questions,list):raise ValueError('Invalid exact instrument registry')
  question=next((q for q in questions if q['question_id']==request['question_id']),None)
  if question is None:raise RequestFailure('unsupported_question','This historical model has no supported registry entry for this question.')
  if question['instrument_hash']!=request['instrument_hash']:raise RequestFailure('instrument_mismatch','Changed wording, context, language or answer options require a new instrument and evaluation.')
  cell=request['cell_id']
  if cell not in CELLS:raise RequestFailure('unsupported_population_cell','Only registered coarse age-by-education cells are supported.')
  options=[o['id'] for o in question['options']]
  support=None
  if architecture=='encoder_safetensors':
   if manifest['support_file'] not in files:raise ValueError('Unpinned support metadata')
   support=_read(_file(root,manifest['support_file']))['items'].get(question['question_id'],{}).get(cell)
   if not support or support.get('supported') is not True:raise RequestFailure('unsupported_population_cell','The training support policy does not permit this item/cell.')
   # All transformer files are local, explicitly pinned safetensors/tokenizer bytes.
   base_name=manifest['base_subdir']
   if base_name!='base' or not all('base/'+name in files for name in ['config.json','model.safetensors','tokenizer.json','tokenizer_config.json','vocab.txt','special_tokens_map.json']):raise ValueError('Unpinned encoder base')
   try:
    import torch
    from transformers import AutoModel,AutoTokenizer
    from safetensors.torch import load_file
   except ImportError as error:raise RequestFailure('dependency_unavailable','Install the pinned CPU encoder dependencies; no hosted inference is invoked.','error') from error
   torch.set_num_threads(1)
   from torch import nn
   class Scorer(nn.Module):
    def __init__(self,hidden):
     super().__init__();self.population=nn.Embedding(13,12);self.scorer=nn.Sequential(nn.Linear(hidden+12,64),nn.GELU(),nn.Linear(64,1))
    def forward(self,text):
     population=self.population.weight[:,None,:].expand(-1,text.shape[0],-1);return self.scorer(torch.cat([text[None,:,:].expand(13,-1,-1),population],-1)).squeeze(-1)
   tokenizer=AutoTokenizer.from_pretrained(root/'base',local_files_only=True,trust_remote_code=False)
   encoder=AutoModel.from_pretrained(root/'base',local_files_only=True,trust_remote_code=False,use_safetensors=True).eval();scorer=Scorer(encoder.config.hidden_size).eval()
   checkpoint=load_file(_file(root,manifest['model_file']));scorer.load_state_dict({k.removeprefix('head.'):v for k,v in checkpoint.items() if k.startswith('head.')});encoder.encoder.layer[-1].load_state_dict({k.removeprefix('last_block.'):v for k,v in checkpoint.items() if k.startswith('last_block.')})
   instrument=' | '.join(filter(None,[question['preceding_context'],question['question_text'],question['stimulus_text']]))
   prompt=(f"2024 CES pre-election survey, US citizen adults, English. Format: {question['response_type']}. {instrument} Offered answers in order: {' | '.join(o['label'] for o in question['options'])}.")
   tokens=tokenizer([prompt]*len(options),[o['label'] for o in question['options']],padding=True,truncation=False,return_tensors='pt')
   if tokens.input_ids.shape[1]>256:raise RequestFailure('instrument_token_limit','The complete instrument exceeds the registered 256-token budget.')
   with torch.no_grad():
    hidden=encoder(**tokens).last_hidden_state;mask=tokens.attention_mask[...,None];embedding=torch.nn.functional.normalize((hidden*mask).sum(1)/mask.sum(1),dim=-1);values=scorer(embedding).softmax(-1)[CELLS.index(cell)].tolist()
  else:
   model=_read(_file(root,manifest['model_file']));items=model['items'];item=items.get(question['question_id']) if isinstance(items,dict) else next((v for v in items if v['question_id']==question['question_id']),None)
   if not item or item['instrument_hash']!=question['instrument_hash'] or item['option_ids']!=options:raise ValueError('Model and instrument option mapping differ')
   support=item.get('training_support',{}).get(cell)
   supported=cell in item.get('supported_cells',[]) if 'supported_cells' in item else support and support.get('supported') is True
   if not supported:raise RequestFailure('unsupported_population_cell','The training support policy does not permit this item/cell.')
   if architecture=='known_item_json':
    champion=item['champion']
    if champion=='shrinkage':values=item['cell_probabilities'][cell]
    elif champion=='marginal':values=item['marginal']
    elif champion=='linear':values=_linear(item,model['cell_features'][cell])
    else:raise ValueError('Unsupported known-item candidate')
   else:values=_linear(item,model['cell_features'][cell],item['intercept_offsets_from_target_dev'] if mode=='2024-development-calibrated' else None)
  probabilities=_probabilities(values,options)
  result.update(status='ok',reason=None,prediction={'question_id':question['question_id'],'instrument_hash':question['instrument_hash'],'cell_id':cell,'mode':mode,'option_ids':options,'probabilities':probabilities},provenance={'architecture':architecture,'manifest_sha256':expected,'model_artifact_sha256':files[manifest['model_file']],'registry_sha256':files[manifest['questions_file']],'upstream':manifest['upstream'],'validation_track':manifest['validation_track'],'capability_status':manifest['capability_status'],'field_dates':question.get('field_dates',manifest.get('field_dates')),'research_scope':'Recorded historical answer distributions, not individual beliefs, persuasion or prospective forecasts.','target_development_labels_used':(mode=='2024-development-calibrated' if architecture=='cross_wave_json' else True),'development_label_role':('target-wave response log-odds offsets' if mode=='2024-development-calibrated' else 'none in historical cross-wave fit' if architecture=='cross_wave_json' else 'same-wave development checkpoint or shrinkage selection; held-out family labels remain outside encoder fitting')},uncertainty={'status':'evaluation_only_not_per_request_calibrated','training_support':support,'interpretation':'Weighted opt-in response aggregates. Published fixed-model respondent bootstrap excludes coverage bias, training variation and new-instrument uncertainty.'})
 except RequestFailure as error:result.update(status=error.status,reason={'code':error.code,'message':str(error)})
 except (OSError,ValueError,TypeError,KeyError,StopIteration,RuntimeError,ImportError) as error:result.update(status='error',reason={'code':'invalid_model_artifact','message':'Local verified inference could not complete: '+type(error).__name__})
 return result