Spaces:
Running on Zero

File size: 7,262 Bytes
3e6f84d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Versioned six-action contextual bandit with delayed, reviewed reading proxies.

The two support levels are UI interventions, not calibrated difficulty levels.
Never consumes held-out assessment scores or first-answer exercise correctness.
"""
import json
import random
from datetime import datetime
import numpy as np
from sqlmodel import select
from database import ReadingSession, LearningReward, now
from policy import fixed_action
from scoring import tokenize
from content import BY_ID

VERSION = 'delayed-linucb-v1'
MODES = ('learning-fixed', 'learning-epsilon', 'learning-linucb', 'learning-comparison')
ACTIONS = tuple(f'{kind}:{level}' for kind in ('comprehension', 'cloze', 'order') for level in ('supported', 'independent'))
FEATURES = ('bias', 'reviewed_difference_rate', 'omissions', 'additions', 'history_size', 'recent_reward', 'passage_length', 'has_review')
EPSILON, ALPHA = .2, .5
REWARD = '0.5 + 0.5 * clipped(previous minus next reviewed word-difference rate); next different practice passage within 14 days; a noisy proxy, not causal learning gain'


def reviewed_rate(row):
    from scoring import align
    draft = json.loads(row.draft)
    if not draft.get('compared') or not draft.get('transcript_reviewed') or not draft.get('transcript', '').strip():
        return None
    return min(1., align(BY_ID[row.passage_id]['text'], draft['transcript'], row.language)['word_difference_rate'])


def settle_previous(db, current):
    """Attach at most one later outcome before choosing the next intervention."""
    if current.split != 'practice' or current.selection_mode not in MODES:
        return
    previous = db.exec(select(ReadingSession).where(ReadingSession.language == current.language, ReadingSession.split == 'practice', ReadingSession.id != current.id, ReadingSession.created_at < current.created_at).order_by(ReadingSession.created_at.desc())).first()
    if not previous or previous.status != 'completed' or not previous.decision or previous.passage_id == current.passage_id:
        return
    decision = json.loads(previous.decision)
    if decision.get('version') != VERSION or db.get(LearningReward, previous.id):
        return
    gap = (datetime.fromisoformat(now()) - datetime.fromisoformat(previous.updated_at)).total_seconds()
    before, after = reviewed_rate(previous), reviewed_rate(current)
    if before is None or after is None or not 0 <= gap <= 14 * 86400:
        return
    db.add(LearningReward(decision_id=previous.id, outcome_id=current.id, language=current.language, reward=.5 + .5 * (before - after), before_rate=before, after_rate=after))
    db.flush()


def history(db, language):
    result = []
    for reward in db.exec(select(LearningReward).where(LearningReward.language == language).order_by(LearningReward.created_at)).all():
        row = db.get(ReadingSession, reward.decision_id)
        if row and row.decision:
            decision = json.loads(row.decision)
            if decision.get('version') == VERSION:
                result.append((decision, reward.reward))
    return result


def features(row, comparison, records):
    draft = json.loads(row.draft)
    checked = bool(draft.get('transcript_reviewed') and comparison)
    n = max(1, comparison['reference_words']) if comparison else 1
    differences = [d for d in comparison['differences'] if d['id'] not in draft.get('dismissed',[])] if checked else []
    values = [1., min(1., comparison['word_difference_rate']) if checked else 0.,
              sum(d['kind'] == 'skipped' for d in differences)/n,
              sum(d['kind'] == 'added' for d in differences)/n,
              min(1., len(records)/50), float(np.mean([r for _, r in records[-5:]])) if records else .5,
              min(1., len(tokenize(BY_ID[row.passage_id]['text'], row.language))/200), float(checked)]
    return values


def action_distribution(policy, x, records, fixed):
    if policy == 'fixed':
        return {a: float(a == fixed) for a in ACTIONS}, {}
    scores = {}
    for action in ACTIONS:
        examples = [(np.asarray(d['features']), r) for d, r in records if d['action_key'] == action]
        if policy == 'epsilon':
            scores[action] = (sum(r for _, r in examples) + .5) / (len(examples) + 1)
        else:
            matrix, vector = np.eye(len(x)), np.zeros(len(x))
            for context, reward in examples:
                matrix += np.outer(context, context)
                vector += context * reward
            direction = np.linalg.solve(matrix, x)
            scores[action] = float(np.dot(x, np.linalg.solve(matrix, vector)) + ALPHA * np.sqrt(max(0, np.dot(x, direction))))
    best = [a for a in ACTIONS if abs(scores[a] - max(scores.values())) < 1e-12]
    return {a: EPSILON/len(ACTIONS) + ((1-EPSILON)/len(best) if a in best else 0.) for a in ACTIONS}, scores


def choose(db, row, comparison, rng=None):
    rng = rng or random.SystemRandom()
    if not json.loads(row.draft).get('transcript_reviewed'):
        comparison = None
    settle_previous(db, row)
    records = history(db, row.language)
    x = features(row, comparison, records)
    fixed = fixed_action(json.loads(row.draft), comparison) + ':supported'
    policies = ('fixed', 'epsilon', 'linucb')
    distributions = {p: action_distribution(p, x, records, fixed) for p in policies}
    randomized = row.selection_mode == 'learning-comparison'
    policy = rng.choice(policies) if randomized else row.selection_mode.removeprefix('learning-')
    conditional, scores = distributions[policy]
    probabilities = {a: sum(distributions[p][0][a] for p in policies)/3 for a in ACTIONS} if randomized else conditional
    action = rng.choices(ACTIONS, weights=[conditional[a] for a in ACTIONS])[0]
    kind, level = action.split(':')
    return {'version': VERSION, 'policy': policy, 'language': row.language, 'action': kind, 'action_key': action,
            'support_level': level, 'features': x, 'feature_names': FEATURES, 'action_set': ACTIONS,
            'probabilities': probabilities, 'action_probability': probabilities[action],
            'conditional_probabilities': conditional, 'arm_probability': 1/3 if randomized else 1.,
            'scores': scores, 'observed_rewards': len(records), 'reward_definition': REWARD,
            'epsilon': EPSILON if policy != 'fixed' else 0., 'alpha': ALPHA, 'selection_mode': row.selection_mode,
            'evaluation': False, 'created_at': now()}


def export_records(db, language):
    """No audio or transcript in the OPE export. One DB is one learner cluster."""
    result = []
    rewards = {r.decision_id: r for r in db.exec(select(LearningReward).where(LearningReward.language == language)).all()}
    for row in db.exec(select(ReadingSession).where(ReadingSession.language == language)).all():
        d = json.loads(row.decision) if row.decision else {}
        if d.get('version') == VERSION:
            reward = rewards.get(row.id)
            result.append({'id': row.id, 'participant': 'local-learner', 'language': language, 'version': VERSION,
                           'features': d['features'], 'action': d['action_key'], 'behavior': d['probabilities'],
                           'reward': reward.reward if reward else None, 'reward_definition': REWARD})
    return result