ants-ts-tiny-ar / inference.py
duj626's picture
Release five original Ants ridge and MLP checkpoints
4646490 verified
Raw History Blame Contribute Delete
4.76 kB
"""Load original Ants E45e weights and forecast using their archived NumPy kernel."""
from dataclasses import dataclass
import hashlib
import importlib.util
import json
from pathlib import Path
import zipfile
import numpy as np
ROOT=Path(__file__).resolve().parent
def _require(ok,message):
if not ok:raise ValueError(message)
def _digest(path):return hashlib.sha256(path.read_bytes()).hexdigest()
@dataclass
class ForecastModel:
"""One dataset-specific checkpoint. Contexts use original physical units."""
arrays:dict
metadata:dict
_kernel:object
def _adapt(self,contexts,channels):
x=np.asarray(contexts,dtype=np.float64)
c=np.asarray(channels)
_require(x.ndim==2 and x.shape[1]==16 and len(x)>0 and np.isfinite(x).all(),
'contexts must be a nonempty finite (batch,16) array')
_require(c.shape==(len(x),) and c.dtype.kind in 'iu' and np.all(c>=0)
and np.all(c<self.metadata['channels']),'supply one original dataset channel index per row')
a=self.arrays
return (x-a['channel_mean'][c,None])/a['channel_scale'][c,None],c
def predict(self,contexts,channels,horizon=96):
"""Recursive forecast, no future observations; returns (batch,horizon)."""
_require(type(horizon) is int and 1<=horizon<=96,'horizon must be an integer in [1,96]')
x,c=self._adapt(contexts,channels);a=self.arrays
y=self._kernel.rollout_batch(a,self.metadata['model'],self.metadata['representation'],x,horizon)
result=y*a['channel_scale'][c,None]+a['channel_mean'][c,None]
_require(np.isfinite(result).all(),'nonfinite forecast')
return result
def predict_one_step(self,contexts,channels):
"""One step per supplied context; this is distinct from 96-step rollout."""
x,c=self._adapt(contexts,channels);a=self.arrays
y=self._kernel.one_step(a,self.metadata['model'],self.metadata['representation'],x)
result=y*a['channel_scale'][c]+a['channel_mean'][c]
_require(np.isfinite(result).all(),'nonfinite one-step prediction')
return result
def load_model(asset_id='Ants-TS-0004',root=ROOT):
"""Load a listed asset from a local downloaded repository; never fit anything."""
root=Path(root)
items={m['asset_id']:m for m in json.loads((root/'models.json').read_text())}
_require(asset_id in items,'unknown asset ID; see models.json')
item=items[asset_id];bundle=root/'checkpoints'/asset_id
for name,key in [('checkpoint.json','checkpoint_json_sha256'),('checkpoint.npz','checkpoint_npz_sha256')]:
_require(_digest(bundle/name)==item[key],'checkpoint checksum mismatch')
r=json.loads((bundle/'checkpoint.json').read_text())
_require(r.get('kind')=='e45e_scale_checkpoint' and r.get('inference_backend')=='channel_adapter_fixed_order_numpy_tanh_v1'
and r.get('model') in ('ridge','mlp') and r.get('representation') in ('level','center_delta')
and r.get('scaling') in ('channel_train','pooled_raw') and r.get('data_role')=='dev'
and r.get('test_values_used') is False and r.get('final_iterate_only') is True
and r.get('channels')==item['channels'] and r.get('lookback')==16 and r.get('horizon')==96,
'unsupported checkpoint identity')
with zipfile.ZipFile(bundle/'checkpoint.npz') as z:
_require(sum(i.file_size for i in z.infolist())<=65536,'oversized checkpoint')
with np.load(bundle/'checkpoint.npz',allow_pickle=False) as z:a={k:z[k] for k in z.files}
shapes={'mean':(16,),'scale':(16,),'target_mean':(),'target_scale':(),
'channel_mean':(r['channels'],),'channel_scale':(r['channels'],)}
shapes.update({'coef':(17,1)} if r['model']=='ridge' else {'w1':(16,8),'b1':(8,),'w2':(8,1),'b2':(1,)})
_require(set(a)==set(shapes) and all(a[k].shape==s for k,s in shapes.items()),'invalid checkpoint shapes')
_require(all(v.dtype==np.dtype('float64') and np.isfinite(v).all() for v in a.values()),'finite binary64 weights required')
_require(sum(v.size for v in a.values())==r['stored_numeric_values']==item['stored_numeric_values']<=300
and np.all(a['scale']>0) and np.all(a['channel_scale']>0) and a['target_scale']>0,
'invalid physical size or preprocessing scales')
source=json.loads((root/'SOURCE.json').read_text())
relative='antslab/gyms/portable_inference.py';p=root/'source'/relative
_require(_digest(p)==source['source_file_sha256'][relative],'archived inference kernel checksum mismatch')
spec=importlib.util.spec_from_file_location('_ants_e45e_portable',p)
kernel=importlib.util.module_from_spec(spec);spec.loader.exec_module(kernel)
return ForecastModel(a,r,kernel)