Spaces:
Running
Running
Upload SIMPLE static Space (in-browser demo)
Browse filesFiles changed (8)
- README.md+92-5
- demo.jsAdded+319
- index.html+211-17
- model/manifest.jsonAdded+48
- model/model_quantized.onnxAdded+3
- model/tokenizer.jsonAdded
- model/tokenizer_config.jsonAdded+59
- simple.pyAdded+86
12345678910---title: Simpleemoji: 🌖colorFrom: pinkcolorTo: pinksdk: staticpinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697---title: SIMPLEemoji: 🧩colorFrom: bluecolorTo: greensdk: staticapp_file: index.htmlpinned: falselicense: mittags:- evaluate- metric- text-simplificationdescription: >-SIMPLE: a reference-free learned metric for text simplification that also reports itsown uncertainty.---# Metric Card for SIMPLE## Metric descriptionSIMPLE (SImplicity Metric via Preference LEarning) scores a candidate simplificationagainst its source sentence, without references. It returns:- **score** `mu` in (-1, 1): +1 = highly successful simplification, 0 = verbatim copy ofthe source, -1 = unrelated or degenerate text. Negative scores flag unsuccessfulsimplifications, including complexifications.- **uncertainty** `sigma` (> 0.05): the model's confidence in that score; lower = moreconfident. Predictions with low sigma agree more often with human judgements.SIMPLE is a DeBERTa-v3 cross-encoder trained with a Thurstone pairwise preference loss andcalibrated on human quality ratings with a Gaussian likelihood. Three sizes are available.This Space's page runs an in-browser demo (SIMPLE-small with 8-bit weights, via ONNX RuntimeWeb); the model is downloaded only when a visitor starts the demo.## How to use```pythonimport evaluatesimple = evaluate.load("mpapucci/simple") # SIMPLE-large (default)# simple = evaluate.load("mpapucci/simple", "base") # or "small"out = simple.compute(sources=["The feline perched upon the mat in a state of repose."],predictions=["The cat sat on the mat."],)print(out["simple"], out["scores"], out["sigmas"])```This needs `pip install simple-metric`. The package can also be used directly, which avoidsthe `evaluate` dependency:```pythonfrom simple_metric import SIMPLEmetric = SIMPLE.from_pretrained("large")metric.score(sources, predictions)```### Inputs- `sources` (list of str): original sentences.- `predictions` (list of str): candidate simplifications, aligned with `sources`.- `batch_size` (int, default 32), `device` (str, default CUDA when available).### Output values- `simple` (float): mean score.- `scores` (list of float): per-example score `mu`.- `sigmas` (list of float): per-example uncertainty `sigma`.## ResultsSimpEval 2022 (Maddela et al., 2023): pairwise accuracy on 484 human preference pairs, andPearson/Spearman correlation with 360 human ratings.| Model | Pairwise acc. | Kendall tau | Pearson | Spearman ||---|---|---|---|---|| SIMPLE-small | 0.738 | 0.475 | 0.414 | 0.407 || SIMPLE-base | 0.781 | 0.562 | 0.427 | 0.448 || SIMPLE-large | 0.814 | 0.628 | 0.391 | 0.454 |## Limitations and bias- Sentence-level and English only; trained mostly on news and Wikipedia simplifications.- It inherits the notion of simplification quality of its training data (ASSET,OneStopEnglish, Newsela, SimpEval PAST).- Insertion/elaboration-heavy rewrites are rare in the training data; both the score andsigma are less reliable on them.- Sigma is a model-confidence signal, not an estimate of human disagreement.- SIMPLE judges how well a sentence was simplified; it can give a positive score to a fluentrewrite that changes the meaning.## CitationCitation will be added upon publication.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319// In-browser SIMPLE demo: tokenizer (tokenizers.js) + ONNX Runtime Web (WebAssembly).// Nothing heavy is fetched until the visitor presses "Load the demo"; the model and tokenizer// are then kept in the browser's Cache Storage for later visits.
const ORT_VERSION = "1.31.1";const TOKENIZERS_VERSION = "0.2.0";const ORT_BASE = `https://cdn.jsdelivr.net/npm/onnxruntime-web@${ORT_VERSION}/dist/`;const TOKENIZERS_URL = `https://cdn.jsdelivr.net/npm/@huggingface/tokenizers@${TOKENIZERS_VERSION}/dist/tokenizers.min.mjs`;const MANIFEST_URL = "model/manifest.json";const CACHE_PREFIX = "simple-metric-demo-";const MAX_TOKENS = 512;
const $ = (id) => document.getElementById(id);let manifest = null;let tokenizer = null;let session = null;let ort = null;
const EXAMPLES = [ ["Good simplification", "The physician recommended that the patient refrain from strenuous physical activity for several weeks.", "The doctor told the patient not to exercise hard for a few weeks.", ""], ["Sentence splitting", "Due to the inclement weather conditions, the municipal authorities decided to postpone the outdoor festival indefinitely.", "The weather was bad. So the city put off the outdoor festival. No new date was set.", ""], ["Copy of the source", "The physician recommended that the patient refrain from strenuous physical activity for several weeks.", "The physician recommended that the patient refrain from strenuous physical activity for several weeks.", ""], ["Complexification", "The doctor told the patient not to exercise hard for a few weeks.", "The physician recommended that the patient refrain from strenuous physical activity for several weeks.", ""], ["Compare two candidates", "Due to the inclement weather conditions, the municipal authorities decided to postpone the outdoor festival indefinitely.", "Because of the bad weather, the city put off the outdoor festival.", "The authorities decided."],];
// ---------------------------------------------------------------- helpers
function formatMB(bytes) { return `${Math.round(bytes / 1e6)} MB`;}
function cacheName() { return CACHE_PREFIX + (manifest ? manifest.version : "unknown");}
async function openCache() { try { return await caches.open(cacheName()); } catch { return null; // private windows or blocked storage: work without a cache }}
async function isCached() { try { const cache = await openCache(); return Boolean(cache && (await cache.match(manifest.model.path))); } catch { return false; }}
// Fetch a file, reporting bytes received; serve it from / store it in Cache Storage.async function cachedFetch(path, onBytes) { const cache = await openCache(); if (cache) { try { const hit = await cache.match(path); if (hit) { const buf = await hit.arrayBuffer(); onBytes(buf.byteLength); return buf; } } catch { /* fall through to the network */ } } const response = await fetch(path); if (!response.ok) throw new Error(`Could not download ${path} (HTTP ${response.status}).`); let buf; if (response.body && response.body.getReader) { const reader = response.body.getReader(); const chunks = []; let received = 0; for (;;) { const { done, value } = await reader.read(); if (done) break; chunks.push(value); received += value.length; onBytes(value.length); } const all = new Uint8Array(received); let offset = 0; for (const c of chunks) { all.set(c, offset); offset += c.length; } buf = all.buffer; } else { buf = await response.arrayBuffer(); onBytes(buf.byteLength); } if (cache) { try { await cache.put(path, new Response(buf)); } catch { /* storage full: skip caching */ } } return buf;}
// Standard normal CDF (Abramowitz and Stegun 7.1.26, |error| < 1.5e-7).function phi(x) { const t = 1 / (1 + 0.3275911 * Math.abs(x) / Math.SQRT2); const y = 1 - (((((1.061405429 * t - 1.453152027) * t) + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t * Math.exp(-x * x / 2); return x >= 0 ? (1 + y) / 2 : (1 - y) / 2;}
function verdict(mu) { if (mu >= 0.5) return "Successful simplification"; if (mu >= 0.15) return "Partial simplification"; if (mu > -0.15) return "Close to a copy of the source"; return "Unsuccessful: complexification, or degenerate text";}
function confidence(sigma) { if (sigma <= 0.1) return "the model is confident"; if (sigma <= 0.2) return "less certain than usual"; return "uncertain: worth a human look";}
// ---------------------------------------------------------------- loading
async function loadDemo() { $("load-error").classList.add("hidden"); $("intro").classList.add("hidden"); $("loading").classList.remove("hidden"); const total = manifest.model.bytes + manifest.tokenizer.bytes + manifest.tokenizer_config.bytes; let received = 0; const onBytes = (n) => { received += n; const pct = Math.min(100, (100 * received) / total); $("bar").style.width = `${pct.toFixed(1)}%`; $("bar").parentElement.setAttribute("aria-valuenow", pct.toFixed(0)); $("status").textContent = `Loading the model: ${formatMB(received)} of ${formatMB(total)}`; }; try { const [tokLib, ortLib, tokJson, tokConfig, modelBuf] = await Promise.all([ import(TOKENIZERS_URL), import(`${ORT_BASE}ort.wasm.min.mjs`), cachedFetch(manifest.tokenizer.path, onBytes), cachedFetch(manifest.tokenizer_config.path, onBytes), cachedFetch(manifest.model.path, onBytes), ]); $("status").textContent = "Starting the model…"; const decoder = new TextDecoder(); tokenizer = new tokLib.Tokenizer(JSON.parse(decoder.decode(tokJson)), JSON.parse(decoder.decode(tokConfig))); ort = ortLib; ort.env.wasm.wasmPaths = ORT_BASE; ort.env.wasm.numThreads = self.crossOriginIsolated ? Math.min(4, navigator.hardwareConcurrency || 1) : 1; session = await ort.InferenceSession.create(new Uint8Array(modelBuf), { executionProviders: ["wasm"], graphOptimizationLevel: "all", }); $("loading").classList.add("hidden"); $("demo").classList.remove("hidden"); $("source").focus(); } catch (err) { $("loading").classList.add("hidden"); $("intro").classList.remove("hidden"); $("load-error").textContent = `The demo could not start: ${err.message || err}`; $("load-error").classList.remove("hidden"); $("load").textContent = "Try again"; $("load").addEventListener("click", loadDemo, { once: true }); }}
// ---------------------------------------------------------------- scoring
async function scorePair(source, candidate) { const ids = tokenizer.encode(source, { text_pair: candidate }).ids; if (ids.length > MAX_TOKENS) { throw new Error(`The texts are too long for the demo (${ids.length} tokens; the limit is ${MAX_TOKENS}).`); } const shape = [1, ids.length]; const feeds = { input_ids: new ort.Tensor("int64", BigInt64Array.from(ids, (v) => BigInt(v)), shape), attention_mask: new ort.Tensor("int64", new BigInt64Array(ids.length).fill(1n), shape), }; const out = await session.run(feeds); const mu = Math.max(-1, Math.min(1, Number(out.mu.data[0]))); return { mu, sigma: Number(out.sigma.data[0]) };}
function place(which, res) { const pos = (v) => `${((Math.max(-1, Math.min(1, v)) + 1) / 2) * 100}%`; const marker = $(`marker-${which}`); const band = $(`band-${which}`); if (!res) { marker.style.display = "none"; band.style.display = "none"; return; } marker.style.display = "block"; marker.style.left = pos(res.mu); band.style.display = "block"; band.style.left = pos(res.mu - res.sigma); band.style.width = `calc(${pos(res.mu + res.sigma)} - ${pos(res.mu - res.sigma)})`;}
function card(which, label, res) { const el = $(`card-${which}`); el.classList.remove("hidden"); el.innerHTML = ""; const title = document.createElement("div"); title.className = "small muted"; title.textContent = label; const big = document.createElement("div"); big.className = "big"; big.textContent = `μ = ${res.mu >= 0 ? "+" : "−"}${Math.abs(res.mu).toFixed(3)}`; const v = document.createElement("div"); v.className = "verdict"; v.textContent = verdict(res.mu); const s = document.createElement("div"); s.className = "small muted"; s.textContent = `σ = ${res.sigma.toFixed(3)}: ${confidence(res.sigma)}`; el.append(title, big, v, s);}
async function onScore() { hideError(); const source = $("source").value.trim(); const a = $("cand-a").value.trim(); const b = $("cand-b").value.trim(); if (!source || !a) { showError("Please enter a source sentence and a simplification."); return; } $("score").disabled = true; $("score").textContent = "Scoring…"; try { const resA = await scorePair(source, a); const resB = b ? await scorePair(source, b) : null; $("result").style.display = "block"; $("marker-b").querySelector("span").textContent = "B"; $("marker-a").querySelector("span").textContent = resB ? "A" : "μ"; place("a", resA); place("b", resB); card("a", resB ? "Simplification A" : "Simplification", resA); if (resB) { card("b", "Simplification B", resB); const p = phi((resA.mu - resB.mu) / Math.sqrt(resA.sigma ** 2 + resB.sigma ** 2)); $("pref").classList.remove("hidden"); const pct = p > 0.999 ? "> 99.9%" : p < 0.001 ? "< 0.1%" : `${(100 * p).toFixed(1)}%`; $("pref").textContent = `Probability that A is the better simplification: ${pct} ` + "(Thurstone's model on the two scores and their uncertainties)."; } else { $("card-b").classList.add("hidden"); $("pref").classList.add("hidden"); } } catch (err) { showError(err.message || String(err)); } finally { $("score").disabled = false; $("score").textContent = "Score"; }}
function showError(msg) { $("error").textContent = msg; $("error").classList.remove("hidden");}
function hideError() { $("error").classList.add("hidden");}
// ---------------------------------------------------------------- page setup
function setupExamples() { for (const [label, source, a, b] of EXAMPLES) { const btn = document.createElement("button"); btn.type = "button"; btn.textContent = label; btn.addEventListener("click", () => { $("source").value = source; $("cand-a").value = a; $("cand-b").value = b; onScore(); }); $("examples").append(btn); }}
async function init() { setupExamples(); $("score").addEventListener("click", onScore); $("forget").addEventListener("click", async () => { try { for (const key of await caches.keys()) if (key.startsWith(CACHE_PREFIX)) await caches.delete(key); $("forget").textContent = "Removed. The model will be downloaded again next time."; } catch { $("forget").textContent = "Could not access the browser storage."; } }); try { manifest = await (await fetch(MANIFEST_URL)).json(); } catch { showError("Could not read the demo's model manifest."); $("load").disabled = true; return; } const total = manifest.model.bytes + manifest.tokenizer.bytes + manifest.runtime_bytes; $("size").textContent = `about ${formatMB(total)}`; if (await isCached()) { $("load").textContent = "Start the demo"; $("cached-note").classList.remove("hidden"); } else { $("load").textContent = `Load the demo (${formatMB(total)})`; } $("load").addEventListener("click", loadDemo, { once: true });}
init();12345678910111213141516171819<!doctype html><html><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width" /><title>My static Space</title><link rel="stylesheet" href="style.css" /></head><body><div class="card"><h1>Welcome to your static Space!</h1><p>You can modify this app directly by editing <i>index.html</i> in the Files and versions tab.</p><p>Also don't forget to check the<a href="https://huggingface.co/docs/hub/spaces" target="_blank">Spaces documentation</a>.</p></div></body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>SIMPLE metric</title><link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='7' fill='%232457c5'/%3E%3Cpath d='M8 21h16M8 15h11M8 9h16' stroke='white' stroke-width='3' stroke-linecap='round'/%3E%3C/svg%3E"><meta name="description" content="SIMPLE: a reference-free metric for sentence simplification that also reports its own uncertainty. Try it in your browser."><style>:root {color-scheme: light;--bg: #f7f7f4;--surface: #ffffff;--surface-2: #f0f0eb;--text: #1c1d1f;--muted: #5d6066;--border: #dcdcd5;--accent: #2457c5;--accent-text: #ffffff;--good: #1f8a4c;--bad: #c2412d;--neutral: #8a8d93;--band: rgba(36, 87, 197, 0.18);--code-bg: #f0f0eb;--focus: #2457c5;}@media (prefers-color-scheme: dark) {:root:not([data-theme="light"]) {color-scheme: dark;--bg: #141517;--surface: #1c1d20;--surface-2: #25262a;--text: #ececea;--muted: #a2a5ab;--border: #34363b;--accent: #7aa2ff;--accent-text: #0e1220;--good: #4cc27f;--bad: #f0806c;--neutral: #8f939a;--band: rgba(122, 162, 255, 0.22);--code-bg: #25262a;--focus: #7aa2ff;}}:root[data-theme="dark"] {color-scheme: dark;--bg: #141517; --surface: #1c1d20; --surface-2: #25262a; --text: #ececea; --muted: #a2a5ab;--border: #34363b; --accent: #7aa2ff; --accent-text: #0e1220; --good: #4cc27f; --bad: #f0806c;--neutral: #8f939a; --band: rgba(122, 162, 255, 0.22); --code-bg: #25262a; --focus: #7aa2ff;}* { box-sizing: border-box; }html { -webkit-text-size-adjust: 100%; }body {margin: 0; background: var(--bg); color: var(--text);font: 16px/1.55 system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;}main { max-width: 780px; margin: 0 auto; padding: 40px 16px 64px; }h1 { font-size: 2.1rem; line-height: 1.15; margin: 0 0 6px; letter-spacing: -0.01em; }h2 { font-size: 1.2rem; margin: 0 0 12px; }p { margin: 0 0 12px; }.lead { font-size: 1.1rem; color: var(--muted); margin-bottom: 24px; }.muted { color: var(--muted); }.small { font-size: 0.875rem; }a { color: var(--accent); }section { background: var(--surface); border: 1px solid var(--border); border-radius: 12px; padding: 20px; margin: 0 0 20px; }code, pre { font: 0.875rem/1.5 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }code { background: var(--code-bg); padding: 1px 5px; border-radius: 4px; }pre { background: var(--code-bg); padding: 12px 14px; border-radius: 8px; overflow-x: auto; margin: 0 0 12px; }pre code { background: none; padding: 0; }/* score scale */.scale { position: relative; height: 14px; border-radius: 7px; margin: 18px 0 6px;background: linear-gradient(90deg, var(--bad), var(--neutral) 50%, var(--good)); }.scale .band { position: absolute; top: -4px; bottom: -4px; background: var(--band); border-radius: 4px; display: none; }.scale .marker { position: absolute; top: -7px; width: 4px; height: 28px; margin-left: -2px; border-radius: 2px;background: var(--text); display: none; }.scale .marker span { position: absolute; top: -22px; left: 50%; transform: translateX(-50%);font-size: 0.75rem; font-weight: 600; white-space: nowrap; }.scale-labels { display: flex; justify-content: space-between; font-size: 0.8rem; color: var(--muted); gap: 8px; }.scale-labels span:nth-child(2) { text-align: center; }.scale-labels span:last-child { text-align: right; }/* demo */button { font: inherit; border-radius: 8px; padding: 10px 16px; cursor: pointer; border: 1px solid var(--border);background: var(--surface-2); color: var(--text); }button.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-text); font-weight: 600; }button:disabled { opacity: 0.55; cursor: not-allowed; }button:focus-visible, textarea:focus-visible, a:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; }.linklike { background: none; border: none; padding: 0; color: var(--accent); text-decoration: underline; font-size: 0.875rem; }.progress { height: 8px; background: var(--surface-2); border-radius: 4px; overflow: hidden; margin: 12px 0 6px; }.progress > div { height: 100%; width: 0; background: var(--accent); transition: width 0.2s; }label { display: block; font-weight: 600; margin: 14px 0 6px; }label .muted { font-weight: 400; }textarea { width: 100%; min-height: 76px; resize: vertical; font: inherit; color: var(--text); background: var(--bg);border: 1px solid var(--border); border-radius: 8px; padding: 10px 12px; }.row { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; margin-top: 14px; }.examples { display: flex; flex-wrap: wrap; gap: 6px; margin: 4px 0 0; }.examples button { padding: 5px 10px; font-size: 0.85rem; border-radius: 999px; }.result { margin-top: 18px; padding-top: 16px; border-top: 1px solid var(--border); display: none; }.scores { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 12px; }.score-card { background: var(--surface-2); border-radius: 10px; padding: 12px 14px; }.score-card .big { font-size: 1.8rem; font-weight: 700; font-variant-numeric: tabular-nums; }.score-card .verdict { font-weight: 600; }.error { color: var(--bad); font-weight: 600; }.hidden { display: none !important; }footer { color: var(--muted); font-size: 0.85rem; text-align: center; margin-top: 28px; }@media (max-width: 520px) {h1 { font-size: 1.7rem; }section { padding: 16px; }.scale-labels { font-size: 0.72rem; }}</style></head><body><main><header><h1>SIMPLE</h1><p class="lead">A reference-free metric for sentence simplification that also says how sure it is.Give it a sentence and a simplification of it; no reference simplification needed.</p></header><section aria-labelledby="read-title"><h2 id="read-title">Reading the score</h2><p>SIMPLE returns a score <strong>μ</strong> between −1 and +1 for each (source, simplification) pair:</p><div class="scale" aria-hidden="true"></div><div class="scale-labels"><span>−1 unrelated or degenerate text</span><span>0 copy of the source</span><span>+1 successful simplification</span></div><p class="small muted" style="margin-top:12px">Negative scores flag unsuccessful simplifications, includingcomplexifications. Each score comes with <strong>σ</strong>, the model's own uncertainty: most predictions sitnear the minimum of 0.05; a larger σ means the model is less sure, and the example deserves a human look.</p></section><section aria-labelledby="demo-title"><h2 id="demo-title">Try it in your browser</h2><div id="intro"><p>The demo runs <strong>SIMPLE-small</strong> entirely on your device: nothing you type is sent anywhere.Starting it downloads the model once (<span id="size">≈ 180 MB</span>); your browser keeps it, so latervisits start quickly.</p><div class="row"><button id="load" class="primary" type="button">Load the demo</button><span id="cached-note" class="small muted hidden">The model is already stored on this device.</span></div><p id="load-error" class="error hidden" role="alert"></p></div><div id="loading" class="hidden" aria-live="polite"><div class="progress" role="progressbar" aria-label="Download progress" aria-valuemin="0" aria-valuemax="100"><div id="bar"></div></div><p id="status" class="small muted">Starting…</p></div><div id="demo" class="hidden"><label for="source">Source sentence</label><textarea id="source" maxlength="2000" placeholder="The original, complex sentence"></textarea><label for="cand-a">Simplification</label><textarea id="cand-a" maxlength="2000" placeholder="A simplified version of the source"></textarea><label for="cand-b">Second simplification <span class="muted">(optional, to compare two candidates)</span></label><textarea id="cand-b" maxlength="2000" placeholder="Leave empty to score a single simplification"></textarea><p class="small muted" style="margin:12px 0 4px">Examples:</p><div class="examples" id="examples"></div><div class="row"><button id="score" class="primary" type="button">Score</button><button id="forget" class="linklike" type="button">Remove the stored model from this device</button></div><div id="result" class="result" aria-live="polite"><div class="scale" id="result-scale"><div class="band" id="band-a"></div><div class="band" id="band-b"></div><div class="marker" id="marker-a"><span>A</span></div><div class="marker" id="marker-b"><span>B</span></div></div><div class="scale-labels"><span>−1</span><span>0</span><span>+1</span></div><div class="scores" style="margin-top:14px"><div class="score-card" id="card-a"></div><div class="score-card hidden" id="card-b"></div></div><p id="pref" class="hidden" style="margin-top:12px"></p></div><p id="error" class="error hidden" role="alert"></p><p class="small muted" style="margin-top:16px">This demo uses SIMPLE-small with 8-bit weights; its scores arewithin about ±0.015 of the full model's. SIMPLE judges how well a sentence was simplified; it can still give apositive score to a fluent rewrite that changes the meaning, so check meaning separately when it matters.For evaluations, use the Python package below (SIMPLE-large by default).</p></div><noscript><p class="error">The demo needs JavaScript.</p></noscript></section><section aria-labelledby="use-title"><h2 id="use-title">Use it in Python</h2><pre><code>pip install simple-metric</code></pre><pre><code>from simple_metric import SIMPLEmetric = SIMPLE.from_pretrained("large") # or "small", "base"out = metric.score(sources, simplifications)out.mu, out.sigma, out.mean</code></pre><p>With 🤗 Evaluate:</p><pre><code>import evaluatesimple = evaluate.load("mpapucci/simple", "large")simple.compute(sources=sources, predictions=simplifications)</code></pre><p class="small muted">Models: <a href="https://huggingface.co/mpapucci/simple-metric-small">small</a>,<a href="https://huggingface.co/mpapucci/simple-metric-base">base</a>,<a href="https://huggingface.co/mpapucci/simple-metric-large">large</a>.Code and training: <a href="https://github.com/michelepapucci/simple-metric">github.com/michelepapucci/simple-metric</a>.Paper: <em>Rethinking Text Simplification Evaluation as Preference Learning</em> (link coming soon).</p></section><footer>SIMPLE · MIT License</footer></main><script type="module" src="demo.js"></script></body></html>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748{ "model": { "path": "model/model_quantized.onnx", "bytes": 165217283 }, "tokenizer": { "path": "model/tokenizer.json", "bytes": 8648864 }, "tokenizer_config": { "path": "model/tokenizer_config.json", "bytes": 1315 }, "version": "small-int8-e2dbc3d43fa5", "runtime_bytes": 14848852, "export_report": { "model": "/tmp/claude-1006/-home-mpapucci-SimRM/02346888-ac69-4314-bd7b-2417b261b6ab/scratchpad/hfcache/models--mpapucci--simple-metric-small/snapshots/da4a27472fda25177e4122ea6f50bffd425249c9", "sizes_mb": { "model.onnx": 539.5, "model_quantized.onnx": 157.6 }, "max_length": 512, "pytorch": { "pairwise_accuracy": 0.738, "pearson": 0.414, "spearman": 0.407, "max_abs_diff_mu_vs_pytorch": 0.0, "mean_abs_diff_mu_vs_pytorch": 0.0, "max_abs_diff_sigma_vs_pytorch": 0.0 }, "onnx_fp32": { "pairwise_accuracy": 0.738, "pearson": 0.414, "spearman": 0.407, "max_abs_diff_mu_vs_pytorch": 9.98377799987793e-07, "mean_abs_diff_mu_vs_pytorch": 2.3662966365615528e-07, "max_abs_diff_sigma_vs_pytorch": 4.172325134277344e-07 }, "onnx_int8": { "pairwise_accuracy": 0.738, "pearson": 0.416, "spearman": 0.409, "max_abs_diff_mu_vs_pytorch": 0.014266684651374817, "mean_abs_diff_mu_vs_pytorch": 0.002166589428412004, "max_abs_diff_sigma_vs_pytorch": 0.004513069987297058 } }}123version https://git-lfs.github.com/spec/v1oid sha256:7f467cce7b75e433702c033c115afb697e5e376384abc5a9c00bc115f41d23b3size 1652172831234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859{ "added_tokens_decoder": { "0": { "content": "[PAD]", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "1": { "content": "[CLS]", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "2": { "content": "[SEP]", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true }, "3": { "content": "[UNK]", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false, "special": true }, "128000": { "content": "[MASK]", "lstrip": false, "normalized": false, "rstrip": false, "single_word": false, "special": true } }, "bos_token": "[CLS]", "clean_up_tokenization_spaces": false, "cls_token": "[CLS]", "do_lower_case": false, "eos_token": "[SEP]", "extra_special_tokens": {}, "mask_token": "[MASK]", "model_max_length": 1000000000000000019884624838656, "pad_token": "[PAD]", "sep_token": "[SEP]", "sp_model_kwargs": {}, "split_by_punct": false, "tokenizer_class": "DebertaV2Tokenizer", "unk_token": "[UNK]", "vocab_type": "spm"}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586"""SIMPLE as a Hugging Face `evaluate` metric.
import evaluate simple = evaluate.load("mpapucci/simple") # SIMPLE-large simple = evaluate.load("mpapucci/simple", "base") # or "small" out = simple.compute(sources=[...], predictions=[...])
This module is a thin wrapper around the `simple-metric` package(`pip install simple-metric`), which can also be used directly."""
import datasetsimport evaluate
_CITATION = """\@misc{simple-metric, title = {Rethinking Text Simplification Evaluation as Preference Learning}, note = {Citation will be added upon publication},}"""
_DESCRIPTION = """\SIMPLE (SImplicity Metric via Preference LEarning) is a reference-free learned metric forsentence simplification. Given a source sentence and a candidate simplification it returns aquality score in (-1, 1): +1 for a highly successful simplification, 0 for a verbatim copy ofthe source, and -1 for unrelated or degenerate text; negative scores flag unsuccessfulsimplifications, including complexifications. With every score it also reports sigma, themodel's own uncertainty (lower = more confident). SIMPLE is a DeBERTa-v3 cross-encoder trainedon pairwise preferences between simplifications (Thurstone model) and calibrated on humanquality ratings. No reference simplifications are needed."""
_KWARGS_DESCRIPTION = """Args: sources (list of str): the original (complex) sentences. predictions (list of str): the candidate simplifications, aligned with `sources`. batch_size (int, optional): batch size for scoring. Defaults to 32. device (str, optional): e.g. "cuda", "cuda:1" or "cpu". Defaults to CUDA when available.Returns: simple (float): mean SIMPLE score over all examples, in (-1, 1). scores (list of float): per-example scores (mu). sigmas (list of float): per-example uncertainty (sigma > 0.05; lower = more confident).Examples: >>> simple = evaluate.load("mpapucci/simple") >>> out = simple.compute( ... sources=["The feline perched upon the mat in a state of repose."], ... predictions=["The cat sat on the mat."]) >>> sorted(out) ['scores', 'sigmas', 'simple']"""
_SIZES = ("small", "base", "large")
@evaluate.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION)class Simple(evaluate.Metric): def _info(self): return evaluate.MetricInfo( description=_DESCRIPTION, citation=_CITATION, inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features( {"sources": datasets.Value("string"), "predictions": datasets.Value("string")} ), codebase_urls=["https://github.com/michelepapucci/simple-metric"], reference_urls=["https://huggingface.co/mpapucci/simple-metric-large"], )
def _download_and_prepare(self, dl_manager): name = (self.config_name or "default").lower() if name not in (*_SIZES, "default"): raise KeyError(f"Unknown SIMPLE size {self.config_name!r}; use one of {_SIZES}.") self._model_name = "large" if name == "default" else name self._scorers = {}
def _scorer(self, device): key = str(device) if key not in self._scorers: from simple_metric import SIMPLE
self._scorers[key] = SIMPLE.from_pretrained(self._model_name, device=device) return self._scorers[key]
def _compute(self, sources, predictions, batch_size=32, device=None): out = self._scorer(device).score(sources, predictions, batch_size=batch_size) return {"simple": out.mean, "scores": out.mu, "sigmas": out.sigma}README.md+92-5
demo.jsAdded+319
index.html+211-17
model/manifest.jsonAdded+48
model/model_quantized.onnxAdded+3
model/tokenizer.jsonAdded
model/tokenizer_config.jsonAdded+59
simple.pyAdded+86