Spaces:
Running on Zero
Running on Zero
Download ope.py from ManasT2485/readloops: direct link, hf CLI and curl.
- Browser
- Download file 8.32 kB
-
https://huggingface.co/spaces/ManasT2485/readloops/resolve/main/ope.py
- Command line
-
hf download hf://spaces/ManasT2485/readloops/ope.py
-
curl -L -o ope.py https://huggingface.co/spaces/ManasT2485/readloops/resolve/main/ope.py
8.32 kB
| """One-step policy value on logged contexts, not evaluation of a whole curriculum. | |
| IPS and SNIPS use exact logged marginal propensities. DR reward regression is | |
| cross-fitted by learner, never by session. Missing delayed outcomes stay missing. | |
| """ | |
| import argparse | |
| import json | |
| from pathlib import Path | |
| import numpy as np | |
| from learning import ACTIONS, FEATURES, VERSION, REWARD, action_distribution | |
| def target_for(record,target): | |
| return target(record) if callable(target) else target | |
| def validate(records, target): | |
| for record in records or [{}]: | |
| probabilities = target_for(record,target) if record or not callable(target) else {a:1/6 for a in ACTIONS} | |
| if set(probabilities) != set(ACTIONS) or any(not np.isfinite(p) or p < 0 for p in probabilities.values()) or abs(sum(probabilities.values())-1) > 1e-8: | |
| raise ValueError('Target must give a probability for every action and sum to one.') | |
| seen = set() | |
| languages = set() | |
| for r in records: | |
| key = (r['participant'], r['id']) | |
| if key in seen: | |
| raise ValueError('Duplicate decision ID in participant.') | |
| seen.add(key) | |
| languages.add(r['language']) | |
| if r.get('version') != VERSION or r.get('reward_definition') != REWARD: | |
| raise ValueError('Incompatible policy or reward version.') | |
| x, behavior = r['features'], r['behavior'] | |
| if len(x) != len(FEATURES) or not np.isfinite(x).all() or set(behavior) != set(ACTIONS): | |
| raise ValueError('Invalid features or logged action set.') | |
| if any(not np.isfinite(v) or v < 0 for v in behavior.values()) or abs(sum(behavior.values()) - 1) > 1e-8 or behavior.get(r['action'], 0) <= 0: | |
| raise ValueError('Invalid behavior propensities.') | |
| if r['reward'] is not None and (not np.isfinite(r['reward']) or not 0 <= r['reward'] <= 1): | |
| raise ValueError('Reward must be absent or in [0, 1].') | |
| if len(languages) > 1: | |
| raise ValueError('Evaluate English and Greek separately.') | |
| def crossfit(rows, target): | |
| people = sorted({r['participant'] for r in rows}) | |
| if len(people) < 2: | |
| return None | |
| # Leave-one-learner-out nuisance fits: no held-out learner in its own model. | |
| values = [] | |
| for person in people: | |
| train = [r for r in rows if r['participant'] != person] | |
| models = {} | |
| for action in ACTIONS: | |
| selected = [r for r in train if r['action'] == action] | |
| x = np.asarray([r['features'] for r in selected], dtype=float).reshape(-1, len(FEATURES)) | |
| y = np.asarray([r['reward'] for r in selected]) | |
| # Ridge around a neutral 0.5 prior, finite even with unseen arms. | |
| models[action] = np.linalg.solve(np.eye(len(FEATURES)) + x.T@x, x.T@(y-.5)) | |
| for r in rows: | |
| if r['participant'] != person: | |
| continue | |
| q = {a: float(np.clip(.5 + np.dot(r['features'], models[a]), 0, 1)) for a in ACTIONS} | |
| probabilities = target_for(r,target) | |
| weight = probabilities[r['action']] / r['behavior'][r['action']] | |
| values.append((person, sum(probabilities[a]*q[a] for a in ACTIONS) + weight*(r['reward']-q[r['action']]))) | |
| return values | |
| def evaluate(records, target, seed=17): | |
| validate(records, target) | |
| rows = [r for r in records if r['reward'] is not None] | |
| unsupported = sum(any(target_for(r,target)[a] > 0 and r['behavior'][a] == 0 for a in ACTIONS) for r in records) | |
| report = {'assigned': len(records), 'observed': len(rows), 'missing_rewards': len(records)-len(rows), | |
| 'participants': len({r['participant'] for r in records}), 'unsupported_contexts': unsupported, | |
| 'target': getattr(target,'__name__','frozen context policy') if callable(target) else target, 'ips': None, 'snips': None, 'doubly_robust': None, 'ess': 0, | |
| 'notice': 'Observed-outcome one-step estimates only. Missing outcomes can bias results. Target must be fixed before inspecting evaluation outcomes. No learning-benefit or curriculum-effect claim.'} | |
| if not rows or unsupported: | |
| report['status'] = 'no observed rewards' if not rows else 'unsupported target; estimates withheld' | |
| return report | |
| w = np.asarray([target_for(r,target)[r['action']]/r['behavior'][r['action']] for r in rows]) | |
| y = np.asarray([r['reward'] for r in rows]) | |
| report.update(ips=float(np.mean(w*y)), snips=float(np.dot(w,y)/sum(w)) if sum(w) else None, | |
| ess=float(sum(w)**2/np.dot(w,w)) if np.dot(w,w) else 0, | |
| maximum_weight=float(max(w)), weight_p95=float(np.quantile(w,.95)), | |
| ips_contribution_variance=float(np.var(w*y, ddof=1)) if len(w)>1 else None, | |
| status='descriptive; review support, dependence and missingness') | |
| dr = crossfit(rows, target) | |
| if dr is not None: | |
| report['doubly_robust'] = float(np.mean([v for _,v in dr])) | |
| people = sorted({r['participant'] for r in rows}) | |
| report['cluster_bootstrap_95'] = None | |
| if len(people) >= 10: | |
| rng = np.random.default_rng(seed) | |
| samples = [] | |
| for _ in range(500): | |
| ids = [i for p in rng.choice(people, len(people)) for i,r in enumerate(rows) if r['participant'] == p] | |
| samples.append(float(np.mean((w*y)[ids]))) | |
| report['cluster_bootstrap_95'] = {'ips': np.quantile(samples,[.025,.975]).tolist(), 'replicates':500} | |
| else: | |
| report['interval_notice'] = 'At least 10 independent learner clusters required by this reporting rule; one learner is not multiple independent participants.' | |
| return report | |
| def compare_policies(training,evaluation): | |
| """Freeze policies on other learners, then evaluate identical logged contexts.""" | |
| uniform = {a:1/len(ACTIONS) for a in ACTIONS} | |
| validate(training,uniform); validate(evaluation,uniform) | |
| if {r['participant'] for r in training}&{r['participant'] for r in evaluation}: | |
| raise ValueError('Training and evaluation must contain different learners.') | |
| if len({r['language'] for r in training+evaluation})>1: | |
| raise ValueError('Keep languages separate.') | |
| if not training or not evaluation: | |
| raise ValueError('Supply nonempty, disjoint training and evaluation logs.') | |
| records = [({'features':r['features'],'action_key':r['action']},r['reward']) for r in training if r['reward'] is not None] | |
| reports = {} | |
| for policy in ('fixed','epsilon','linucb'): | |
| def target(row): | |
| # Same omission/addition precedence as the online fixed rule. | |
| x = row['features'] | |
| fixed = ('cloze' if x[2]>0 else 'order' if x[3]>0 else 'comprehension')+':supported' | |
| return action_distribution(policy,x,records,fixed)[0] | |
| target.__name__ = 'frozen-'+policy | |
| reports[policy] = evaluate(evaluation,target) | |
| import hashlib | |
| reports['provenance'] = {'training_sha256':hashlib.sha256(json.dumps(training,sort_keys=True).encode()).hexdigest(), | |
| 'evaluation_sha256':hashlib.sha256(json.dumps(evaluation,sort_keys=True).encode()).hexdigest(), | |
| 'notice':'Policies frozen on separate learners. No online state transitions or curriculum-effect estimate. Choose hyperparameters before opening evaluation outcomes.'} | |
| return reports | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument('input', type=Path) | |
| group = parser.add_mutually_exclusive_group(required=True) | |
| group.add_argument('--target', type=Path, help='Predeclared fixed probability JSON over six actions') | |
| group.add_argument('--training',type=Path,help='Disjoint learner logs for fixed, epsilon and LinUCB comparison') | |
| parser.add_argument('--output', type=Path, required=True) | |
| args = parser.parse_args() | |
| records = json.loads(args.input.read_text(encoding='utf-8')) | |
| report = compare_policies(json.loads(args.training.read_text(encoding='utf-8')),records) if args.training else evaluate(records,json.loads(args.target.read_text(encoding='utf-8'))) | |
| args.output.parent.mkdir(parents=True, exist_ok=True) | |
| args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8') | |
| print(json.dumps(report, indent=2)) | |
| if __name__ == '__main__': | |
| main() | |