sharada 0.1.0.dev0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sharada/__init__.py +31 -0
- sharada/calibrate.py +115 -0
- sharada/data.py +105 -0
- sharada/evaluate.py +105 -0
- sharada/layout.py +78 -0
- sharada/masking.py +48 -0
- sharada/model.py +167 -0
- sharada/policy.py +100 -0
- sharada/train.py +125 -0
- sharada-0.1.0.dev0.dist-info/METADATA +223 -0
- sharada-0.1.0.dev0.dist-info/RECORD +13 -0
- sharada-0.1.0.dev0.dist-info/WHEEL +4 -0
- sharada-0.1.0.dev0.dist-info/licenses/LICENSE +201 -0
sharada/__init__.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Sharada — typed decisions from text in one forward pass.
|
|
2
|
+
|
|
3
|
+
from sharada import DecisionModel
|
|
4
|
+
|
|
5
|
+
model = DecisionModel.from_pretrained("LenaBarretta/sharada-base")
|
|
6
|
+
d = model.decide("My card hasn't arrived yet",
|
|
7
|
+
"Which team should handle this?",
|
|
8
|
+
["billing", "technical", "sales"])
|
|
9
|
+
d.answer, d.confidence
|
|
10
|
+
|
|
11
|
+
The model reads the text, the question and every option in one pass and returns a probability for each
|
|
12
|
+
option. Every option is a branch of the sequence starting at the same position, so their order cannot
|
|
13
|
+
change the answer; an option reads the text, the question and itself, so its score does not depend on
|
|
14
|
+
which other options are offered.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from .calibrate import calibrate, check_passport, fit_temperature, save_passport
|
|
18
|
+
from .data import Example, Request
|
|
19
|
+
from .evaluate import calibration_error, evaluate, latency, risk_coverage
|
|
20
|
+
from .layout import Limits
|
|
21
|
+
from .model import Config, Decision, DecisionModel
|
|
22
|
+
from .policy import Action, Policy, escalation_budget
|
|
23
|
+
from .train import fit
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
"DecisionModel", "Config", "Decision", "Request", "Example", "Limits",
|
|
27
|
+
"fit", "calibrate", "fit_temperature", "save_passport", "check_passport",
|
|
28
|
+
"evaluate", "calibration_error", "risk_coverage", "latency",
|
|
29
|
+
"Policy", "Action", "escalation_budget",
|
|
30
|
+
]
|
|
31
|
+
__version__ = "0.1.0.dev0"
|
sharada/calibrate.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""Calibration, and the passport that says where it holds.
|
|
2
|
+
|
|
3
|
+
A model is not calibrated in general; it is calibrated on a distribution, and it goes stale when the
|
|
4
|
+
traffic moves. So fitting a temperature also writes a passport: what it was fitted on, how far off the
|
|
5
|
+
probabilities were, and what should make you fit it again.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import datetime as dt
|
|
11
|
+
import json
|
|
12
|
+
import math
|
|
13
|
+
import pathlib
|
|
14
|
+
|
|
15
|
+
from .data import Example
|
|
16
|
+
|
|
17
|
+
VALID_DAYS = 90
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _negative_log_likelihood(log_probabilities: list[list[float]], labels: list[int], temperature: float) -> float:
|
|
21
|
+
total = 0.0
|
|
22
|
+
for row, label in zip(log_probabilities, labels):
|
|
23
|
+
scaled = [v / temperature for v in row]
|
|
24
|
+
top = max(scaled)
|
|
25
|
+
total += -(scaled[label] - (top + math.log(sum(math.exp(v - top) for v in scaled))))
|
|
26
|
+
return total / len(labels)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def fit_temperature(probabilities: list[list[float]], labels: list[int],
|
|
30
|
+
grid: tuple[float, float, int] = (0.25, 8.0, 61)) -> float:
|
|
31
|
+
"""One number per task: divide the scores by it. Chosen to minimise the log loss on held-out
|
|
32
|
+
answers, which is what a temperature can honestly be chosen on."""
|
|
33
|
+
low, high, steps = grid
|
|
34
|
+
log_probabilities = [[math.log(max(p, 1e-12)) for p in row] for row in probabilities]
|
|
35
|
+
candidates = [math.exp(math.log(low) + (math.log(high) - math.log(low)) * i / (steps - 1)) for i in range(steps)]
|
|
36
|
+
return min(candidates, key=lambda t: _negative_log_likelihood(log_probabilities, labels, t))
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def fingerprint(model, examples: list[Example]) -> dict:
|
|
40
|
+
"""What the examples looked like, so a later drift is visible."""
|
|
41
|
+
out: dict[str, dict] = {}
|
|
42
|
+
for task in sorted({e.task for e in examples}):
|
|
43
|
+
subset = [e for e in examples if e.task == task]
|
|
44
|
+
lengths = sorted(len(model.layout(e.text, e.question, e.options).ids) for e in subset)
|
|
45
|
+
counts: dict[str, int] = {}
|
|
46
|
+
for e in subset:
|
|
47
|
+
counts[e.options[e.label]] = counts.get(e.options[e.label], 0) + 1
|
|
48
|
+
out[task] = {"n": len(subset), "options": subset[0].options,
|
|
49
|
+
"median_tokens": lengths[len(lengths) // 2],
|
|
50
|
+
"answers": counts}
|
|
51
|
+
return out
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def calibrate(model, examples: list[Example], batch_size: int = 32, valid_days: int = VALID_DAYS) -> dict:
|
|
55
|
+
"""Fit one temperature per task on these examples and return the passport. The temperatures are
|
|
56
|
+
stored on the model, so `decide` uses them from then on."""
|
|
57
|
+
from .evaluate import evaluate
|
|
58
|
+
|
|
59
|
+
raw = model.probabilities(examples, batch_size=batch_size, calibrated=False)
|
|
60
|
+
for task in sorted({e.task for e in examples}):
|
|
61
|
+
index = [i for i, e in enumerate(examples) if e.task == task]
|
|
62
|
+
model.config.temperatures[task] = fit_temperature([raw[i] for i in index],
|
|
63
|
+
[examples[i].label for i in index])
|
|
64
|
+
measured = evaluate(model, examples, batch_size=batch_size, calibrated=True)
|
|
65
|
+
today = dt.date.today()
|
|
66
|
+
return {
|
|
67
|
+
"created": today.isoformat(),
|
|
68
|
+
"valid_until": (today + dt.timedelta(days=valid_days)).isoformat(),
|
|
69
|
+
"encoder": model.config.encoder,
|
|
70
|
+
"examples": len(examples),
|
|
71
|
+
"temperatures": dict(model.config.temperatures),
|
|
72
|
+
"fingerprint": fingerprint(model, examples),
|
|
73
|
+
"calibration_error": measured["calibration_error"],
|
|
74
|
+
"calibration_error_interval": measured["calibration_error_interval"],
|
|
75
|
+
"accuracy": measured["accuracy"],
|
|
76
|
+
"reliability": measured["reliability"],
|
|
77
|
+
"risk_coverage": measured["risk_coverage"],
|
|
78
|
+
"recalibrate_if": {
|
|
79
|
+
"after": "valid_until",
|
|
80
|
+
"options_change": True,
|
|
81
|
+
"median_tokens_shift": 0.5, # half as long, or twice as long
|
|
82
|
+
},
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def save_passport(passport: dict, path: str | pathlib.Path) -> pathlib.Path:
|
|
87
|
+
path = pathlib.Path(path)
|
|
88
|
+
path.write_text(json.dumps(passport, indent=1))
|
|
89
|
+
return path
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def check_passport(passport: dict, examples: list[Example] | None = None, model=None,
|
|
93
|
+
today: dt.date | None = None) -> list[str]:
|
|
94
|
+
"""What is wrong with trusting these probabilities today. An empty list means nothing found —
|
|
95
|
+
run it in the deployment pipeline and fail the build on anything it returns."""
|
|
96
|
+
today = today or dt.date.today()
|
|
97
|
+
problems = []
|
|
98
|
+
if today.isoformat() > passport["valid_until"]:
|
|
99
|
+
problems.append(f"the calibration expired on {passport['valid_until']}; fit it again on recent answers")
|
|
100
|
+
if passport["examples"] < 200:
|
|
101
|
+
problems.append(f"fitted on {passport['examples']} answers — the interval on the calibration error is wide")
|
|
102
|
+
if examples and model:
|
|
103
|
+
now = fingerprint(model, examples)
|
|
104
|
+
for task, then in passport["fingerprint"].items():
|
|
105
|
+
if task not in now:
|
|
106
|
+
continue
|
|
107
|
+
if now[task]["options"] != then["options"]:
|
|
108
|
+
problems.append(f"{task}: the options have changed since the calibration")
|
|
109
|
+
ratio = now[task]["median_tokens"] / max(then["median_tokens"], 1)
|
|
110
|
+
if ratio < 0.5 or ratio > 2:
|
|
111
|
+
problems.append(f"{task}: texts are now {ratio:.1f}× the length they were calibrated on")
|
|
112
|
+
for task in now:
|
|
113
|
+
if task not in passport["fingerprint"]:
|
|
114
|
+
problems.append(f"{task}: never calibrated — its probabilities are raw")
|
|
115
|
+
return problems
|
sharada/data.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""Requests, examples and batches."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import random
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
|
|
8
|
+
import torch
|
|
9
|
+
|
|
10
|
+
from .layout import FIRST_OPTION, Laid, Layout
|
|
11
|
+
|
|
12
|
+
KINDS = ("choice", "scale", "binary") # unordered labels, an ordered scale, yes or no
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass
|
|
16
|
+
class Request:
|
|
17
|
+
"""One question about one text."""
|
|
18
|
+
|
|
19
|
+
text: str
|
|
20
|
+
question: str
|
|
21
|
+
options: list[str]
|
|
22
|
+
kind: str = "choice"
|
|
23
|
+
task: str = "task" # a name, so temperatures can be fitted per task
|
|
24
|
+
|
|
25
|
+
def __post_init__(self):
|
|
26
|
+
if self.kind not in KINDS:
|
|
27
|
+
raise ValueError(f"kind must be one of {KINDS}, got {self.kind!r}")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass
|
|
31
|
+
class Example(Request):
|
|
32
|
+
"""A request whose answer is known: `label` is the index of the right option."""
|
|
33
|
+
|
|
34
|
+
label: int = 0
|
|
35
|
+
|
|
36
|
+
def __post_init__(self):
|
|
37
|
+
super().__post_init__()
|
|
38
|
+
if not 0 <= self.label < len(self.options):
|
|
39
|
+
raise ValueError(f"label {self.label} is outside the {len(self.options)} options")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass
|
|
43
|
+
class Batch:
|
|
44
|
+
ids: torch.Tensor
|
|
45
|
+
positions: torch.Tensor
|
|
46
|
+
segments: torch.Tensor
|
|
47
|
+
present: torch.Tensor # [batch, options] — which option slots are real
|
|
48
|
+
kinds: torch.Tensor
|
|
49
|
+
n_options: torch.Tensor
|
|
50
|
+
labels: torch.Tensor | None = None
|
|
51
|
+
tasks: list[str] = field(default_factory=list)
|
|
52
|
+
width: int = 0 # the widest number of options in this batch
|
|
53
|
+
|
|
54
|
+
def to(self, device) -> "Batch":
|
|
55
|
+
move = lambda v: v.to(device) if torch.is_tensor(v) else v
|
|
56
|
+
return Batch(move(self.ids), move(self.positions), move(self.segments), move(self.present),
|
|
57
|
+
move(self.kinds), move(self.n_options), move(self.labels), self.tasks, self.width)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def collate(laid: list[Laid], requests: list[Request], pad_id: int) -> Batch:
|
|
61
|
+
length = max(len(l) for l in laid)
|
|
62
|
+
width = max(l.n_options for l in laid)
|
|
63
|
+
n = len(laid)
|
|
64
|
+
ids = torch.full((n, length), pad_id, dtype=torch.long)
|
|
65
|
+
positions = torch.zeros((n, length), dtype=torch.long)
|
|
66
|
+
segments = torch.full((n, length), -1, dtype=torch.long)
|
|
67
|
+
for i, l in enumerate(laid):
|
|
68
|
+
k = len(l)
|
|
69
|
+
ids[i, :k] = torch.tensor(l.ids)
|
|
70
|
+
positions[i, :k] = torch.tensor(l.positions)
|
|
71
|
+
segments[i, :k] = torch.tensor(l.segments)
|
|
72
|
+
counts = torch.tensor([l.n_options for l in laid])
|
|
73
|
+
labels = None
|
|
74
|
+
if all(isinstance(r, Example) for r in requests):
|
|
75
|
+
labels = torch.tensor([r.label for r in requests])
|
|
76
|
+
return Batch(ids=ids, positions=positions, segments=segments,
|
|
77
|
+
present=torch.arange(width)[None] < counts[:, None],
|
|
78
|
+
kinds=torch.tensor([KINDS.index(r.kind) for r in requests]),
|
|
79
|
+
n_options=counts, labels=labels, tasks=[r.task for r in requests], width=width)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def batches(requests: list[Request], layout: Layout, batch_size: int, pad_id: int,
|
|
83
|
+
shuffle: bool = False, seed: int = 0):
|
|
84
|
+
"""Mini-batches. When shuffling, requests of similar length travel together, so a batch of short
|
|
85
|
+
questions is not padded out to the length of one with sixty options."""
|
|
86
|
+
order = list(range(len(requests)))
|
|
87
|
+
laid = [layout(r.text, r.question, r.options) for r in requests]
|
|
88
|
+
if shuffle:
|
|
89
|
+
rng = random.Random(seed)
|
|
90
|
+
rng.shuffle(order)
|
|
91
|
+
window = batch_size * 50
|
|
92
|
+
order = [j for w in range(0, len(order), window)
|
|
93
|
+
for j in sorted(order[w:w + window], key=lambda j: len(laid[j]))]
|
|
94
|
+
chunks = [order[i:i + batch_size] for i in range(0, len(order), batch_size)]
|
|
95
|
+
if shuffle:
|
|
96
|
+
random.Random(seed + 1).shuffle(chunks)
|
|
97
|
+
for chunk in chunks:
|
|
98
|
+
yield chunk, collate([laid[j] for j in chunk], [requests[j] for j in chunk], pad_id)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def option_mass(segments: torch.Tensor, states: torch.Tensor, width: int) -> torch.Tensor:
|
|
102
|
+
"""Mean of each option's own final token states -> [batch, options, hidden]."""
|
|
103
|
+
index = FIRST_OPTION + torch.arange(width, device=states.device)
|
|
104
|
+
member = (segments[:, :, None] == index[None, None, :]).to(states.dtype)
|
|
105
|
+
return torch.einsum("blk,bld->bkd", member, states) / member.sum(1).clamp(min=1)[..., None]
|
sharada/evaluate.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""Measuring a decision model: the answer, the stated number, and the whole distribution."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
import random
|
|
7
|
+
import time
|
|
8
|
+
|
|
9
|
+
from .data import Example
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _bands(confidence: list[float], n: int) -> list[int]:
|
|
13
|
+
return [min(int(c * n), n - 1) for c in confidence]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def calibration_error(confidence: list[float], correct: list[int], bands: int = 15) -> float:
|
|
17
|
+
"""The average gap between the probability stated and how often it turns out right, over equal
|
|
18
|
+
bands, weighted by how many answers fall in each. Zero means this estimate finds no gap — on a
|
|
19
|
+
finite sample that is not proof of none."""
|
|
20
|
+
index = _bands(confidence, bands)
|
|
21
|
+
total = 0.0
|
|
22
|
+
for b in range(bands):
|
|
23
|
+
inside = [i for i, j in enumerate(index) if j == b]
|
|
24
|
+
if inside:
|
|
25
|
+
said = sum(confidence[i] for i in inside) / len(inside)
|
|
26
|
+
was = sum(correct[i] for i in inside) / len(inside)
|
|
27
|
+
total += len(inside) / len(confidence) * abs(said - was)
|
|
28
|
+
return total
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def calibration_interval(confidence: list[float], correct: list[int], bands: int = 15,
|
|
32
|
+
draws: int = 200, seed: int = 0) -> tuple[float, float]:
|
|
33
|
+
"""A bootstrap interval for the calibration error — on a few hundred answers it is wide, and
|
|
34
|
+
saying so is the point."""
|
|
35
|
+
rng = random.Random(seed)
|
|
36
|
+
n = len(confidence)
|
|
37
|
+
values = []
|
|
38
|
+
for _ in range(draws):
|
|
39
|
+
pick = [rng.randrange(n) for _ in range(n)]
|
|
40
|
+
values.append(calibration_error([confidence[i] for i in pick], [correct[i] for i in pick], bands))
|
|
41
|
+
values.sort()
|
|
42
|
+
return values[int(0.025 * draws)], values[int(0.975 * draws) - 1]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def reliability_curve(confidence: list[float], correct: list[int], bands: int = 10) -> list[dict]:
|
|
46
|
+
index = _bands(confidence, bands)
|
|
47
|
+
curve = []
|
|
48
|
+
for b in range(bands):
|
|
49
|
+
inside = [i for i, j in enumerate(index) if j == b]
|
|
50
|
+
curve.append({"from": b / bands, "n": len(inside),
|
|
51
|
+
"stated": sum(confidence[i] for i in inside) / len(inside) if inside else None,
|
|
52
|
+
"observed": sum(correct[i] for i in inside) / len(inside) if inside else None})
|
|
53
|
+
return curve
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def risk_coverage(confidence: list[float], correct: list[int], steps: int = 20) -> list[dict]:
|
|
57
|
+
"""Answer only where the model is surest: what accuracy, at what share of the traffic."""
|
|
58
|
+
order = sorted(range(len(confidence)), key=lambda i: -confidence[i])
|
|
59
|
+
out = []
|
|
60
|
+
for k in range(1, steps + 1):
|
|
61
|
+
take = max(1, round(len(order) * k / steps))
|
|
62
|
+
kept = [correct[i] for i in order[:take]]
|
|
63
|
+
out.append({"coverage": take / len(order), "accuracy": sum(kept) / len(kept),
|
|
64
|
+
"threshold": confidence[order[take - 1]]})
|
|
65
|
+
return out
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def evaluate(model, examples: list[Example], batch_size: int = 32, calibrated: bool = True) -> dict:
|
|
69
|
+
"""Everything above, on one set of labelled examples."""
|
|
70
|
+
probabilities = model.probabilities(examples, batch_size=batch_size, calibrated=calibrated)
|
|
71
|
+
confidence, correct, true_p, squared = [], [], [], []
|
|
72
|
+
for p, e in zip(probabilities, examples):
|
|
73
|
+
best = max(range(len(p)), key=p.__getitem__)
|
|
74
|
+
confidence.append(p[best])
|
|
75
|
+
correct.append(int(best == e.label))
|
|
76
|
+
true_p.append(p[e.label])
|
|
77
|
+
squared.append(sum((q - (1.0 if i == e.label else 0.0)) ** 2 for i, q in enumerate(p)))
|
|
78
|
+
low, high = calibration_interval(confidence, correct)
|
|
79
|
+
return {"n": len(examples),
|
|
80
|
+
"accuracy": sum(correct) / len(correct),
|
|
81
|
+
"mean_confidence": sum(confidence) / len(confidence),
|
|
82
|
+
"calibration_error": calibration_error(confidence, correct),
|
|
83
|
+
"calibration_error_interval": [low, high],
|
|
84
|
+
"log_loss": sum(-math.log(max(p, 1e-9)) for p in true_p) / len(true_p),
|
|
85
|
+
"brier": sum(squared) / len(squared),
|
|
86
|
+
"reliability": reliability_curve(confidence, correct),
|
|
87
|
+
"risk_coverage": risk_coverage(confidence, correct)}
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def latency(model, request, batch_size: int = 1, repeats: int = 20) -> dict:
|
|
91
|
+
"""Milliseconds per call and per question, as the model is loaded right now."""
|
|
92
|
+
import torch
|
|
93
|
+
|
|
94
|
+
requests = [request] * batch_size
|
|
95
|
+
for _ in range(3):
|
|
96
|
+
model.probabilities(requests, batch_size=batch_size)
|
|
97
|
+
if next(model.parameters()).is_cuda:
|
|
98
|
+
torch.cuda.synchronize()
|
|
99
|
+
start = time.time()
|
|
100
|
+
for _ in range(repeats):
|
|
101
|
+
model.probabilities(requests, batch_size=batch_size)
|
|
102
|
+
if next(model.parameters()).is_cuda:
|
|
103
|
+
torch.cuda.synchronize()
|
|
104
|
+
per_call = (time.time() - start) / repeats * 1e3
|
|
105
|
+
return {"batch": batch_size, "ms_per_call": per_call, "ms_per_question": per_call / batch_size}
|
sharada/layout.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""One request, laid out as one sequence.
|
|
2
|
+
|
|
3
|
+
position: 0 1 … n n+1 n+2 … m m+1 │ m+2 … │ m+2 …
|
|
4
|
+
token: [CLS] the text [SEP] question [SEP]│ option 0 [SEP] │ option 1 [SEP]
|
|
5
|
+
|
|
6
|
+
Every option is a branch of its own and every branch starts at the same position, the one right after
|
|
7
|
+
the question. The encoder's positions are rotary, so to it no option is earlier or later than another:
|
|
8
|
+
the order of the options cannot change their scores. `masking.who_reads_whom` then decides who may read
|
|
9
|
+
whom; together the two give the properties the model is built on.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import functools
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
|
|
17
|
+
TEXT = 0
|
|
18
|
+
QUESTION = 1
|
|
19
|
+
FIRST_OPTION = 2 # option i has segment FIRST_OPTION + i
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class Limits:
|
|
24
|
+
"""How many tokens each part of a request may use."""
|
|
25
|
+
|
|
26
|
+
text: int = 256
|
|
27
|
+
question: int = 48
|
|
28
|
+
option: int = 12
|
|
29
|
+
|
|
30
|
+
def as_dict(self) -> dict:
|
|
31
|
+
return {"text": self.text, "question": self.question, "option": self.option}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass
|
|
35
|
+
class Laid:
|
|
36
|
+
"""A request turned into token ids, position ids and one segment per token."""
|
|
37
|
+
|
|
38
|
+
ids: list[int]
|
|
39
|
+
positions: list[int]
|
|
40
|
+
segments: list[int]
|
|
41
|
+
n_options: int
|
|
42
|
+
option_start: int = field(default=0)
|
|
43
|
+
|
|
44
|
+
def __len__(self) -> int:
|
|
45
|
+
return len(self.ids)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class Layout:
|
|
49
|
+
"""Lays requests out for one tokenizer. Token ids of repeated strings — option names, instructions,
|
|
50
|
+
the same text asked about twice — are cached, which is most of the cost of preparing a batch."""
|
|
51
|
+
|
|
52
|
+
def __init__(self, tokenizer, limits: Limits | None = None):
|
|
53
|
+
self.tokenizer = tokenizer
|
|
54
|
+
self.limits = limits or Limits()
|
|
55
|
+
self._ids = functools.lru_cache(maxsize=100_000)(self._encode)
|
|
56
|
+
|
|
57
|
+
def _encode(self, text: str) -> tuple[int, ...]:
|
|
58
|
+
return tuple(self.tokenizer(text, add_special_tokens=False)["input_ids"])
|
|
59
|
+
|
|
60
|
+
def __call__(self, text: str, question: str, options: list[str]) -> Laid:
|
|
61
|
+
if len(options) < 2:
|
|
62
|
+
raise ValueError("a decision needs at least two options")
|
|
63
|
+
cls_id, sep_id = self.tokenizer.cls_token_id, self.tokenizer.sep_token_id
|
|
64
|
+
body = list(self._ids(text))[: self.limits.text]
|
|
65
|
+
ask = list(self._ids(question))[: self.limits.question]
|
|
66
|
+
|
|
67
|
+
ids = [cls_id] + body + [sep_id] + ask + [sep_id]
|
|
68
|
+
segments = [TEXT] * (len(body) + 2) + [QUESTION] * (len(ask) + 1)
|
|
69
|
+
positions = list(range(len(ids)))
|
|
70
|
+
|
|
71
|
+
start = len(ids)
|
|
72
|
+
for i, option in enumerate(options):
|
|
73
|
+
tokens = list(self._ids(" " + option))[: self.limits.option] + [sep_id]
|
|
74
|
+
ids += tokens
|
|
75
|
+
segments += [FIRST_OPTION + i] * len(tokens)
|
|
76
|
+
positions += range(start, start + len(tokens)) # every option restarts here
|
|
77
|
+
return Laid(ids=ids, positions=positions, segments=segments, n_options=len(options),
|
|
78
|
+
option_start=start)
|
sharada/masking.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Who reads whom.
|
|
2
|
+
|
|
3
|
+
The text reads only the text, so its states do not depend on the question or the options — a text asked
|
|
4
|
+
several questions could be read once. The question reads the text and itself. An option reads the text,
|
|
5
|
+
the question and its own tokens, and nothing else: with seventy-seven options on offer, each one still
|
|
6
|
+
sees only the message and itself, and its score does not depend on which other options came along.
|
|
7
|
+
|
|
8
|
+
`read_each_other=True` keeps the other behaviour — options that also read one another — which is what
|
|
9
|
+
this model was first trained with. On label sets of a few options it costs nothing; on seventy-seven it
|
|
10
|
+
cost thirty points of accuracy, which is why it is not the default.
|
|
11
|
+
|
|
12
|
+
The encoder's local-attention layers only look a fixed distance away, and the distance is measured in
|
|
13
|
+
positions, so an option sees the end of the question the same way wherever it sits in the sequence.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import torch
|
|
19
|
+
|
|
20
|
+
from .layout import QUESTION, TEXT
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def who_reads_whom(segments: torch.Tensor, positions: torch.Tensor, local_reach: int,
|
|
24
|
+
read_each_other: bool = False) -> tuple[torch.Tensor, torch.Tensor]:
|
|
25
|
+
"""-> two [batch, length, length] boolean masks: for the global layers and for the local ones.
|
|
26
|
+
True at (i, j) means query token i may read key token j."""
|
|
27
|
+
q, k = segments[:, :, None], segments[:, None, :]
|
|
28
|
+
real = k >= 0 # padding is not a key
|
|
29
|
+
context = (k == TEXT) | (k == QUESTION)
|
|
30
|
+
options_see = real if read_each_other else (context | (k == q))
|
|
31
|
+
full = torch.where(q == TEXT, k == TEXT, torch.where(q == QUESTION, context, options_see)) & real
|
|
32
|
+
full = full | torch.eye(segments.size(1), dtype=torch.bool, device=segments.device)[None]
|
|
33
|
+
near = (positions[:, :, None] - positions[:, None, :]).abs() <= local_reach
|
|
34
|
+
return full, full & near
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def encoder_masks(segments: torch.Tensor, positions: torch.Tensor, local_reach: int,
|
|
38
|
+
attn_implementation: str, dtype: torch.dtype, read_each_other: bool = False) -> dict:
|
|
39
|
+
"""The masks in the form the encoder expects: booleans for fused attention, an additive float mask
|
|
40
|
+
for the plain implementation."""
|
|
41
|
+
out = {}
|
|
42
|
+
names = ("full_attention", "sliding_attention")
|
|
43
|
+
for name, allowed in zip(names, who_reads_whom(segments, positions, local_reach, read_each_other)):
|
|
44
|
+
mask = allowed[:, None]
|
|
45
|
+
if attn_implementation == "eager":
|
|
46
|
+
mask = torch.zeros(mask.shape, dtype=dtype, device=mask.device).masked_fill(~mask, torch.finfo(dtype).min)
|
|
47
|
+
out[name] = mask
|
|
48
|
+
return out
|
sharada/model.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""The decision model: an encoder, a small read-out, one number per option."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import pathlib
|
|
7
|
+
from dataclasses import asdict, dataclass, field
|
|
8
|
+
|
|
9
|
+
import torch
|
|
10
|
+
import torch.nn as nn
|
|
11
|
+
|
|
12
|
+
from .data import Batch, Example, Request, batches, collate, option_mass
|
|
13
|
+
from .layout import Laid, Layout, Limits
|
|
14
|
+
|
|
15
|
+
DEFAULT_ENCODER = "answerdotai/ModernBERT-base"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass
|
|
19
|
+
class Config:
|
|
20
|
+
encoder: str = DEFAULT_ENCODER
|
|
21
|
+
limits: dict = field(default_factory=lambda: Limits().as_dict())
|
|
22
|
+
local_reach: int | None = None # taken from the encoder when left out
|
|
23
|
+
read_each_other: bool = False # options reading one another; off by default, see masking.py
|
|
24
|
+
temperatures: dict = field(default_factory=dict) # per task, fitted by `calibrate`
|
|
25
|
+
version: int = 1
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class Decision:
|
|
30
|
+
"""What the model answers, and how sure it says it is."""
|
|
31
|
+
|
|
32
|
+
answer: str
|
|
33
|
+
index: int
|
|
34
|
+
probabilities: dict[str, float]
|
|
35
|
+
confidence: float
|
|
36
|
+
|
|
37
|
+
def __repr__(self) -> str:
|
|
38
|
+
return f"Decision({self.answer!r}, confidence={self.confidence:.3f})"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class DecisionModel(nn.Module):
|
|
42
|
+
def __init__(self, config: Config | None = None, tokenizer=None, encoder=None):
|
|
43
|
+
super().__init__()
|
|
44
|
+
from transformers import AutoModel, AutoTokenizer
|
|
45
|
+
|
|
46
|
+
self.config = config or Config()
|
|
47
|
+
self.tokenizer = tokenizer or AutoTokenizer.from_pretrained(self.config.encoder)
|
|
48
|
+
self.attn = "eager" if not torch.cuda.is_available() else "sdpa"
|
|
49
|
+
self.encoder = encoder or AutoModel.from_pretrained(self.config.encoder, attn_implementation=self.attn)
|
|
50
|
+
hidden = self.encoder.config.hidden_size
|
|
51
|
+
self.read = nn.Sequential(nn.Linear(2 * hidden, hidden), nn.GELU(), nn.LayerNorm(hidden),
|
|
52
|
+
nn.Linear(hidden, 1))
|
|
53
|
+
if self.config.local_reach is None:
|
|
54
|
+
self.config.local_reach = getattr(self.encoder.config, "local_attention", 128) // 2
|
|
55
|
+
self.layout = Layout(self.tokenizer, Limits(**self.config.limits))
|
|
56
|
+
|
|
57
|
+
# ── the forward pass ──────────────────────────────────────────────────────────────────────
|
|
58
|
+
def forward(self, batch: Batch) -> torch.Tensor:
|
|
59
|
+
"""-> [batch, options] scores; options that do not exist cannot win."""
|
|
60
|
+
from .masking import encoder_masks
|
|
61
|
+
|
|
62
|
+
dtype = self.encoder.embeddings.tok_embeddings.weight.dtype
|
|
63
|
+
masks = encoder_masks(batch.segments, batch.positions, self.config.local_reach,
|
|
64
|
+
self.attn, dtype, self.config.read_each_other)
|
|
65
|
+
states = self.encoder(input_ids=batch.ids, position_ids=batch.positions,
|
|
66
|
+
attention_mask=masks).last_hidden_state
|
|
67
|
+
options = option_mass(batch.segments, states, batch.width)
|
|
68
|
+
summary = states[:, :1].expand(-1, batch.width, -1)
|
|
69
|
+
scores = self.read(torch.cat([options, options * summary], -1)).squeeze(-1).float()
|
|
70
|
+
return scores.masked_fill(~batch.present, -1e4)
|
|
71
|
+
|
|
72
|
+
# ── asking it things ──────────────────────────────────────────────────────────────────────
|
|
73
|
+
@torch.no_grad()
|
|
74
|
+
def probabilities(self, requests: list[Request], batch_size: int = 32,
|
|
75
|
+
calibrated: bool = True) -> list[list[float]]:
|
|
76
|
+
"""One distribution over the options of each request, in the order they were given."""
|
|
77
|
+
self.eval()
|
|
78
|
+
device = next(self.parameters()).device
|
|
79
|
+
out: list[list[float]] = [[] for _ in requests]
|
|
80
|
+
for chunk, batch in batches(requests, self.layout, batch_size, self.tokenizer.pad_token_id):
|
|
81
|
+
scores = self(batch.to(device))
|
|
82
|
+
for row, j in enumerate(chunk):
|
|
83
|
+
k = int(batch.n_options[row])
|
|
84
|
+
z = scores[row, :k].float().cpu()
|
|
85
|
+
if calibrated:
|
|
86
|
+
z = z / self.temperature_for(requests[j])
|
|
87
|
+
out[j] = torch.softmax(z, -1).tolist()
|
|
88
|
+
return out
|
|
89
|
+
|
|
90
|
+
def decide(self, text: str, question: str, options: list[str], kind: str = "choice",
|
|
91
|
+
task: str = "task", calibrated: bool = True) -> Decision:
|
|
92
|
+
"""One decision, start to finish."""
|
|
93
|
+
request = Request(text=text, question=question, options=options, kind=kind, task=task)
|
|
94
|
+
return self.decide_many([request], calibrated=calibrated)[0]
|
|
95
|
+
|
|
96
|
+
def decide_many(self, requests: list[Request], batch_size: int = 32,
|
|
97
|
+
calibrated: bool = True) -> list[Decision]:
|
|
98
|
+
decisions = []
|
|
99
|
+
for request, probabilities in zip(requests, self.probabilities(requests, batch_size, calibrated)):
|
|
100
|
+
best = max(range(len(probabilities)), key=probabilities.__getitem__)
|
|
101
|
+
decisions.append(Decision(answer=request.options[best], index=best,
|
|
102
|
+
probabilities=dict(zip(request.options, probabilities)),
|
|
103
|
+
confidence=probabilities[best]))
|
|
104
|
+
return decisions
|
|
105
|
+
|
|
106
|
+
def temperature_for(self, request: Request) -> float:
|
|
107
|
+
return float(self.config.temperatures.get(request.task, 1.0))
|
|
108
|
+
|
|
109
|
+
# ── saving and loading ────────────────────────────────────────────────────────────────────
|
|
110
|
+
def save(self, path: str | pathlib.Path) -> pathlib.Path:
|
|
111
|
+
from safetensors.torch import save_file
|
|
112
|
+
|
|
113
|
+
path = pathlib.Path(path)
|
|
114
|
+
path.mkdir(parents=True, exist_ok=True)
|
|
115
|
+
save_file({k: v.contiguous() for k, v in self.state_dict().items()}, path / "model.safetensors")
|
|
116
|
+
(path / "config.json").write_text(json.dumps(asdict(self.config), indent=1))
|
|
117
|
+
self.tokenizer.save_pretrained(path)
|
|
118
|
+
return path
|
|
119
|
+
|
|
120
|
+
@classmethod
|
|
121
|
+
def from_pretrained(cls, path: str | pathlib.Path, device: str | None = None) -> "DecisionModel":
|
|
122
|
+
"""A local directory saved by `save`, or a model id on the Hub."""
|
|
123
|
+
from safetensors.torch import load_file
|
|
124
|
+
from transformers import AutoConfig, AutoModel, AutoTokenizer
|
|
125
|
+
|
|
126
|
+
local = pathlib.Path(path)
|
|
127
|
+
if not local.is_dir():
|
|
128
|
+
from huggingface_hub import snapshot_download
|
|
129
|
+
|
|
130
|
+
local = pathlib.Path(snapshot_download(str(path)))
|
|
131
|
+
config = Config(**json.loads((local / "config.json").read_text()))
|
|
132
|
+
tokenizer = AutoTokenizer.from_pretrained(local)
|
|
133
|
+
attn = "eager" if not torch.cuda.is_available() else "sdpa"
|
|
134
|
+
encoder = AutoModel.from_config(AutoConfig.from_pretrained(config.encoder), attn_implementation=attn)
|
|
135
|
+
model = cls(config=config, tokenizer=tokenizer, encoder=encoder)
|
|
136
|
+
model.load_state_dict(load_file(local / "model.safetensors"))
|
|
137
|
+
return model.to(device or ("cuda" if torch.cuda.is_available() else "cpu"))
|
|
138
|
+
|
|
139
|
+
def push_to_hub(self, repo_id: str, private: bool = False) -> str:
|
|
140
|
+
"""Upload to the Hub. The token comes from the environment; this never asks for one."""
|
|
141
|
+
import tempfile
|
|
142
|
+
|
|
143
|
+
from huggingface_hub import HfApi
|
|
144
|
+
|
|
145
|
+
api = HfApi()
|
|
146
|
+
api.create_repo(repo_id, private=private, exist_ok=True)
|
|
147
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
148
|
+
self.save(tmp)
|
|
149
|
+
api.upload_folder(folder_path=tmp, repo_id=repo_id)
|
|
150
|
+
return f"https://huggingface.co/{repo_id}"
|
|
151
|
+
|
|
152
|
+
# ── training lives in train.py, calibration in calibrate.py ───────────────────────────────
|
|
153
|
+
def fit(self, examples: list[Example], **kwargs):
|
|
154
|
+
from .train import fit
|
|
155
|
+
|
|
156
|
+
return fit(self, examples, **kwargs)
|
|
157
|
+
|
|
158
|
+
def calibrate(self, examples: list[Example], **kwargs):
|
|
159
|
+
from .calibrate import calibrate
|
|
160
|
+
|
|
161
|
+
return calibrate(self, examples, **kwargs)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def encode_one(model: DecisionModel, request: Request) -> tuple[Laid, Batch]:
|
|
165
|
+
"""Handy in tests: one request, laid out and collated."""
|
|
166
|
+
laid = model.layout(request.text, request.question, request.options)
|
|
167
|
+
return laid, collate([laid], [request], model.tokenizer.pad_token_id)
|
sharada/policy.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""What to do with 0.94.
|
|
2
|
+
|
|
3
|
+
A probability is not a decision. The decision depends on what each mistake costs and on what it costs
|
|
4
|
+
to hand the case to a person or to a bigger model. Give those costs and the rule is arithmetic: take the
|
|
5
|
+
action with the smallest expected loss, and abstain when abstaining costs less than any of them.
|
|
6
|
+
|
|
7
|
+
policy = Policy(options=["approve", "reject"],
|
|
8
|
+
costs={("fraud", "approve"): 10_000, ("clean", "reject"): 100},
|
|
9
|
+
escalate=30)
|
|
10
|
+
policy.act(decision.probabilities)
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
|
|
17
|
+
ESCALATE = "escalate"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class Action:
|
|
22
|
+
kind: str # "answer" or "escalate"
|
|
23
|
+
answer: str | None
|
|
24
|
+
expected_loss: float
|
|
25
|
+
margin: float # how much better than the next best course of action
|
|
26
|
+
|
|
27
|
+
def __repr__(self) -> str:
|
|
28
|
+
what = self.answer if self.kind == "answer" else "escalate"
|
|
29
|
+
return f"Action({what!r}, expected_loss={self.expected_loss:.2f})"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass
|
|
33
|
+
class Policy:
|
|
34
|
+
"""Costs are given per (true option, chosen option) pair; anything not named costs `wrong` when the
|
|
35
|
+
answer is wrong and nothing when it is right."""
|
|
36
|
+
|
|
37
|
+
options: list[str]
|
|
38
|
+
costs: dict[tuple[str, str], float] = field(default_factory=dict)
|
|
39
|
+
wrong: float = 1.0
|
|
40
|
+
escalate: float | None = None
|
|
41
|
+
|
|
42
|
+
def loss(self, true_option: str, chosen: str) -> float:
|
|
43
|
+
if true_option == chosen:
|
|
44
|
+
return float(self.costs.get((true_option, chosen), 0.0))
|
|
45
|
+
return float(self.costs.get((true_option, chosen), self.wrong))
|
|
46
|
+
|
|
47
|
+
def expected_losses(self, probabilities: dict[str, float]) -> dict[str, float]:
|
|
48
|
+
"""What each course of action is expected to cost, under the model's own probabilities."""
|
|
49
|
+
out = {chosen: sum(p * self.loss(true_option, chosen) for true_option, p in probabilities.items())
|
|
50
|
+
for chosen in self.options}
|
|
51
|
+
if self.escalate is not None:
|
|
52
|
+
out[ESCALATE] = float(self.escalate)
|
|
53
|
+
return out
|
|
54
|
+
|
|
55
|
+
def act(self, probabilities: dict[str, float]) -> Action:
|
|
56
|
+
losses = self.expected_losses(probabilities)
|
|
57
|
+
ranked = sorted(losses.items(), key=lambda kv: kv[1])
|
|
58
|
+
(best, loss), (_, second) = ranked[0], ranked[1]
|
|
59
|
+
if best == ESCALATE:
|
|
60
|
+
return Action(kind=ESCALATE, answer=None, expected_loss=loss, margin=second - loss)
|
|
61
|
+
return Action(kind="answer", answer=best, expected_loss=loss, margin=second - loss)
|
|
62
|
+
|
|
63
|
+
# ── choosing how much to take on ──────────────────────────────────────────────────────────
|
|
64
|
+
def coverage(self, probabilities: list[dict[str, float]]) -> float:
|
|
65
|
+
"""The share of these requests the model would answer itself."""
|
|
66
|
+
answered = sum(1 for p in probabilities if self.act(p).kind == "answer")
|
|
67
|
+
return answered / len(probabilities)
|
|
68
|
+
|
|
69
|
+
def realised_loss(self, probabilities: list[dict[str, float]], truths: list[str]) -> dict:
|
|
70
|
+
"""What this policy would actually have cost on labelled data — the number to compare policies
|
|
71
|
+
on, and the one that goes wrong when the probabilities are not honest."""
|
|
72
|
+
total, answered, mistakes = 0.0, 0, 0
|
|
73
|
+
for p, truth in zip(probabilities, truths):
|
|
74
|
+
action = self.act(p)
|
|
75
|
+
if action.kind == ESCALATE:
|
|
76
|
+
total += float(self.escalate or 0.0)
|
|
77
|
+
continue
|
|
78
|
+
answered += 1
|
|
79
|
+
total += self.loss(truth, action.answer)
|
|
80
|
+
mistakes += action.answer != truth
|
|
81
|
+
n = len(truths)
|
|
82
|
+
return {"loss_per_request": total / n, "coverage": answered / n,
|
|
83
|
+
"accuracy_when_answering": (answered - mistakes) / answered if answered else float("nan")}
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def escalation_budget(policy: Policy, probabilities: list[dict[str, float]], budget: float) -> Policy:
|
|
87
|
+
"""Escalating everything the model is unsure about only works while there is someone to escalate to.
|
|
88
|
+
Given a budget — the share of requests that may be handed over — this returns the policy that keeps
|
|
89
|
+
to it: the cost of escalating is raised until few enough cases are worth escalating."""
|
|
90
|
+
if policy.escalate is None:
|
|
91
|
+
raise ValueError("this policy never escalates; give it an `escalate` cost first")
|
|
92
|
+
low, high = 0.0, max(policy.wrong, policy.escalate) * 100
|
|
93
|
+
for _ in range(40):
|
|
94
|
+
middle = (low + high) / 2
|
|
95
|
+
trial = Policy(policy.options, policy.costs, policy.wrong, middle)
|
|
96
|
+
if 1 - trial.coverage(probabilities) > budget:
|
|
97
|
+
low = middle # too many escalations: make escalating dearer
|
|
98
|
+
else:
|
|
99
|
+
high = middle
|
|
100
|
+
return Policy(policy.options, policy.costs, policy.wrong, high)
|
sharada/train.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"""Fine-tuning on your own labelled examples.
|
|
2
|
+
|
|
3
|
+
Three lines should get you a usable model:
|
|
4
|
+
|
|
5
|
+
model = DecisionModel.from_pretrained("LenaBarretta/sharada-base")
|
|
6
|
+
report = model.fit(examples)
|
|
7
|
+
model.save("my-router")
|
|
8
|
+
|
|
9
|
+
`fit` holds a part of the examples out, trains on the rest, stops when the held-out log loss stops
|
|
10
|
+
improving, then fits one temperature per task on that same held-out part and writes a calibration
|
|
11
|
+
passport. What comes back is a report of what it did and how well it ended up.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import math
|
|
17
|
+
import random
|
|
18
|
+
import time
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
|
|
21
|
+
import torch
|
|
22
|
+
import torch.nn as nn
|
|
23
|
+
import torch.nn.functional as F
|
|
24
|
+
|
|
25
|
+
from .data import Example, batches
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class Report:
|
|
30
|
+
examples: int
|
|
31
|
+
held_out: int
|
|
32
|
+
epochs: float
|
|
33
|
+
minutes: float
|
|
34
|
+
accuracy: float
|
|
35
|
+
log_loss: float
|
|
36
|
+
calibration_error: float
|
|
37
|
+
temperatures: dict
|
|
38
|
+
passport: dict
|
|
39
|
+
|
|
40
|
+
def __repr__(self) -> str:
|
|
41
|
+
return (f"Report({self.examples} examples, accuracy {self.accuracy:.3f}, "
|
|
42
|
+
f"log loss {self.log_loss:.3f}, calibration error {self.calibration_error:.3f})")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def brier_loss(scores: torch.Tensor, batch) -> torch.Tensor:
|
|
46
|
+
"""The squared error over all options; for a scale, over the cumulative distribution."""
|
|
47
|
+
probabilities = torch.softmax(scores, -1) * batch.present
|
|
48
|
+
truth = F.one_hot(batch.labels, scores.size(-1)).to(probabilities.dtype) * batch.present
|
|
49
|
+
flat = ((probabilities - truth) ** 2 * batch.present).sum(-1)
|
|
50
|
+
ranked = (((probabilities.cumsum(-1) - truth.cumsum(-1)) ** 2) * batch.present).sum(-1) / (batch.n_options - 1).clamp(min=1)
|
|
51
|
+
return torch.where(batch.kinds == 1, ranked, flat).mean()
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def fit(model, examples: list[Example], *, val_split: float = 0.2, max_epochs: int = 10,
|
|
55
|
+
batch_size: int = 16, lr: float = 2e-5, patience: int = 2, loss: str = "cross_entropy",
|
|
56
|
+
freeze_encoder: bool = False, seed: int = 0, device: str | None = None,
|
|
57
|
+
progress: bool = True) -> Report:
|
|
58
|
+
if len(examples) < 20:
|
|
59
|
+
raise ValueError("fine-tuning needs at least 20 examples; below that, use the model as it is")
|
|
60
|
+
device = device or ("cuda" if torch.cuda.is_available() else "cpu")
|
|
61
|
+
model.to(device)
|
|
62
|
+
|
|
63
|
+
rng = random.Random(seed)
|
|
64
|
+
order = list(range(len(examples)))
|
|
65
|
+
rng.shuffle(order)
|
|
66
|
+
cut = max(10, int(len(examples) * val_split))
|
|
67
|
+
held_out = [examples[i] for i in order[:cut]]
|
|
68
|
+
training = [examples[i] for i in order[cut:]]
|
|
69
|
+
|
|
70
|
+
for parameter in model.encoder.parameters():
|
|
71
|
+
parameter.requires_grad = not freeze_encoder
|
|
72
|
+
trainable = [p for p in model.parameters() if p.requires_grad]
|
|
73
|
+
optimizer = torch.optim.AdamW(trainable, lr=lr, weight_decay=0.01)
|
|
74
|
+
steps = max_epochs * math.ceil(len(training) / batch_size)
|
|
75
|
+
schedule = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr=lr, total_steps=steps + 1, pct_start=0.1)
|
|
76
|
+
scaler = torch.amp.GradScaler("cuda", enabled=device.startswith("cuda"))
|
|
77
|
+
loss_fn = brier_loss if loss == "brier" else None
|
|
78
|
+
|
|
79
|
+
best, best_state, waited, start, epochs_done = math.inf, None, 0, time.time(), 0
|
|
80
|
+
for epoch in range(max_epochs):
|
|
81
|
+
model.train()
|
|
82
|
+
for _, batch in batches(training, model.layout, batch_size, model.tokenizer.pad_token_id,
|
|
83
|
+
shuffle=True, seed=seed + epoch):
|
|
84
|
+
batch = batch.to(device)
|
|
85
|
+
with torch.amp.autocast("cuda", dtype=torch.float16, enabled=device.startswith("cuda")):
|
|
86
|
+
scores = model(batch)
|
|
87
|
+
step_loss = loss_fn(scores, batch) if loss_fn else F.cross_entropy(scores, batch.labels)
|
|
88
|
+
optimizer.zero_grad(set_to_none=True)
|
|
89
|
+
scaler.scale(step_loss).backward()
|
|
90
|
+
scaler.unscale_(optimizer)
|
|
91
|
+
nn.utils.clip_grad_norm_(trainable, 1.0)
|
|
92
|
+
scaler.step(optimizer)
|
|
93
|
+
scaler.update()
|
|
94
|
+
schedule.step()
|
|
95
|
+
epochs_done = epoch + 1
|
|
96
|
+
|
|
97
|
+
current = _log_loss(model, held_out, batch_size)
|
|
98
|
+
if progress:
|
|
99
|
+
print(f"epoch {epochs_done}: held-out log loss {current:.4f}", flush=True)
|
|
100
|
+
if current < best - 1e-4:
|
|
101
|
+
best, waited = current, 0
|
|
102
|
+
best_state = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
|
|
103
|
+
else:
|
|
104
|
+
waited += 1
|
|
105
|
+
if waited >= patience:
|
|
106
|
+
break
|
|
107
|
+
if best_state is not None:
|
|
108
|
+
model.load_state_dict(best_state)
|
|
109
|
+
model.to(device)
|
|
110
|
+
|
|
111
|
+
from .calibrate import calibrate
|
|
112
|
+
|
|
113
|
+
passport = calibrate(model, held_out, batch_size=batch_size)
|
|
114
|
+
from .evaluate import evaluate
|
|
115
|
+
|
|
116
|
+
scores = evaluate(model, held_out, batch_size=batch_size)
|
|
117
|
+
return Report(examples=len(examples), held_out=len(held_out), epochs=epochs_done,
|
|
118
|
+
minutes=(time.time() - start) / 60, accuracy=scores["accuracy"],
|
|
119
|
+
log_loss=scores["log_loss"], calibration_error=scores["calibration_error"],
|
|
120
|
+
temperatures=dict(model.config.temperatures), passport=passport)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _log_loss(model, examples: list[Example], batch_size: int) -> float:
|
|
124
|
+
probabilities = model.probabilities(examples, batch_size=batch_size, calibrated=False)
|
|
125
|
+
return float(sum(-math.log(max(p[e.label], 1e-9)) for p, e in zip(probabilities, examples)) / len(examples))
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: sharada
|
|
3
|
+
Version: 0.1.0.dev0
|
|
4
|
+
Summary: Typed decisions from text in one forward pass — options in the request, calibrated probabilities, easy to fine-tune.
|
|
5
|
+
Project-URL: Homepage, https://github.com/LenaBarretta/sharada
|
|
6
|
+
Project-URL: Article, https://lenatriestounderstand.com/notes/llm/024-rlcr/
|
|
7
|
+
Author: Lena Barretta
|
|
8
|
+
License-Expression: Apache-2.0
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: calibration,decision-making,text-classification,uncertainty,zero-shot-classification
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Intended Audience :: Science/Research
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
16
|
+
Requires-Python: >=3.10
|
|
17
|
+
Requires-Dist: huggingface-hub>=0.26
|
|
18
|
+
Requires-Dist: safetensors>=0.4
|
|
19
|
+
Requires-Dist: torch>=2.2
|
|
20
|
+
Requires-Dist: transformers==5.12.1
|
|
21
|
+
Provides-Extra: train
|
|
22
|
+
Requires-Dist: datasets>=4; extra == 'train'
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
|
|
25
|
+
<p align="center">
|
|
26
|
+
<img src="docs/logo.png" alt="Sharada" width="200">
|
|
27
|
+
</p>
|
|
28
|
+
|
|
29
|
+
<h1 align="center">Sharada</h1>
|
|
30
|
+
|
|
31
|
+
<p align="center">
|
|
32
|
+
<em>Typed decisions about text in one forward pass — options in the request, calibrated probabilities out.</em>
|
|
33
|
+
</p>
|
|
34
|
+
|
|
35
|
+
<p align="center">
|
|
36
|
+
<a href="https://github.com/LenaBarretta/sharada/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-Apache%202.0-blue.svg" alt="Apache 2.0"></a>
|
|
37
|
+
<a href="https://huggingface.co/LenaBarretta/sharada-base"><img src="https://img.shields.io/badge/%F0%9F%A4%97-sharada--base-yellow" alt="sharada-base on the Hub"></a>
|
|
38
|
+
<a href="https://lenatriestounderstand.com/notes/llm/024-rlcr/"><img src="https://img.shields.io/badge/write--up-lenatriestounderstand-ff69b4" alt="the write-up"></a>
|
|
39
|
+
</p>
|
|
40
|
+
|
|
41
|
+
A small encoder that makes **typed decisions about text in one forward pass**: the options come with the
|
|
42
|
+
request, and what comes back is a probability for each of them. Nothing is generated, nothing is parsed,
|
|
43
|
+
and the same model answers a question it has never seen because the labels are part of the input rather
|
|
44
|
+
than part of the weights.
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
from sharada import DecisionModel
|
|
48
|
+
|
|
49
|
+
model = DecisionModel.from_pretrained("LenaBarretta/sharada-base")
|
|
50
|
+
|
|
51
|
+
d = model.decide(
|
|
52
|
+
text="My card still hasn't arrived and I ordered it two weeks ago.",
|
|
53
|
+
question="Which team should handle this?",
|
|
54
|
+
options=["billing", "card delivery", "technical support", "account closure"],
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
d.answer # 'card delivery'
|
|
58
|
+
d.confidence # 0.86
|
|
59
|
+
d.probabilities # {'billing': 0.07, 'card delivery': 0.86, ...}
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Three kinds of question are typed, so the model knows what the options mean:
|
|
63
|
+
|
|
64
|
+
| kind | the options are | example |
|
|
65
|
+
| --- | --- | --- |
|
|
66
|
+
| `choice` | unordered labels | which team, which topic, which intent |
|
|
67
|
+
| `scale` | ordered steps | severity 1–5, how positive, how urgent |
|
|
68
|
+
| `binary` | yes or no | is this spam, does this need a human |
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
from sharada import Request
|
|
72
|
+
|
|
73
|
+
model.decide_many([
|
|
74
|
+
Request(text=review, question="How positive is this review?",
|
|
75
|
+
options=["very negative", "negative", "neutral", "positive", "very positive"],
|
|
76
|
+
kind="scale", task="review-tone"),
|
|
77
|
+
Request(text=review, question="Does this mention a refund?",
|
|
78
|
+
options=["no", "yes"], kind="binary", task="refund-flag"),
|
|
79
|
+
])
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
## Install
|
|
83
|
+
|
|
84
|
+
```bash
|
|
85
|
+
pip install git+https://github.com/LenaBarretta/sharada
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
Python 3.10+, `torch` and `transformers`; CPU is enough to run it.
|
|
89
|
+
|
|
90
|
+
## Models
|
|
91
|
+
|
|
92
|
+
| model | encoder | parameters | what it is for |
|
|
93
|
+
| --- | --- | --- | --- |
|
|
94
|
+
| `LenaBarretta/sharada-base` | ModernBERT-base | 150M | the default; fine-tune this one |
|
|
95
|
+
| `LenaBarretta/sharada-large` | ModernBERT-large | 400M | a few points better, ~2.5× the time |
|
|
96
|
+
|
|
97
|
+
Accuracy and calibration per label set are in each model card, measured on label sets the model was
|
|
98
|
+
**not** trained on as well as on the ones it was.
|
|
99
|
+
|
|
100
|
+
## Three things the architecture guarantees
|
|
101
|
+
|
|
102
|
+
The request is laid out as one sequence — text, question, then every option as a parallel branch — and a
|
|
103
|
+
mask decides who may read whom. Both are in [`layout.py`](sharada/layout.py) and
|
|
104
|
+
[`masking.py`](sharada/masking.py), and they buy three properties that hold by construction, not because
|
|
105
|
+
training got them approximately right:
|
|
106
|
+
|
|
107
|
+
1. **The order of the options cannot matter.** Every option branch starts at the same position id, and
|
|
108
|
+
the encoder's positions are rotary, so no option is earlier or later than another. Reshuffle them and
|
|
109
|
+
the probabilities follow their options exactly.
|
|
110
|
+
2. **An option's score does not depend on which other options are offered.** An option reads the text,
|
|
111
|
+
the question and itself, nothing else. Drop two options from a list of four and the remaining two keep
|
|
112
|
+
their scores to the last bit — so the probabilities are a renormalisation, and a long list of options
|
|
113
|
+
does not make each one noisier.
|
|
114
|
+
3. **The text is read once.** Text tokens read only text tokens, so their states do not depend on the
|
|
115
|
+
question. Ten questions about one document are ten cheap read-outs over one encoding of it.
|
|
116
|
+
|
|
117
|
+
These are the tests in [`tests/test_model.py`](tests/test_model.py), checked on an untrained model.
|
|
118
|
+
|
|
119
|
+
## Fine-tune it on your own labels
|
|
120
|
+
|
|
121
|
+
This is what the package is built around: a few hundred labelled examples and a few minutes.
|
|
122
|
+
|
|
123
|
+
```python
|
|
124
|
+
from sharada import DecisionModel, Example
|
|
125
|
+
|
|
126
|
+
examples = [
|
|
127
|
+
Example(text="the invoice is wrong again", question="Which team should handle this?",
|
|
128
|
+
options=["billing", "technical", "sales"], label=0, task="routing"),
|
|
129
|
+
...
|
|
130
|
+
]
|
|
131
|
+
|
|
132
|
+
model = DecisionModel.from_pretrained("LenaBarretta/sharada-base")
|
|
133
|
+
report = model.fit(examples) # holds out 20%, stops when held-out log loss stops improving
|
|
134
|
+
model.save("my-router")
|
|
135
|
+
|
|
136
|
+
report # Report(820 examples, accuracy 0.914, log loss 0.287, calibration error 0.031)
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
`fit` keeps a part of the examples out, trains on the rest, early-stops, then fits one temperature per
|
|
140
|
+
task on the held-out part and writes a calibration passport. Useful arguments:
|
|
141
|
+
|
|
142
|
+
| argument | default | |
|
|
143
|
+
| --- | --- | --- |
|
|
144
|
+
| `loss` | `"cross_entropy"` | `"brier"` scores the whole distribution, not just the right option |
|
|
145
|
+
| `freeze_encoder` | `False` | train the read-out only: seconds, and enough for a few hundred examples |
|
|
146
|
+
| `batch_size`, `lr`, `max_epochs`, `patience` | `16`, `2e-5`, `10`, `2` | |
|
|
147
|
+
|
|
148
|
+
Mixing several tasks in one `fit` is the normal case — give each one its own `task` name and each gets
|
|
149
|
+
its own temperature. See [`examples/finetune_your_own.py`](examples/finetune_your_own.py), which trains
|
|
150
|
+
on a CSV.
|
|
151
|
+
|
|
152
|
+
## The number next to the answer is supposed to be true
|
|
153
|
+
|
|
154
|
+
`0.86` should mean right about 86% of the time. That is a property of a distribution, not of a model, so
|
|
155
|
+
it is fitted and it expires:
|
|
156
|
+
|
|
157
|
+
```python
|
|
158
|
+
from sharada import check_passport, save_passport
|
|
159
|
+
|
|
160
|
+
passport = model.calibrate(recent_examples) # one temperature per task
|
|
161
|
+
save_passport(passport, "passport.json")
|
|
162
|
+
|
|
163
|
+
check_passport(passport, recent_examples, model)
|
|
164
|
+
# ['the calibration expired on 2026-04-01; fit it again on recent answers',
|
|
165
|
+
# 'routing: the options have changed since the calibration']
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
`check_passport` returns an empty list when it finds nothing wrong — run it in the deployment pipeline
|
|
169
|
+
and fail the build on anything it returns. `evaluate` gives accuracy, log loss, Brier, expected
|
|
170
|
+
calibration error with a bootstrap interval, a reliability curve and a risk–coverage curve.
|
|
171
|
+
|
|
172
|
+
## What to do with 0.86
|
|
173
|
+
|
|
174
|
+
A probability is not a decision. `Policy` turns one into the action that costs the least, including
|
|
175
|
+
handing the request to a person:
|
|
176
|
+
|
|
177
|
+
```python
|
|
178
|
+
from sharada import Policy, escalation_budget
|
|
179
|
+
|
|
180
|
+
policy = Policy(options=["approve", "reject"],
|
|
181
|
+
costs={("fraud", "approve"): 10_000, ("clean", "reject"): 100},
|
|
182
|
+
escalate=30)
|
|
183
|
+
|
|
184
|
+
policy.act({"fraud": 0.1, "clean": 0.9}) # Action('answer', 'reject', expected_loss=90.0)
|
|
185
|
+
policy.act({"fraud": 0.5, "clean": 0.5}) # Action('escalate', ...)
|
|
186
|
+
|
|
187
|
+
# a person can look at 5% of the traffic, no more:
|
|
188
|
+
policy = escalation_budget(policy, probabilities, budget=0.05)
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
## Train the base models yourself
|
|
192
|
+
|
|
193
|
+
[`training/`](training) has the whole run: a mix of public label sets in
|
|
194
|
+
[`sources.py`](training/sources.py) — intents, topics, sentiment, toxicity, spam, entailment, review
|
|
195
|
+
scores — each one presented with several question phrasings, shuffled options and sampled option
|
|
196
|
+
subsets, so the model learns to read the options rather than their positions. Some label sets are held
|
|
197
|
+
out of training entirely and only measured, which is where the zero-shot numbers come from.
|
|
198
|
+
|
|
199
|
+
```bash
|
|
200
|
+
python training/run.py --encoder answerdotai/ModernBERT-base --out runs/base
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
It checkpoints every few hundred steps and resumes from the checkpoint if it finds one, which is what
|
|
204
|
+
makes it survive a Kaggle session; [`training/kaggle.ipynb`](training/kaggle.ipynb) is the notebook
|
|
205
|
+
wrapper. One free T4: about an hour for base, about three for large.
|
|
206
|
+
|
|
207
|
+
## What it will not do
|
|
208
|
+
|
|
209
|
+
- **It does not generate.** No free-form answers, no extraction, no reasoning out loud. Options or
|
|
210
|
+
nothing.
|
|
211
|
+
- **256 tokens of text** by default (`Limits`), with 48 for the question and 12 per option. Longer
|
|
212
|
+
documents need chunking or a larger limit, and the limit costs quadratic attention.
|
|
213
|
+
- **English.** The encoder is English-only; a multilingual encoder drops in, but the published
|
|
214
|
+
checkpoints are not trained for it.
|
|
215
|
+
- **It is small.** Where a frontier model knows a fact that is not in the text, it wins. This answers
|
|
216
|
+
questions about the text in front of it.
|
|
217
|
+
|
|
218
|
+
## Where it came from
|
|
219
|
+
|
|
220
|
+
The design, the experiments behind it and what each training signal did are written up in
|
|
221
|
+
[RLCR from Scratch](https://lenatriestounderstand.com/notes/llm/024-rlcr/), with a runnable lab.
|
|
222
|
+
|
|
223
|
+
Apache 2.0.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
sharada/__init__.py,sha256=kqs7sBkdNMppeKdGznxvz9jMdiWoMvUNz5yox7OQLj8,1358
|
|
2
|
+
sharada/calibrate.py,sha256=htaw-6roSaSf50RrrsW6DMZFcQAk4re-RX_goieBStM,5425
|
|
3
|
+
sharada/data.py,sha256=Ow5gKtU571DxXDCRcexGPz10ligmV9MSR3MF8A543G0,4170
|
|
4
|
+
sharada/evaluate.py,sha256=GJEiK-MGQxeM74t9F0SGU21oaBrU6VQcJX8tdFgKqz0,4725
|
|
5
|
+
sharada/layout.py,sha256=I0_L1RCZfo26r06cIHic8A0FgTnb1AGTseZIfAiBMwg,2962
|
|
6
|
+
sharada/masking.py,sha256=HG1xSUhUj0DRswzrZ4IU8AOIGuxWR3gF1jYFEtGm8kM,2625
|
|
7
|
+
sharada/model.py,sha256=2xj0BfzXjgxHnD6jZVXJhQlPq5kQSnAQ9tivqELCVMo,8307
|
|
8
|
+
sharada/policy.py,sha256=FbP-cIf5LeF0NfLNTSRy8mcfDzjCqQ49xypIWTyEfy0,4829
|
|
9
|
+
sharada/train.py,sha256=ftGiOQv8rPTRVBBhhKlSaYVfvpt1inOn6ek_cAFgdmI,5283
|
|
10
|
+
sharada-0.1.0.dev0.dist-info/METADATA,sha256=ZUBbEwQ7gJe7EfelwLKFAQRNIGc8fJGwdzl6qDMY528,9821
|
|
11
|
+
sharada-0.1.0.dev0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
12
|
+
sharada-0.1.0.dev0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
|
|
13
|
+
sharada-0.1.0.dev0.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|