"""WISP-Funnel: the Random and Evolution controllers in one run, sharing split-local preparation. Both controllers propose on the same training-only proxy (one feature dictionary and one dataset fingerprint), verify their own shortlists on the full splits and refit their own winners on train+validation. With two workers the controllers run in parallel threads; results do not depend on the number of workers. """ from concurrent.futures import ThreadPoolExecutor,Future from contextvars import ContextVar,copy_context from pathlib import Path from time import perf_counter import json from .fingerprint import compute_dataset_fingerprint from .dictionary import Dictionary,_DictionarySearch from .race import _proxy_data,fit_funnel from .search import _AcceleratedSearch,_configure from .selection import check_splits from .search_cache import SearchFeatures _capture=ContextVar('wisp_funnel_capture',default=None) def _route_capture(x,blocks,values): capture=_capture.get() if capture is not None:capture(x,blocks,values) class _SharedFingerprint(_DictionarySearch): def _fingerprint(self): return self.bank.fingerprint class _SharedFeatures(SearchFeatures): def __init__(self,limit,arrays): super().__init__(limit,arrays) self.pending={} def get(self,key,fn,*,tile=False): if tile or key[1] not in ('z','wear','dyad','interval_rank'): return super().get(key,fn,tile=tile) with self.lock: if key in self.store:return super().get(key,fn) pending=self.pending.get(key) if pending is None: pending=Future();self.pending[key]=pending;owner=True else:owner=False if not owner:return pending.result() try: value=super().get(key,fn) pending.set_result(value) return value except BaseException as exc: pending.set_exception(exc);raise finally: with self.lock:self.pending.pop(key) def fit_joint_funnel(train,valid,*,output,seed=42,evaluations=329,population=24, workers=2,shortlist=4,proxy_train=4096,proxy_valid=1024, cache_mb=128,stress_cache_mb=16,design_mb=256): """Original Random and Evolution. Each controller owns its proposals, ranks and refits. With two cores, run one sequential controller on each; with one, run them in series. Job and BLAS threads per candidate must be one. Memory retains one bounded cache of raw feature blocks and two private final-replay caches. """ from threadpoolctl import threadpool_limits if workers not in (1,2):raise ValueError('Use 1 or 2 controller workers') check_splits(train,valid) root=Path(output);root.mkdir(parents=True,exist_ok=True) if any(root.iterdir()):raise ValueError('Choose a fresh output directory') methods=('wisp_random','wisp_evolution') args=dict(seed=seed,evaluations=evaluations,shortlist=shortlist,population=population, family_scope='cis',mode='exact',workers=1,n_jobs=1,cost_weight=0.,ridge_solver='screened', verify_gram=True,reuse_final_design=True,design_mb=design_mb, cache_mb=cache_mb,stress_cache_mb=stress_cache_mb) start=perf_counter() with threadpool_limits(1): tr,ti=_proxy_data(train,proxy_train,seed,'train') va,vi=_proxy_data(valid,proxy_valid,seed+1,'valid') bank=Dictionary(tr,va,seed) bank.fingerprint=compute_dataset_fingerprint(tr,seed=seed) prepared=_AcceleratedSearch(train,valid,'.',seed=seed,candidate_workers=1,n_jobs_per_candidate=1,cost_weight=0.) _configure(prepared,'exact',None,'screened',cache_mb,stress_cache_mb,4) prepared.memory=_SharedFeatures(cache_mb,[array for array,_ in prepared.memory.known.values()]) prepared.memory.capture=_route_capture prep=perf_counter()-start joint=((tr,ti,va,vi),bank,prepared) def run(method): return fit_funnel(method,train,valid,output=root/method,_joint=joint,**args) try: if workers==2: with ThreadPoolExecutor(max_workers=2) as pool: fs=[pool.submit(copy_context().run,run,m) for m in methods] both=[f.result() for f in fs] else:both=[run(m) for m in methods] stats=prepared.memory.stats() finally:prepared.memory.clear() receipt=dict(seed=seed,evaluations=evaluations,total_seconds=perf_counter()-start,shared_preparation_s=prep, controller_workers=workers,worker_threads_each=1,feature_cache=stats,shared_fingerprints=1, shared_dictionaries=1,separate_winner_refits=2) (root/'pair.json').write_text(json.dumps(receipt,indent=2)) return {k:v[0] for k,v in zip(methods,both)},{k:v[1] for k,v in zip(methods,both)},receipt