File size: 8,818 Bytes
4437ddb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
"""Small portable development classifier and extractive evidence selector."""
import argparse
from collections import Counter
import json
import math
from pathlib import Path
import re

from methods import LABELS

ROOT = Path(__file__).parent
FEATURE = re.compile(r"\b[^\W_]+\b", re.UNICODE)
SENTENCE = re.compile(r"\S.*?(?:[.!?](?=\s|$)|(?=\n)|$)", re.S)


def features(text, channel):
    tokens = FEATURE.findall(text.casefold())
    counts = Counter(f"{channel}:w:{value}" for value in tokens)
    counts.update(f"{channel}:b:{a} {b}" for a, b in zip(tokens, tokens[1:]))
    return counts


def inputs(text, context, with_context):
    result = features(text, "p")
    if with_context:
        result.update(features(context, "c"))
    return result


def candidates(text, context):
    for segment, value in (("passage",text),("context",context)):
        for match in SENTENCE.finditer(value):
            yield {"segment":segment,"start":match.start(),"end":match.end(),"quote":match.group()}


def rank_features(candidate, label):
    return features(candidate["quote"], f'{label}:{candidate["segment"]}')


def scores(head, feature_counts):
    vocabulary = head["vocabulary"]
    observed = [(vocabulary[key], value) for key,value in feature_counts.items() if key in vocabulary]
    if not observed:
        return None
    norm = math.sqrt(sum(value * value for _,value in observed))
    raw = [intercept + sum(row[index] * value / norm for index,value in observed)
           for row,intercept in zip(head["weights"],head["intercepts"],strict=True)]
    terms = [math.exp(v - max(raw)) for v in raw]
    total = sum(terms)
    return {label: value / total for label,value in zip(head["classes"],terms,strict=True)}


class PortableModel:
    max_chars = 6000

    def __init__(self, artifact):
        self.model = json.loads(Path(artifact).read_text(encoding="utf-8"))
        self.revision = self.model["revision"]

    def predict(self, text, context="", kind="with_context"):
        if not isinstance(text,str) or not isinstance(context,str) or not text.strip():
            raise ValueError("Passage must be non-empty text and context must be text")
        if max(len(text),len(context)) > self.max_chars:
            raise ValueError("Passage and context are limited to 6,000 Unicode characters each")
        result = {"model_revision":self.revision,"architecture":kind,"decision":None,
                  "status":"abstained","scores":None,"evidence":None,
                  "annotation_status":"experimental_synthetic_development"}
        probs = scores(self.model[kind],inputs(text,context,kind=="with_context"))
        if not probs:
            result["reason"]="no_known_features"
            return result
        winner = max(probs,key=probs.get)
        result["scores"]=probs
        if probs[winner] < self.model["decision_threshold"]:
            result["reason"]="low_uncalibrated_score"
            return result
        if winner == "insufficient_context":
            result["reason"]="insufficient_context"
            return result
        result.update(status="ok",decision=winner)
        chosen = None
        best = self.model["evidence_threshold"]
        for candidate in candidates(text,context if kind=="with_context" else ""):
            probability = scores(self.model["extractor"],rank_features(candidate,winner))
            if probability and probability["eligible"] > best:
                chosen,best = candidate,probability["eligible"]
        if chosen:
            result["evidence"]=chosen
        return result


def fit_head(samples, labels):
    from sklearn.feature_extraction import DictVectorizer
    from sklearn.linear_model import LogisticRegression
    from sklearn.preprocessing import normalize

    vectorizer=DictVectorizer()
    matrix=normalize(vectorizer.fit_transform(samples))
    learner=LogisticRegression(C=8.0, max_iter=500,random_state=1729).fit(matrix,labels)
    coefficients=learner.coef_
    intercepts=learner.intercept_
    if len(learner.classes_) == 2:
        coefficients=[-coefficients[0]/2,coefficients[0]/2]
        intercepts=[-intercepts[0]/2,intercepts[0]/2]
    return {"vocabulary": vectorizer.vocabulary_, "classes":list(learner.classes_),
            "weights":[row.tolist() for row in coefficients],
            "intercepts":[float(value) for value in intercepts]}


def overlap(candidate, reference):
    if not candidate or candidate["segment"] != reference["segment"]:
        return 0.0
    shared = max(0,min(candidate["end"],reference["end"])-max(candidate["start"],reference["start"]))
    union = max(candidate["end"],reference["end"])-min(candidate["start"],reference["start"])
    return shared/union


def evaluate(model, rows, kind):
    from sklearn.metrics import f1_score
    by_event = {}
    labeled = []
    for row in rows:
        result=model.predict(row["text"],row["context"],kind)
        # An explicit insufficient-context response is a meaningful predicted
        # class; a confidence or vocabulary abstention stays unclassified.
        decision=result["decision"] or ("insufficient_context" if result.get("reason")=="insufficient_context" else "abstained")
        score = overlap(result["evidence"],row["reference_span"])
        labeled.append({"unit_id":row["unit_id"],"event_id":row["event_id"],"family":row["family"],
                        "reference":row["label"],"decision":decision,"exact_span":score==1.0,
                        "overlap":score,**{key:result[key] for key in ("status","evidence","scores")}})
        if row["family"]=="context_flip":
            by_event.setdefault(row["event_id"],[]).append(decision==row["label"])
    eligible_spans=[row for row in labeled if row["reference"]!="insufficient_context"]
    return {
        "rows":len(labeled),"events":len({row["event_id"] for row in rows}),
        "macro_f1":float(f1_score([row["reference"] for row in labeled],
                                   [row["decision"] for row in labeled],labels=list(LABELS),average="macro",zero_division=0)),
        "coverage":sum(row["decision"]!="abstained" for row in labeled)/len(labeled),
        "paired_context_switches":len(by_event),
        "paired_both_correct":sum(len(x)==2 and all(x) for x in by_event.values()),
        "correct_decision_exact_evidence":sum(row["exact_span"] and row["reference"]==row["decision"] for row in eligible_spans),
        "evidence_denominator":len(eligible_spans),"outputs":labeled,
    }


def train(data, out):
    import pyarrow.parquet as pq
    from build_data import json_file
    from methods import canonical_sha
    tr=pq.read_table(data/"train.parquet").to_pylist()
    va=pq.read_table(data/"validation.parquet").to_pylist()
    te=pq.read_table(data/"development_test.parquet").to_pylist()
    parts=[{row["event_id"] for row in split} for split in (tr,va,te)]
    if any(parts[a] & parts[b] for a,b in ((0,1),(0,2),(1,2))):
        raise ValueError("Event leakage across splits")
    model={
        "revision":"0.1.0","training_data_sha256":canonical_sha(tr),
        "decision_threshold":.45,"evidence_threshold":.50,
        "passage_only":fit_head([inputs(row["text"],"",False) for row in tr],[row["label"] for row in tr]),
        "with_context":fit_head([inputs(row["text"],row["context"],True) for row in tr],[row["label"] for row in tr]),
    }
    samples, labels = [],[]
    for row in tr:
        if row["label"]=="insufficient_context":
            continue
        for candidate in candidates(row["text"],row["context"]):
            samples.append(rank_features(candidate,row["label"]))
            labels.append("eligible" if overlap(candidate,row["reference_span"])>=.5 else "ineligible")
    model["extractor"]=fit_head(samples,labels)
    out.mkdir(parents=True,exist_ok=True)
    json_file(out/"model.json",model)
    portable=PortableModel(out/"model.json")
    report={split:{kind:evaluate(portable,rows,kind) for kind in ("passage_only","with_context")}
            for split,rows in (("validation",va),("development_test",te))}
    report["data_status"]="Fictional template families and AI-provisional decisions. Development results only."
    report["training_groups"]=[len(part) for part in parts]
    report["threshold_policy"]="Fixed during implementation at 0.45 for the classifier and 0.50 for the span selector. Scores are uncalibrated."
    json_file(out/"evaluation.json",report)
    for kind,metrics in report["development_test"].items():
        print(kind,{k:v for k,v in metrics.items() if k!="outputs"})


if __name__=="__main__":
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--data",type=Path,default=ROOT/"work")
    parser.add_argument("--out",type=Path,default=ROOT/"work")
    args=parser.parse_args()
    train(args.data,args.out)