#!/usr/bin/env python """Build the HuggingFace repo: EmoTweetID unified under Ekman's seven universal emotions. The pool is everything EmoTweetID's annotators labelled (2,243 tweets). Two provenances: * the five classes they already tagged that are Ekman universals - fear, disgust, sadness, surprise, joy - are carried over **unchanged** (their majority-vote human labels; `joy` is renamed to Ekman's own term `enjoyment`, the upstream name stays in `source_label`); * the `anger` pool is the only thing re-decided here: laya splits it into `anger` vs `contempt` against Ekman's definitions (out/anger_ekman_rows.csv, from label_anger.py). Configs, each stratified 8:1:1 train/valid/test with seed 0 and duplicate-safe groups: full all Ekman-7 rows, natural imbalance balanced Ekman-7 rows down-sampled to equal size per class (seed 0) [default] anger_split the anger pool only, two-class, with every evidence column anger_split_balanced that pool at 1:1 Layout and card style mirror mahalisyarifuddin/goemotions-ekman. Usage: python make_dataset.py [--dist dist] [--out-dir out] [--repo ns/name] """ import argparse import json import os import re import shutil import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from ekman_questions import EKMAN7, BINARY from split_exact import (FRACTIONS as SPLIT_FRACTIONS, apportion, assign_groups, ideal_targets, sample_groups_per_class) LABELS_EKMAN = EKMAN7 LABELS_BINARY = BINARY # EmoTweetID's label names -> Ekman's universal-emotion names. Everything but joy is identity. SOURCE_TO_EKMAN = {"joy": "enjoyment"} SPLITS = ("train", "valid", "test") CONFIGS = ("balanced", "full", "anger_split", "anger_split_balanced") # `full` and `anger_split` ship the whole pool as a single `train` split; the two balanced configs # are the ones that carry an exact 8b : 1b : 1b train/valid/test. WHOLE_CONFIGS = ("full", "anger_split") SPLIT_CONFIGS = ("balanced", "anger_split_balanced") SEED = 0 # the split seed the card promises; every run reads it from here OUT_DIR = "out" # label_anger.py --out DATA_CSV, DATA_CSV_EN = "data/file1.csv", "data/file2.csv" PREV_DIR = "out_prev" # the previous revision's run artefacts (shipped for the comparison) PREV_CACHE = os.path.join(PREV_DIR, "cache_id_core.json") PREV_CSV = os.path.join(PREV_DIR, "anger_ekman_rows.csv") SHIPPED = """README.template.md label_anger.py label_anger_id.py make_dataset.py fetch_source_data.py publish.py laya_opt.py ekman_questions.py ekman_questions_id.py zcsafe.py prepare_checkpoint.py probe_quality.py probe_quality_id.py probes.py probes_id.py split_exact.py test_split_exact.py bench_speedup.py bench_batch.py check_veto_and_speed.py sweep_config.py""".split() REQUIRED = ["text", "text_en", "label", "label_idx", "source_label", "label_origin"] def norm(s): return re.sub(r"\s+", " ", str(s)).strip() def load_pool(out_dir=OUT_DIR): """All annotated tweets, with laya's anger/contempt decision overlaid on the `anger` rows.""" df = pd.read_csv(DATA_CSV) en = pd.read_csv(DATA_CSV_EN) df["text"] = df["tweet"].astype(str).map(norm) df["text_en"] = pd.Series(en["tweet_en"]).astype(str).map(norm).values df["row_src"] = df.index df["source_label"] = df["label"].astype(str).str.strip().str.lower() # human labels enter here unchanged; only `anger` is left for the model to split df["label"] = df["source_label"].map(lambda x: SOURCE_TO_EKMAN.get(x, x)) lab = pd.read_csv(os.path.join(out_dir, "anger_ekman_rows.csv")) lab = lab[lab["source_label"] == "anger"] assert len(lab) == lab["row_src"].nunique(), "anger labels are not row-unique" assert set(lab["label"]) <= set(BINARY), f"unexpected labels in anger run: {set(lab['label'])}" keep = ["label_source", "ambiguous", "ekman_p_anger", "ekman_p_contempt", "ekman_confidence", "p_anger_id", "p_anger_swapped", "ekman_margin_id", "p_superiority", "p_blocked_or_unfair", "p_not_anger_or_contempt"] m = df.merge(lab[["row_src", "label"] + keep].rename(columns={"label": "ek_label"}), on="row_src", how="left") anger = m["source_label"].eq("anger") # every anger row must have exactly one decision, and no other row may have one assert m["ek_label"].notna().eq(anger).all(), "the anger run does not cover the pool exactly" m["label"] = np.where(anger, m["ek_label"], m["label"]) m["label_origin"] = np.where(anger, "laya_anger_split", "upstream_manual") m = m.drop(columns=["ek_label"]) untouched = ~anger assert m.loc[untouched, "label"].eq( m.loc[untouched, "source_label"].map(lambda x: SOURCE_TO_EKMAN.get(x, x))).all(), \ "a human label was changed" assert m["label"].isin(LABELS_EKMAN).all(), "a row ended up outside the Ekman-7 label set" return m, lab def add_text_group(df): """Transitive text identity over both language columns -> split groups (see the leakage test). Rows are union-find'd when their Indonesian text matches or when their English translation matches: EmoTweetID's `tweet` column has repeats, and one translation can cover several different Indonesian tweets, which would otherwise land on both sides of a split. """ parent = list(range(len(df))) def find(x): while parent[x] != x: parent[x] = parent[parent[x]] x = parent[x] return x def union(a, b): ra, rb = find(a), find(b) if ra != rb: parent[max(ra, rb)] = min(ra, rb) for col in ("text", "text_en"): first = {} for i, t in enumerate(df[col].tolist()): if t in first: union(i, first[t]) else: first[t] = i roots, grp = {}, [] for i in range(len(df)): r = find(i) roots.setdefault(r, len(roots)) grp.append(roots[r]) df["group"] = grp return df def stratified_811_greedy(df, seed): """The splitter the *previous* revision shipped - kept so the card can compare against it. Shuffles each class's duplicate groups with `seed`, then hands them out greedily one at a time to the split with the largest remaining row deficit against 0.8/0.1/0.1. Groups are the unit, so nothing leaks, but a class whose last group overshoots cannot be corrected, which is why it lands on 1794/226/223 rather than on whole-row 8:1:1. `make_dataset.stratified_811` is the exact one. """ rng = np.random.RandomState(seed) lab, grp = df["label"].to_numpy(), df["group"].to_numpy() sizes = pd.Series(grp).value_counts().reindex(range(grp.max() + 1), fill_value=0).to_numpy() modal = (pd.DataFrame({"g": grp, "l": lab}).groupby("g")["l"] .agg(lambda x: x.value_counts().index[0])) assign = {} for c in sorted(df["label"].unique()): gs = [g for g in modal.index if modal[g] == c] rng.shuffle(gs) gs.sort(key=lambda g: -sizes[g]) target = np.array([0.8, 0.1, 0.1]) * sizes[gs].sum() cur = np.zeros(3) for g in gs: j = int(np.argmax(target - cur)) assign[g] = SPLITS[j] cur[j] += sizes[g] out = df.copy() out["split"] = [assign[g] for g in grp] return out def stratified_811(df, seed): """Exact 8:1:1 by row count, still group-aware - see split_exact.py for the how and the why. The row count of a config decides its column totals (`apportion`, i.e. largest remainder: 2,243 rows -> 1,795/224/224, 475 rows -> 380/48/47), and the per-class-per-split counts are the integer solution closest to `n_class x 0.8 | 0.1 | 0.1` given those totals. Groups are then placed by need and repaired by moving whole groups, so no wording straddles two splits and the split sizes come out exact rather than "to within a group". """ sizes = df["label"].value_counts().to_dict() split_sizes = apportion(len(df), SPLIT_FRACTIONS) targets = ideal_targets(sizes, split_sizes) out = assign_groups(df, targets, seed) for s in SPLITS: g = out.loc[out["split"] == s, "group"] for other in SPLITS: if other != s: leak = int(g.isin(out.loc[out["split"] == other, "group"]).sum()) assert leak == 0, f"group leaked between {s} and {other}: {leak} rows" assert int((out["split"] == s).sum()) == split_sizes[SPLITS.index(s)], "split size off target" return out def balanced_pool(df, labels, seed=SEED): """Down-sample to `m` rows per class, whole groups, with `m` the largest multiple of ten that fits. The ten-row block has to be the unit if the split is to be exactly 8b : 1b : 1b, so a balanced config picks its per-class size accordingly - 186 eligible `contempt` rows become 180, i.e. 144 train / 18 valid / 18 test per class and 1,008 / 126 / 126 overall (b = 126). Nothing else about the sample changes: seed 0, whole duplicate groups, identical class counts. """ counts = df["label"].value_counts() m = min(int(counts[c]) for c in labels) // 10 * 10 assert m > 0, "no class reaches ten rows" sub, dropped = sample_groups_per_class(df, m, seed, labels=labels) return sub, m, dropped def features(labels): from datasets import ClassLabel, Features, Value return Features({ "text": Value("string"), "text_en": Value("string"), # `label` stays a readable string (a parquet opened in pandas/duckdb shows "contempt", not 1); # `label_idx` is the ClassLabel for training, and its names are the same list in the same order. "label": Value("string"), "label_idx": ClassLabel(names=list(labels)), "source_label": Value("string"), "label_origin": Value("string"), "label_source": Value("string"), "ambiguous": Value("bool"), "ekman_p_anger": Value("float32"), "ekman_p_contempt": Value("float32"), "ekman_confidence": Value("float32"), "p_anger_id": Value("float32"), "p_anger_swapped": Value("float32"), "ekman_margin_id": Value("float32"), "p_superiority": Value("float32"), "p_blocked_or_unfair": Value("float32"), "p_not_anger_or_contempt": Value("float32"), "row_src": Value("int32"), }) def to_frame(df, labels): """Column order like the schema; keep None for un-run evidence (NaN would round-trip badly).""" want = REQUIRED + ["label_source", "ambiguous", "ekman_p_anger", "ekman_p_contempt", "ekman_confidence", "p_anger_id", "p_anger_swapped", "ekman_margin_id", "p_superiority", "p_blocked_or_unfair", "p_not_anger_or_contempt", "row_src"] cols = {} for k in want: v = df[k] if k in df else pd.Series([None] * len(df)) if k == "label": v = df["label"] elif k == "label_idx": v = pd.Series([labels.index(x) for x in df["label"]]) cols[k] = [None if pd.isna(x) else x for x in v] return pd.DataFrame(cols, columns=want) def write_parquet(df, labels, dist, config): from datasets import Dataset ds = Dataset.from_pandas(to_frame(df, labels), features=features(labels), preserve_index=False) out_dir = os.path.join(dist, config) os.makedirs(out_dir, exist_ok=True) present = [s for s in SPLITS if (df["split"] == s).any()] for f in os.listdir(out_dir): # a config that stops being split must not keep files if f.endswith(".parquet") and f[:-len(".parquet")] not in present: os.remove(os.path.join(out_dir, f)) for s in present: sub = ds.select([i for i in range(len(ds)) if df["split"].iloc[i] == s]) sub.to_parquet(os.path.join(out_dir, f"{s}.parquet")) return sorted(os.listdir(out_dir)) def class_table(df, labels): vc = df["label"].value_counts() mine = "split here: laya on the `anger` pool" return "\n".join( f"| `{c}` | {int(vc.get(c, 0))} | {100.0 * int(vc.get(c, 0)) / len(df):.1f}% | " f"{mine if c in ('anger', 'contempt') else 'EmoTweetID annotators, kept verbatim'} |" for c in labels if int(vc.get(c, 0)) > 0) def checkpoint_facts(ckpt_dir="models/laya-ml/multilingual"): """Read the checkpoint's real size/config out of its safetensors header - no model load. Counts unique storages, so a tied/aliased weight is counted once (that is what makes the number differ from a naive `sum(v.numel() for v in state_dict.values())`). """ import struct out = {"params": None, "params_enc": None, "params_heads": None, "tensors": None, "enc_name": "n/a", "model_type": "n/a", "vocab": "n/a", "ctx_default": "n/a", "amp": "n/a"} path = os.path.join(ckpt_dir, "model.safetensors") if not os.path.exists(path): return out with open(path, "rb") as f: hdr = json.loads(f.read(struct.unpack(" 0.5).sum())} of {len(v)} rows above 0.5 (mean P(neither) {v.mean():.2f}) " f"- Indonesian reading") stage_rows = timings.get("stage_rows", {}) n_states = sum(stage_rows.values()) or (4 * len(ang) + int(timings["ambiguous_rows"]) * 3) # agreement with the previous revision: `id_core` is the *same* stage, on the same texts, as the # published out/cache_id_core.json (shipped here as out_prev/), so a re-run has to reproduce it repro_note = "the shipped `out/cache_id_core.json` is from that run" new_cache = os.path.join(out_dir, "cache_id_core.json") if os.path.exists(PREV_CACHE) and os.path.exists(new_cache): a, b = json.load(open(PREV_CACHE)), json.load(open(new_cache)) common = sorted(set(a) & set(b)) d = [abs(a[k]["ekman"]["probabilities"]["anger"] - b[k]["ekman"]["probabilities"]["anger"]) for k in common] same = sum((a[k]["ekman"]["probabilities"]["anger"] >= 0.5) == (b[k]["ekman"]["probabilities"]["anger"] >= 0.5) for k in common) repro_note = (f"the `id_core` stage matches the earlier two-language run's " f"`out_prev/cache_id_core.json` (shipped here) to the last digit - " f"{same}/{len(common)} unique texts on the same side of the decision line, " f"mean |delta p(anger)| {sum(d) / len(d):.4f}, max {max(d):.4f}") if same != len(common): n_moved = len(common) - same repro_note += (f"; the {n_moved} row{'s' if n_moved > 1 else ''} that moved sit within " f"0.05 of p=0.5") # the second run (reconfirm.py): stage-by-stage and row-by-row agreement with the shipped labels reconfirm_note = "a second run has not been compared against this one" rc = os.path.join(out_dir, "reconfirm.json") if os.path.exists(rc): r = json.load(open(rc)) st = r.get("stages", {}) lab = r.get("labels", {}) drift = [k for k, v in st.items() if v["max_abs_diff"] > 0 or v["only_in_a"] or v["only_in_b"]] covers = ", ".join(sorted(st)) if lab and not drift and not lab["flips"]: sec = (r.get("second_run") or {}).get("total_laya_seconds") reconfirm_note = (f"every stage ({covers}) matched row for row and reproduced **" f"{lab['identical']}/{lab['rows']} labels**") reconfirm_note += (", down to a byte-identical `anger_ekman_rows.csv`" if lab.get("identical_bytes") else "") reconfirm_note += (f", the largest probability difference anywhere being " f"{lab['max_prob_abs_diff']:.6f}") if sec: reconfirm_note += (f" ({sec:,.1f} s of model time against {timings['total_laya_seconds']:,.1f} s" f" for the shipped run)") elif lab: reconfirm_note = (f"the stages agreed on {lab['identical']}/{lab['rows']} labels, with " f"drift in {drift or 'no stage'} and flips " f"{lab['flips'] or 'none'} (largest probability difference " f"{lab['max_prob_abs_diff']:.6f})") else: reconfirm_note = f"the stages agree as follows: {st}" # what changed against the previous revision's shipped labels (English-pooled decision) prev_note, prev_stats = "not available", {} if os.path.exists(PREV_CSV): pv = pd.read_csv(PREV_CSV)[["row_src", "label", "ekman_confidence"]].rename( columns={"label": "label_prev", "ekman_confidence": "conf_prev"}) ang = ang.merge(pv, on="row_src", how="left") j = ang[["row_src", "label", "label_prev"]].dropna(subset=["label_prev"]) if len(j): n_flip = int((j["label"] != j["label_prev"]).sum()) p_ang, p_con = int((j["label_prev"] == "anger").sum()), int((j["label_prev"] == "contempt").sum()) c2a = int(((j["label_prev"] == "contempt") & (j["label"] == "anger")).sum()) a2c = int(((j["label_prev"] == "anger") & (j["label"] == "contempt")).sum()) prev_stats = {"prev_anger": p_ang, "prev_contempt": p_con, "flipped": n_flip, "flip_to_anger": c2a, "flip_to_contempt": a2c, "prev_share_contempt": round(100.0 * p_con / len(j), 1)} prev_note = (f"it labelled {p_ang} anger / {p_con} contempt; the labels here differ on " f"{n_flip} of the {len(j)} rows, {a2c} of them anger -> contempt") # the corpus's own evidence: EmoTweetID sampled by emotion keyword, so a row that contains an # explicit Indonesian anger word carries an upstream hint that it is anger and not contempt. # How often does each revision overrule that hint? LEXICON = ("kesal", "marah", "murka", "benci", "jengkel", "geram", "tersinggung", "muak", "ngamuk") hint = ang["text"].str.lower().str.contains("|".join(LEXICON), regex=True) lex_stats = {"lexicon_rows": int(hint.sum()), "lexicon_contempt_new": None, "lexicon_contempt_prev": None} if "label_prev" in ang: lex_stats["lexicon_contempt_new"] = int((ang.loc[hint, "label"] == "contempt").sum()) lex_stats["lexicon_contempt_prev"] = int((ang.loc[hint, "label_prev"] == "contempt").sum()) lex_stats["lexicon_note"] = ( f"{int(hint.sum())} of the {len(ang)} pool rows contain an explicit Indonesian anger word " f"(`kesal`, `marah`, `murka`, `benci`, `jengkel`, `geram`, `tersinggung`, `muak`, `ngamuk`) " f"- which is how EmoTweetID's annotators sampled, so the word is upstream evidence for " f"anger. {int((ang.loc[hint, 'label'] == 'contempt').sum())} of those " f"{int(hint.sum())} rows ({100.0 * (ang.loc[hint, 'label'] == 'contempt').mean():.0f}%) " f"are labelled `contempt` here.") else: lex_stats["lexicon_note"] = (f"{int(hint.sum())} pool rows contain an explicit Indonesian anger " f"word; the Indonesian-only reading calls " f"{int((ang.loc[hint, 'label'] == 'contempt').sum())} of them contempt") # the one-reader audit of the flips (audit_flips.py), shipped as out/audit_flips.csv audit_stats = {} ap = os.path.join(out_dir, "audit_flips.csv") if os.path.exists(ap): au = pd.read_csv(ap) n = len(au) a_new = int((au["verdict"] == au["label"]).sum()) a_prev = int((au["verdict"] == au["shipped_label"]).sum()) other = int((au["verdict"] == "other").sum()) moved = au[au["label"] != au["shipped_label"]] moved_c = int((moved["label"] == "contempt").sum()) moved_c_ok = int(((moved["label"] == "contempt") & (moved["verdict"] == "contempt")).sum()) audit_stats = { "audit_n": n, "audit_agree_new": a_new, "audit_agree_prev": a_prev, "audit_other": other, "audit_note": ( f"A sample of {n} rows where the readings disagree was judged against the operational " f"boundary by one reader working from the tweet text alone, before seeing any " f"probability: {a_prev}/{n} of those judgements land on the two-language reading, " f"{a_new}/{n} on the label here, and {other}/{n} read as neither emotion. Of the " f"{moved_c} rows labelled `contempt` here and `anger` by the two-language reading, " f"{moved_c_ok} was accepted as contempt. The reader is a machine reader, not a human " f"annotator, and works on short code-mixed text - a signal, not gold labels."), "audit_caveat": ("one reader, unblinded to the hypothesis, and the pool is short, shouty, " "code-mixed Indonesian - rerun this on a larger sample before quoting it"), } # how close to a coin flip each revision's reading ended, on the same scale (max P of the reading) conf_stats = {"conf_low_new": int((np.maximum(ang["p_anger_id"], 1 - ang["p_anger_id"]) < 0.6).sum())} if "conf_prev" in ang: conf_stats["conf_low_prev"] = int((ang["conf_prev"] < 0.6).sum()) conf_stats["conf_note"] = ( f"{conf_stats['conf_low_new']} of {len(ang)} rows land within 0.10 of a coin flip on the " f"primary reading (max probability of the two options under 0.60), and the mean max " f"probability across the pool is " f"{float(np.mean(np.maximum(ang['p_anger_id'], 1 - ang['p_anger_id']))):.3f}") else: conf_stats["conf_note"] = f"{conf_stats['conf_low_new']} rows land within 0.10 of a coin flip" conf_stats["lowconf_laya"] = int((ang["ekman_confidence"] < 0.6).sum()) # the option-order control, on the rows this build labels order_stats = {"order_flip": "n/a", "order_shift": "n/a", "order_note": "not measured - run label_anger_id.py without --no-swap"} if "p_anger_swapped" in ang and ang["p_anger_swapped"].notna().any(): pa, psw = ang["p_anger_id"].to_numpy(), ang["p_anger_swapped"].to_numpy() flip, shift = float(np.mean((pa >= 0.5) != (psw >= 0.5))), float(np.mean(np.abs(pa - psw))) order_stats = { "order_flip": round(100 * flip, 1), "order_shift": round(shift, 3), "mean_p_anger_prompt": round(float(np.mean(pa)), 3), "mean_p_anger_swapped": round(float(np.mean(psw)), 3), "order_note": (f"Listing contempt first moved the argmax on {100 * flip:.1f}% of the pool " f"(mean |delta p(anger)| {shift:.3f}; mean P(anger) {np.mean(pa):.3f} as " f"prompted vs {np.mean(psw):.3f} with the options swapped), so the " f"prompt's option order is worth roughly a third of the contempt shift"), } # fit-for-purpose probes, both languages (out/probe_quality_id.json, from probe_quality_id.py) probe = {} pq = os.path.join(out_dir, "probe_quality_id.json") if os.path.exists(pq): conds = json.load(open(pq))["conditions"] tag = {c["condition"].strip()[0]: c for c in conds} def fmt(c): return f"{c['correct']}/{c['n']} ({c['accuracy']:.3f})" probe = {k: fmt(tag[t]) for k, t in (("probe_author", "Z"), ("probe_en", "A"), ("probe_id", "B"), ("probe_id_idq", "C"), ("probe_en_idq", "D"), ("probe_id_swapped", "E")) if t in tag} b, a, c_, d_, e = (tag.get(x) for x in "BACDE") if a and b: probe["probe_gap"] = (f"The gap is {a['correct'] - b['correct']} items out of 16: the same " f"sentences are called correctly {a['correct']} times in English and " f"{b['correct']} times in Indonesian") probe["probe_mean_p"] = ( f"Mean P(anger) on the anger probes {b['per_class']['anger']['mean_p_anger']:.2f} in " f"Indonesian vs {a['per_class']['anger']['mean_p_anger']:.2f} in English; on the " f"contempt probes {b['per_class']['contempt']['mean_p_anger']:.2f} vs " f"{a['per_class']['contempt']['mean_p_anger']:.2f}") if b and c_: probe["probe_lang_q"] = (f"with the question in Indonesian instead of English, the gap " f"closes only {b['correct']} -> {c_['correct']} items") if d_: probe["probe_en_q"] = f"English items with the Indonesian question: {fmt(d_)}" if b and e: probe["probe_order"] = ( f"On the contempt items the mean P(anger) is {b['per_class']['contempt']['mean_p_anger']:.2f} " f"with anger listed first and {e['per_class']['contempt']['mean_p_anger']:.2f} with " f"contempt listed first - the order effect seen on the corpus") facts = checkpoint_facts() tbl = [] for name in CONFIGS: d, labels = tables[name], (LABELS_BINARY if name.startswith("anger") else LABELS_EKMAN) present = [s for s in SPLITS if (d["split"] == s).any()] for s in present: vc = d.loc[d["split"] == s, "label"].value_counts() per = " / ".join(f"{c} {int(vc.get(c, 0))}" for c in labels if int(vc.get(c, 0)) > 0) note = " (the whole pool, one split)" if len(present) == 1 else "" tbl.append(f"| `{name}` | {s} | {int((d['split'] == s).sum()):,} | {per}{note} |") # one-line summary of every config's split sizes, for the card split_note = ", ".join( ("%s %s of %s (b=%d)" % (name, " / ".join(str(splits[name][x]) for x in SPLITS), f"{sum(splits[name].values()):,}", sum(splits[name].values()) // 10)) if name in SPLIT_CONFIGS else ("%s 1 split of %s" % (name, f"{sum(splits[name].values()):,}")) for name in CONFIGS) dup = int(df.duplicated("text").sum()) g = df.groupby("text")["source_label"].nunique() conflict = int((g > 1).sum()) info = { "dup_conflicts": conflict, "n_pool": f"{len(df):,}", "n_anger_pool": f"{len(ang):,}", "n_manual": f"{len(df) - len(ang):,}", "n_contempt": int((df["label"] == "contempt").sum()), "n_anger_kept": int((df["label"] == "anger").sum()), "share_contempt": round(100.0 * int((ang["label"] == "contempt").sum()) / len(ang), 1), "n_balanced": int(sum(splits["balanced"].values())), "per_class_balanced": per_class["balanced"], "per_class_anger_balanced": per_class["anger_split_balanced"], "n_full_pool": int(sum(splits["full"].values())), "n_anger_pool_rows": int(sum(splits["anger_split"].values())), "balanced_split": " / ".join(str(splits["balanced"][x]) for x in SPLITS), "anger_split_balanced_split": " / ".join(str(splits["anger_split_balanced"][x]) for x in SPLITS), "balanced_per_class_split": " / ".join( str(apportion(per_class["balanced"])[i]) for i in range(3)), "anger_balanced_per_class_split": " / ".join( str(apportion(per_class["anger_split_balanced"])[i]) for i in range(3)), "n_anger_balanced": int(sum(splits["anger_split_balanced"].values())), "balanced_b": int(sum(splits["balanced"].values()) // 10), "n_balanced_s": f"{int(sum(splits['balanced'].values())):,}", "n_anger_balanced_s": f"{int(sum(splits['anger_split_balanced'].values())):,}", "whole_note": ("`full` and `anger_split` are the complete pools in a single `train` split - " "nothing is held out, and users who want their own validation split take it " "from there. The two balanced configs are the ones that carry an exact " "8:1:1 train/valid/test."), "class_table": class_table(df, LABELS_EKMAN), "split_table": "\n".join(tbl), "sources_str": ", ".join(f"`{k}` {v}" for k, v in src.most_common()), "noul_n": int(src.get("ekman_noul_tiebreak", 0)), "choice_n": int(src.get("ekman_choice_id", 0)), "orderavg_n": int(src.get("ekman_choice_order_avg", 0)), "kept_n": int(src.get("kept_original_label", 0)), "ambig": int(ang["ambiguous"].sum()), "offtopic": int((ang["p_not_anger_or_contempt"] > 0.5).sum()), "lowconf": int((ang["ekman_confidence"] < 0.6).sum()), "stages": ", ".join(f"{k.replace('_', ' ')} {float(v):.1f} s" for k, v in timings["stages"].items()), "veto": veto_str, "laya_seconds": round(timings["total_laya_seconds"], 1), "max_len": timings["max_len"], "head_max_len": timings["head_max_len"], "budget": timings["token_budget"], "margin": timings["margin"], "scored_rows": n_states, "naive_rows": 4 * len(ang), "repro_note": repro_note, "reconfirm_note": reconfirm_note, "prev_note": prev_note, "split_exact_note": split_note, **prev_stats, **lex_stats, **conf_stats, **order_stats, **probe, **audit_stats, "splits": splits, "duplicates_note": ( f"{dup} rows share an identical `text` string with another row (more, if you count pairs " f"whose English translation collides), and {conflict} of those repeated wordings repeat " "with *different* upstream labels - the annotators disagreed, and this dataset inherits " "that rather than re-judging it. Splitting is therefore **group-aware**: every member of a " "duplicate group lands in one split, so no wording appears in either side of a " "train/valid/test boundary (`verify()` fails the build if one does). The balanced " "configs sample whole groups as well, so a dropped row never orphans its duplicate."), "checkpoint": "convaiinnovations/laya (subfolder `multilingual/`)", "laya_v": laya.__version__, "datasets_v": datasets.__version__, "transformers_v": transformers.__version__, "torch_v": torch.__version__, "stageC": int(timings["ambiguous_rows"]), "stage_diag": int(stage_rows.get("id_diag", 2 * int(timings["ambiguous_rows"]))), "dup_conflicts": conflict, **{k: (f"{v / 1e6:.1f}M" if k.startswith("params") and isinstance(v, int) else v) for k, v in facts.items()}, } with open(info_path, "w") as f: json.dump(info, f, indent=1, sort_keys=True) return info def render_readme(info, template="README.template.md"): with open(template) as f: out = f.read() for k, v in info.items(): out = out.replace("{{" + k + "}}", str(v)) left = sorted(set(re.findall(r"\{\{(\w+)\}\}", out))) if left: raise SystemExit(f"unfilled README placeholders: {left}") return out def verify(dist, out_dir=OUT_DIR): """Open the written parquet files and check labels, provenance, leakage and card numbers.""" from datasets import Value, load_dataset info = json.load(open(os.path.join(dist, "build_info.json"))) for name in CONFIGS: labels = LABELS_BINARY if name.startswith("anger") else LABELS_EKMAN present = [s for s in SPLITS if os.path.exists(os.path.join(dist, name, f"{s}.parquet"))] ds = load_dataset("parquet", data_files={s: os.path.join(dist, name, f"{s}.parquet") for s in present}) assert list(ds[present[0]].features["label_idx"].names) == list(labels), f"{name}: label_idx" assert ds[present[0]].features["label"] == ds[present[0]].features["text"] == Value("string") for s in present: d = ds[s].to_pandas() assert len(d) > 0 and set(d["label"]) <= set(labels), f"{name}/{s}: bad labels" assert (d["text"].str.len() > 0).all() and (d["text_en"].str.len() > 0).all() ws = d["text"].str.replace(r"\s+", " ", regex=True).str.strip() assert (d["text"] == ws).all(), f"{name}/{s}: text not normalised" assert (d["label_idx"] == [labels.index(x) for x in d["label"]]).all(), f"{name}/{s}: idx" pool = d["label_origin"] == "laya_anger_split" assert set(d.loc[pool, "source_label"]) == {"anger"}, f"{name}: relabelled a non-anger row" kept = d.loc[~pool] assert (kept["label"] == kept["source_label"].map( lambda x: SOURCE_TO_EKMAN.get(x, x))).all(), f"{name}: changed a human label" if name.startswith("anger"): assert pool.all(), f"{name}: non-anger row inside the anger config" assert d["ekman_p_anger"].notna().all(), f"{name}: missing probabilities" else: assert d.loc[~pool, "ekman_p_anger"].isna().all(), f"{name}: stray evidence values" for other in present: if other == s: continue o = ds[other].to_pandas() assert not set(d["text"]) & set(o["text"]), f"{name}: text leakage {s}/{other}" assert not set(d["text_en"]) & set(o["text_en"]), f"{name}: translated-text leakage" counts = {s: len(ds[s]) for s in present} assert counts == info["splits"][name], f"{name}: card counts {info['splits'][name]} != {counts}" tot = sum(counts.values()) if len(present) == 1: assert present == ["train"], f"{name}: a single-split config must ship `train` only" assert tot == info["n_full_pool" if name == "full" else "n_anger_pool_rows"], \ f"{name}: the whole pool must be in `train` ({tot} rows)" print(f"[verify] {name}: {tot} rows, one split (the whole pool, nothing held out)") continue want = apportion(tot) # exact 8b : 1b : 1b got = [counts[s] for s in SPLITS] assert got == want, f"{name}: split sizes {got} != 8b:b:b targets {want}" frac = [abs(counts[s] / tot - x) * 100 for s, x in zip(SPLITS, (0.8, 0.1, 0.1))] assert tot % 10 == 0 and tot - 2 * (tot // 10) == 8 * (tot // 10), f"{name}: 10 | N" print(f"[verify] {name}: {got} of {tot} rows, b={tot // 10}, off 8:1:1 by " f"{frac[0]:.2f}/{frac[1]:.2f}/{frac[2]:.2f} points, {tot // len(labels)} per class") # the balanced configs must be exact per class in every split, not just in the column totals for name in SPLIT_CONFIGS: labels = LABELS_BINARY if name.startswith("anger") else LABELS_EKMAN per = info["per_class_" + ("anger_balanced" if name.startswith("anger") else "balanced")] want = apportion(per) for s in SPLITS: d = pd.read_parquet(os.path.join(dist, name, f"{s}.parquet")) vc = d["label"].value_counts() assert set(vc.values) == {want[SPLITS.index(s)]}, f"{name}/{s}: per-class {vc.to_dict()}" print(f"[verify] {name}: {per} rows per class, {want[0]} / {want[1]} / {want[2]} per class") # every shipped row still matches the upstream CSV, on top of the per-split checks src = pd.read_csv(DATA_CSV) src["text"] = src["tweet"].astype(str).map(norm) src["source_label"] = src["label"].astype(str).str.strip().str.lower() def _splits_on_disk(cfg): return [x for x in SPLITS if os.path.exists(os.path.join(dist, cfg, f"{x}.parquet"))] pool = pd.concat([pd.read_parquet(os.path.join(dist, "full", f"{s}.parquet")) for s in _splits_on_disk("full")]) assert len(pool) == len(src) == 2243, f"full config covers {len(pool)} of {len(src)}" # join on row_src, not on text: identical wordings are not the same row (and can disagree) src["row_src"] = src.index m = pool[["row_src", "text", "source_label", "label", "label_origin"]].merge( src[["row_src", "label", "tweet"]], on="row_src", how="outer", suffixes=("", "_src")) assert len(m) == len(src) and m["label_src"].notna().all(), "row_src coverage mismatch" assert (m["source_label"] == m["label_src"].str.strip().str.lower()).all(), \ "source_label disagrees with upstream" assert (m["text"] == m["tweet"].astype(str).str.replace(r"\s+", " ", regex=True).str.strip()).all(), \ "text is not the whitespace-normalised upstream tweet" ang = pd.concat([pd.read_parquet(os.path.join(dist, "anger_split", f"{s}.parquet")) for s in _splits_on_disk("anger_split")])[["row_src", "label"]] raw = pd.read_csv(os.path.join(out_dir, "anger_ekman_rows.csv")) raw = raw[raw["source_label"] == "anger"][["row_src", "label"]] j = ang.merge(raw, on="row_src", suffixes=("", "_csv")) assert len(j) == len(ang) == len(raw) and (j["label"] == j["label_csv"]).all(), \ "anger_split does not equal the labeller's CSV" print(f"[verify] provenance: {len(pool)} rows vs upstream CSV, {len(ang)} anger rows vs " f"{out_dir}/anger_ekman_rows.csv -> ok") # the card's YAML front matter is what huggingface.co parses into dataset configs: check that it # declares exactly the configs on disk, that its paths resolve, and that `label_idx` matches its # declared ClassLabel names import yaml txt = open(os.path.join(dist, "README.md")).read() fm = yaml.safe_load(txt[txt.index("---") + 3:txt.index("---", txt.index("---") + 3)]) cfgs = {c["config_name"]: c for c in fm["configs"]} assert list(cfgs) == list(CONFIGS), f"card configs {list(cfgs)} != {list(CONFIGS)}" assert [n for n, c in cfgs.items() if c.get("default")] == ["balanced"], "default config" for name, c in cfgs.items(): declared_splits = [d["split"] for d in c["data_files"]] on_disk = _splits_on_disk(name) assert sorted(declared_splits) == sorted(on_disk), \ f"{name}: card declares {declared_splits} but disk has {on_disk}" for d in c["data_files"]: p = os.path.join(dist, d["path"]) assert os.path.exists(p), f"card points at a missing file: {d['path']}" import pyarrow.parquet as pq names = pq.read_schema(p).field("label_idx").metadata declared = list(LABELS_BINARY if name.startswith("anger") else LABELS_EKMAN) if names: assert json.loads(names.decode()).get("names") == declared, f"{d['path']}: ClassLabel names" n_total = sum(len(pd.read_parquet(os.path.join(dist, name, f"{s}.parquet"))) for s in _splits_on_disk(name)) assert n_total == sum(info["splits"][name].values()), f"{name}: card/parquet row mismatch" print(f"[verify] card YAML: {len(cfgs)} configs, default=balanced, every declared path exists " f"and carries the right ClassLabel names") return True def main(): ap = argparse.ArgumentParser() ap.add_argument("--dist", default="dist") ap.add_argument("--out-dir", default=OUT_DIR, help="dir holding anger_ekman_rows.csv") ap.add_argument("--repo", default="mahalisyarifuddin/emotweetid-ekman7", help="recorded in build_info") a = ap.parse_args() os.makedirs(a.dist, exist_ok=True) df, _ = load_pool(a.out_dir) df = add_text_group(df) ang_pool = df[df["label_origin"] == "laya_anger_split"].reset_index(drop=True) tables, splits, per_class, dropped = {}, {}, {}, {} for name, labels in (("balanced", LABELS_EKMAN), ("full", LABELS_EKMAN), ("anger_split", LABELS_BINARY), ("anger_split_balanced", LABELS_BINARY)): base = df if name in ("full", "balanced") else ang_pool if name in SPLIT_CONFIGS: base, per_class[name], dropped[name] = balanced_pool(base, labels) assert sum(base["label"].value_counts().values) % 10 == 0, "a split config needs 10 | N" sub = stratified_811(base, SEED) expected = apportion(len(sub)) got = [int((sub["split"] == s).sum()) for s in SPLITS] assert got == expected, f"{name}: {got} != 8b:b:b {expected}" else: per_class[name] = int(base["label"].value_counts().min()) sub = base.copy() sub["split"] = SPLITS[0] # the whole pool, one split, nothing held out tables[name] = sub splits[name] = {s: int((sub["split"] == s).sum()) for s in SPLITS if (sub["split"] == s).any()} print(f"[build] {name}: {write_parquet(sub, labels, a.dist, name)} " f"({splits[name]}, per-class>={per_class[name]})") info = build_info(df, tables, splits, per_class, a.out_dir, os.path.join(a.dist, "build_info.json"), dropped=dropped) info["repo"] = a.repo with open(os.path.join(a.dist, "README.md"), "w") as f: f.write(render_readme(info)) with open(os.path.join(a.dist, ".gitattributes"), "w") as f: f.write("*.parquet filter=lfs diff=lfs merge=lfs -text\n") found = set() for f in sorted(os.listdir(".")): if f in SHIPPED: shutil.copy(f, os.path.join(a.dist, f)) found.add(f) assert found == set(SHIPPED), f"not shipped: {sorted(set(SHIPPED) - found)}" if os.path.isdir("runs"): os.makedirs(os.path.join(a.dist, "runs"), exist_ok=True) for f in sorted(os.listdir("runs")): shutil.copy(os.path.join("runs", f), os.path.join(a.dist, "runs", f)) os.makedirs(os.path.join(a.dist, "out"), exist_ok=True) for f in ("veto_check.json", "speedup.json", "timings.json", "anger_ekman_rows.csv", "probe_quality_id.json", "audit_flips.csv", "audit_summary.json", "reconfirm.json", "cache_id_core.json", "cache_id_core_swap.json", "cache_id_diag.json", "cache_id_veto.json"): p = os.path.join(a.out_dir, f) if os.path.exists(p): shutil.copy(p, os.path.join(a.dist, "out", f)) # the previous revision's run artefacts, so the new-vs-old comparison in the card is reproducible if os.path.isdir(PREV_DIR) and os.path.abspath(PREV_DIR) != os.path.abspath(a.out_dir): prev_out = os.path.join(a.dist, "out_prev") os.makedirs(prev_out, exist_ok=True) for f in sorted(os.listdir(PREV_DIR)): src = os.path.join(PREV_DIR, f) if os.path.isfile(src): shutil.copy(src, os.path.join(prev_out, f)) print("[write] out_prev/ = the previous revision's caches", sorted(os.listdir(prev_out))) with open(os.path.join(a.dist, "build_info.json"), "w") as f: # now incl. repo json.dump(info, f, indent=1, sort_keys=True) print("[write] README.md,", json.dumps({k: info[k] for k in ("n_pool", "n_anger_pool", "n_contempt", "n_anger_kept", "share_contempt", "n_balanced", "laya_seconds")})) # nothing that is not part of the dataset may reach the published tree (working notes and the # build scratch dir are the two that have been tempting) forbidden = [f for f in os.listdir(a.dist) if f.upper().startswith(("REVISION_NOTES", "NOTES", "TODO", "CHANGELOG")) or f in ("build", "models", "data", "dist")] assert not forbidden, f"refusing to publish: {forbidden}" verify(a.dist, a.out_dir) if __name__ == "__main__": main()