simple-score 0.1.0__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.
@@ -0,0 +1,34 @@
1
+ """SIMPLE Score: SImplicity Metric via Preference LEarning.
2
+
3
+ A reference-free learned metric for text simplification. For each (source, candidate)
4
+ pair it returns a quality score ``mu`` in (-1, 1) and the model's uncertainty ``sigma``.
5
+
6
+ >>> from simple_score import SIMPLE
7
+ >>> metric = SIMPLE.from_pretrained("large")
8
+ >>> metric.score(["The feline perched upon the mat."], ["The cat sat on the mat."])
9
+ """
10
+
11
+ from ._version import __version__
12
+ from .losses import (
13
+ bradley_terry_loss,
14
+ gaussian_nll_loss,
15
+ mse_loss,
16
+ preference_probability,
17
+ thurstone_loss,
18
+ )
19
+ from .modeling import SimpleConfig, SimpleModel
20
+ from .scorer import SIMPLE, ScoreOutput, load
21
+
22
+ __all__ = [
23
+ "SIMPLE",
24
+ "ScoreOutput",
25
+ "SimpleConfig",
26
+ "SimpleModel",
27
+ "__version__",
28
+ "bradley_terry_loss",
29
+ "gaussian_nll_loss",
30
+ "load",
31
+ "mse_loss",
32
+ "preference_probability",
33
+ "thurstone_loss",
34
+ ]
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
simple_score/cli.py ADDED
@@ -0,0 +1,155 @@
1
+ """Command line interface: ``simple-score {score,train,build-data}``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import logging
8
+ import sys
9
+ from pathlib import Path
10
+
11
+
12
+ def _read_lines(path: str) -> list[str]:
13
+ return [line.rstrip("\n") for line in Path(path).read_text(encoding="utf-8").splitlines()]
14
+
15
+
16
+ # ----------------------------------------------------------------------------- score
17
+
18
+
19
+ def _cmd_score(args: argparse.Namespace) -> int:
20
+ from .scorer import SIMPLE
21
+
22
+ if args.input:
23
+ from .data.io import read_records
24
+
25
+ rows = read_records(args.input, ["source", "candidate"])
26
+ sources = [r["source"] for r in rows]
27
+ candidates = [r["candidate"] for r in rows]
28
+ else:
29
+ if not (args.sources and args.candidates):
30
+ print("Give --input FILE, or both --sources and --candidates.", file=sys.stderr)
31
+ return 2
32
+ sources, candidates = _read_lines(args.sources), _read_lines(args.candidates)
33
+
34
+ metric = SIMPLE.from_pretrained(args.model, device=args.device, batch_size=args.batch_size)
35
+ out = metric.score(sources, candidates, show_progress=not args.quiet)
36
+ sink = open(args.output, "w", encoding="utf-8") if args.output else sys.stdout
37
+ try:
38
+ for s, c, m, sg in zip(sources, candidates, out.mu, out.sigma):
39
+ sink.write(json.dumps({"source": s, "candidate": c, "mu": round(m, 6),
40
+ "sigma": round(sg, 6)}, ensure_ascii=False) + "\n")
41
+ finally:
42
+ if args.output:
43
+ sink.close()
44
+ print(f"SIMPLE mean score over {len(out)} examples: {out.mean:.4f}", file=sys.stderr)
45
+ return 0
46
+
47
+
48
+ # ----------------------------------------------------------------------------- train / build-data
49
+
50
+
51
+ def _config_from_args(args: argparse.Namespace):
52
+ from .training.config import apply_overrides, config_from_dict, load_config
53
+
54
+ if args.config:
55
+ cfg = load_config(args.config, args.set)
56
+ else:
57
+ data: dict = {}
58
+ for kind in ("parallel", "graded", "preferences"):
59
+ data[kind] = list(getattr(args, kind) or [])
60
+ if args.graded and args.min_level_gap is not None:
61
+ data["graded"] = [{"path": p, "min_level_gap": args.min_level_gap} for p in args.graded]
62
+ if args.ratings:
63
+ if not args.rating_scale:
64
+ raise SystemExit("--ratings needs --rating-scale LOW HIGH (e.g. 0 100)")
65
+ data["ratings"] = [{"path": p, "scale": args.rating_scale} for p in args.ratings]
66
+ raw = apply_overrides({"data": data}, args.set)
67
+ cfg = config_from_dict(raw, base_dir=Path.cwd())
68
+ if getattr(args, "output_dir", None):
69
+ cfg.output_dir = args.output_dir
70
+ if getattr(args, "backbone", None):
71
+ cfg.model.backbone = args.backbone
72
+ return cfg
73
+
74
+
75
+ def _cmd_build_data(args: argparse.Namespace) -> int:
76
+ from .data.builders import DataSpec, build_training_data
77
+ from .training.trainer import export_training_data
78
+
79
+ logging.basicConfig(level=logging.INFO, format="%(message)s")
80
+ cfg = _config_from_args(args)
81
+ spec = DataSpec.from_dict(cfg.data, base_dir=Path(cfg.data_base_dir) if cfg.data_base_dir else None)
82
+ data = build_training_data(spec)
83
+ stats = data.stats()
84
+ if not args.dry_run:
85
+ export_training_data(data, args.output_dir or Path(cfg.output_dir) / "data")
86
+ print(json.dumps(stats, indent=2))
87
+ return 0
88
+
89
+
90
+ def _cmd_train(args: argparse.Namespace) -> int:
91
+ from .training.trainer import train
92
+
93
+ cfg = _config_from_args(args)
94
+ train(cfg)
95
+ return 0
96
+
97
+
98
+ def _add_data_flags(p: argparse.ArgumentParser) -> None:
99
+ p.add_argument("--config", help="YAML config (see configs/). Other data flags are ignored.")
100
+ p.add_argument("--set", action="append", default=[], metavar="KEY=VALUE",
101
+ help="Override a config value, e.g. --set training.lr=2e-5 (repeatable).")
102
+ g = p.add_argument_group("quick data flags (no config file)")
103
+ g.add_argument("--parallel", action="append", metavar="FILE",
104
+ help="(source, simplification) pairs.")
105
+ g.add_argument("--graded", action="append", metavar="FILE",
106
+ help="(source, simplification, level) rows; higher level = simpler.")
107
+ g.add_argument("--min-level-gap", type=float, default=None,
108
+ help="Minimum level difference for inter-simplification pairs (default 1).")
109
+ g.add_argument("--ratings", action="append", metavar="FILE",
110
+ help="(source, candidate, rating) rows; needs --rating-scale.")
111
+ g.add_argument("--rating-scale", type=float, nargs=2, metavar=("LOW", "HIGH"))
112
+ g.add_argument("--preferences", action="append", metavar="FILE",
113
+ help="(source, chosen, rejected[, margin, weight]) rows.")
114
+
115
+
116
+ def build_parser() -> argparse.ArgumentParser:
117
+ parser = argparse.ArgumentParser(
118
+ prog="simple-score",
119
+ description="SIMPLE Score: reference-free text simplification metric with uncertainty.")
120
+ sub = parser.add_subparsers(dest="command", required=True)
121
+
122
+ s = sub.add_parser("score", help="Score simplifications against their sources.")
123
+ s.add_argument("--model", default="large",
124
+ help="small | base | large, a Hub repo id, or a local checkpoint dir.")
125
+ s.add_argument("--input", help="File with source and candidate columns (jsonl/csv/tsv).")
126
+ s.add_argument("--sources", help="Plain-text file, one source sentence per line.")
127
+ s.add_argument("--candidates", help="Plain-text file, one simplification per line.")
128
+ s.add_argument("--output", help="Write JSONL results here (default: stdout).")
129
+ s.add_argument("--batch-size", type=int, default=32)
130
+ s.add_argument("--device", default=None)
131
+ s.add_argument("--quiet", action="store_true")
132
+ s.set_defaults(func=_cmd_score)
133
+
134
+ t = sub.add_parser("train", help="Train a SIMPLE model on your data.")
135
+ _add_data_flags(t)
136
+ t.add_argument("--output-dir")
137
+ t.add_argument("--backbone", help="e.g. microsoft/deberta-v3-base")
138
+ t.set_defaults(func=_cmd_train)
139
+
140
+ b = sub.add_parser("build-data",
141
+ help="Build (and optionally export) the training pairs without training.")
142
+ _add_data_flags(b)
143
+ b.add_argument("--output-dir", help="Where to write the JSONL files.")
144
+ b.add_argument("--dry-run", action="store_true", help="Only print counts.")
145
+ b.set_defaults(func=_cmd_build_data)
146
+ return parser
147
+
148
+
149
+ def main(argv: list[str] | None = None) -> int:
150
+ args = build_parser().parse_args(argv)
151
+ return args.func(args)
152
+
153
+
154
+ if __name__ == "__main__":
155
+ raise SystemExit(main())
@@ -0,0 +1,35 @@
1
+ """Generic data handling: read plain files and derive SIMPLE's training signal."""
2
+
3
+ from .builders import (
4
+ INTER_TYPES,
5
+ KINDS,
6
+ AugmentationOptions,
7
+ DataSpec,
8
+ TrainingData,
9
+ ValidationOptions,
10
+ build_training_data,
11
+ pairs_from_graded,
12
+ pairs_from_parallel,
13
+ pairs_from_preferences,
14
+ pairs_from_ratings,
15
+ rating_targets,
16
+ )
17
+ from .io import DataFormatError, read_records, write_jsonl
18
+
19
+ __all__ = [
20
+ "INTER_TYPES",
21
+ "KINDS",
22
+ "AugmentationOptions",
23
+ "DataFormatError",
24
+ "DataSpec",
25
+ "TrainingData",
26
+ "ValidationOptions",
27
+ "build_training_data",
28
+ "pairs_from_graded",
29
+ "pairs_from_parallel",
30
+ "pairs_from_preferences",
31
+ "pairs_from_ratings",
32
+ "rating_targets",
33
+ "read_records",
34
+ "write_jsonl",
35
+ ]
@@ -0,0 +1,82 @@
1
+ """Synthetic examples that teach SIMPLE where the bottom half of its scale is (paper §4.2).
2
+
3
+ Regression anchors (targets on the (-1, 1) scale):
4
+
5
+ copy (s, s) -> 0.0 doing nothing scores zero
6
+ random_other (s, unrelated) -> -1.0 unrelated text is maximally wrong
7
+ shuffled (s, shuffled words) -> -0.8
8
+ word_dropout (s, ~50% of words) -> -0.5
9
+ truncated (s, first half) -> -0.4
10
+
11
+ and, around human-rated data, flipped pairs ``(candidate, source) -> -target`` for every
12
+ rated simplification with target > 0.1, plus a copy and a cross-source pair per rated source.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import random
18
+ from collections.abc import Sequence
19
+
20
+ ADVERSARIAL_TARGETS = {
21
+ "random_other": -1.0,
22
+ "shuffled": -0.8,
23
+ "word_dropout": -0.5,
24
+ "truncated": -0.4,
25
+ }
26
+
27
+
28
+ def derangement_partner(items: Sequence[str], rng: random.Random) -> dict[str, str]:
29
+ """Map each distinct item to a different item: shuffle, then pair each item with its
30
+ successor in the shuffled order (a single cycle, so never with itself when n > 1)."""
31
+ pool = list(dict.fromkeys(items))
32
+ rng.shuffle(pool)
33
+ return {s: pool[(i + 1) % len(pool)] for i, s in enumerate(pool)}
34
+
35
+
36
+ def copy_anchors(sources: Sequence[str], n: int, seed: int) -> list[dict]:
37
+ """``n`` (source, source) -> 0.0 examples drawn from ``sources``."""
38
+ pool = sorted(set(sources))
39
+ random.Random(seed).shuffle(pool)
40
+ return [{"source": s, "candidate": s, "target": 0.0, "type": "copy"} for s in pool[:n]]
41
+
42
+
43
+ def adversarial_anchors(sources: Sequence[str], n: int, seed: int) -> list[dict]:
44
+ """Up to four degenerate candidates for each of ``n`` sampled sources."""
45
+ rng = random.Random(seed)
46
+ unique = sorted(set(sources))
47
+ rng.shuffle(unique)
48
+ sampled = unique[:n]
49
+ partner = derangement_partner(sampled, rng)
50
+
51
+ out: list[dict] = []
52
+ for src in sampled:
53
+ words = src.split()
54
+ out.append({"source": src, "candidate": partner[src],
55
+ "target": ADVERSARIAL_TARGETS["random_other"], "type": "random_other"})
56
+ if len(words) >= 5:
57
+ w = words[:]
58
+ rng.shuffle(w)
59
+ out.append({"source": src, "candidate": " ".join(w),
60
+ "target": ADVERSARIAL_TARGETS["shuffled"], "type": "shuffled"})
61
+ if len(words) >= 6:
62
+ out.append({"source": src, "candidate": " ".join(words[: max(1, len(words) // 2)]),
63
+ "target": ADVERSARIAL_TARGETS["truncated"], "type": "truncated"})
64
+ if len(words) >= 6:
65
+ kept = [w for w in words if rng.random() > 0.5] or [words[0]]
66
+ out.append({"source": src, "candidate": " ".join(kept),
67
+ "target": ADVERSARIAL_TARGETS["word_dropout"], "type": "word_dropout"})
68
+ return out
69
+
70
+
71
+ def rating_anchors(rated: Sequence[dict], seed: int, flip_threshold: float = 0.1) -> list[dict]:
72
+ """Copy, flipped and cross-source anchors around human-rated examples."""
73
+ sources = sorted({r["source"] for r in rated})
74
+ out = [{"source": s, "candidate": s, "target": 0.0, "type": "copy"} for s in sources]
75
+ for r in rated:
76
+ if r["target"] > flip_threshold:
77
+ out.append({"source": r["candidate"], "candidate": r["source"],
78
+ "target": round(-r["target"], 4), "type": "flipped"})
79
+ partner = derangement_partner(sources, random.Random(seed))
80
+ out.extend({"source": s, "candidate": partner[s], "target": -1.0, "type": "random_other"}
81
+ for s in sources)
82
+ return out