emotweetid-ekman7 / label_anger_id.py
mahalisyarifuddin's picture
Anger pool re-decided from the Indonesian text only; exact 8b:1b:1b balanced splits; whole pools unsplit in `full`/`anger_split`; option-order control, probe matrix, flip audit and second-run reconfirmation shipped
675bd91 verified
Raw History Blame Contribute Delete
13.3 kB
#!/usr/bin/env python
"""Split EmoTweetID's `anger` pool into `anger` vs `contempt` with laya - **Indonesian only**.
Difference from `label_anger.py`: the English translation (`tweet_en`) is never shown to the model.
The published run read every tweet twice, once in Indonesian and once in EmoTweetID's machine
translation, and pooled the two; the translation mistranslates the slang and code-mixing these
tweets are made of (`GUA MURKA` -> "THE CAVE IS ANGER"), so the English reading is what defined
122 of the 475 shipped labels. Here the decision is made from `text` alone.
Stages (all on Indonesian text; the question wording stays laya's own English prompt, i.e. the
criteria are Ekman's, quoted in the language they were written in):
id_core `ekman` choice on all 475 rows. Same stage name, questions and texts as the
published `out/cache_id_core.json`, so this stage must reproduce that cache
*exactly* - the run asserts it and the card quotes the agreement. This is the
primary reading.
id_core_swap the same choice with the two criteria in the opposite order. Measured on the
probe set, the option listed second is favoured (mean P(anger) on contempt probes
0.31 with anger first vs 0.48 with contempt first), so the swapped pass records how
much of the contempt shift is prompt-order artifact. `p_anger_swapped` ships on
every row; the average of the two orders is the debiased reading.
id_diag Ekman's core-feature probes (superiority, blocked_or_unfair) - only on the rows
where the primary choice reading is not decisive (|margin| < 0.10).
id_veto the `not_anger_or_contempt` diagnostic on all rows (card: do not filter on it).
Output: out/anger_ekman_rows.csv, out/timings.json, out/cache_<stage>.json.
"""
import argparse
import hashlib
import json
import os
import re
import sys
import time
import numpy as np
import pandas as pd
def norm(s):
return re.sub(r"\s+", " ", str(s)).strip()
def cache_path(out_dir, stage):
return os.path.join(out_dir, "cache_%s.json" % stage)
def load_cache(path):
if os.path.exists(path):
with open(path) as f:
return {k: v for k, v in json.load(f).items()}
return {}
def save_cache(path, cache):
tmp = path + ".tmp"
with open(tmp, "w") as f:
json.dump(cache, f)
os.replace(tmp, path)
def run_stage(agent, laya_opt, questions, texts, out_dir, stage, max_len, head_max_len, budget):
"""Score `texts` with `questions`, one cache row per (text, stage) so a re-run resumes."""
cache = load_cache(cache_path(out_dir, stage))
todo_idx, todo_txt = [], []
for t in texts:
key = hashlib.sha1(("%s|%s" % (stage, t)).encode()).hexdigest()[:16]
if key not in cache:
todo_idx.append(key)
todo_txt.append(t)
print("[stage %s] %d rows to score, %d already cached" % (
stage, len(todo_txt), len(texts) - len(todo_txt)), flush=True)
t0 = time.time()
if todo_txt:
res, stats = laya_opt.score_texts(agent, questions, todo_txt, max_len=max_len,
head_max_len=head_max_len, token_budget=budget,
log=lambda *a: None)
for k, r in zip(todo_idx, res):
cache[k] = r
save_cache(cache_path(out_dir, stage), cache)
print("[stage %s] %s" % (stage, json.dumps(stats)), flush=True)
else:
stats = {"seconds": 0.0}
out = []
for t in texts:
key = hashlib.sha1(("%s|%s" % (stage, t)).encode()).hexdigest()[:16]
if key not in cache:
raise RuntimeError("cache miss for %s after stage %s" % (key, stage))
out.append(cache[key])
return out, stats
def combine_id(probs, swap=None, sup=None, blk=None, choice_margin=0.10, noul_margin=0.05):
"""(label, label_source, margin, p_anger, p_contempt).
Rules, in order - the single-reading version of `ekman_questions.combine`:
1. the Indonesian choice reading is decisive (|p(anger) - p(contempt)| >= 0.10) -> its argmax
(`ekman_choice_id`).
2. not decisive -> Ekman's core-feature probes break the tie: superiority => contempt,
blocked-or-unfair => anger (`ekman_noul_tiebreak`).
3. not decisive and probes agree too -> the *order-averaged* reading decides if it has a
side to pick (`ekman_choice_order_avg`).
4. still nothing -> keep the upstream EmoTweetID label `anger`: this dataset only ever splits
an existing anger pool, it does not re-litigate it (`kept_original_label`).
"""
p_a, p_c = probs["anger"], probs["contempt"]
m = p_a - p_c
src = "ekman_choice_id"
if abs(m) < choice_margin:
m = m
if sup is not None and blk is not None and abs(sup - blk) >= noul_margin:
lab = "contempt" if sup > blk else "anger"
return lab, "ekman_noul_tiebreak", m, p_a, p_c
if swap is not None:
ma = ((p_a + swap["anger"]) - (p_c + swap["contempt"])) / 2.0
if abs(ma) >= choice_margin:
return ("anger" if ma >= 0 else "contempt"), "ekman_choice_order_avg", m, p_a, p_c
return "anger", "kept_original_label", m, p_a, p_c
return ("anger" if p_a >= p_c else "contempt"), src, m, p_a, p_c
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--max-len", type=int, default=256)
ap.add_argument("--head-max-len", type=int, default=144)
ap.add_argument("--token-budget", type=int, default=6144)
ap.add_argument("--margin", type=float, default=0.10)
ap.add_argument("--out", default="build/out")
ap.add_argument("--limit", type=int, default=0)
ap.add_argument("--no-swap", action="store_true", help="skip the option-order control pass")
ap.add_argument("--no-veto", action="store_true", help="skip the not_anger_or_contempt diagnostic")
args = ap.parse_args()
os.makedirs(args.out, exist_ok=True)
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import laya_opt
from ekman_questions import CHOICE_MARGIN, EKMAN_QUESTIONS, assert_option_budget
t_load = time.time()
agent = laya_opt.load_agent()
print("[laya] agent ready in %.1fs (%d params)" % (
time.time() - t_load, sum(p.numel() for p in agent.model.parameters())), flush=True)
assert_option_budget(agent.tok)
print("[laya] option budget ok: every criterion fits laya's 48-token cap", flush=True)
# ---- data: identical input to the published run, so the Indonesian stage is comparable -------
f1 = pd.read_csv("data/file1.csv", index_col=0)
f2 = pd.read_csv("data/file2.csv", index_col=0)
assert len(f1) == len(f2) and (f1.index == f2.index).all(), "the two EmoTweetID files must align"
df = f1.join(f2)
df = df[df["label"] == "anger"].copy()
df["row_src"] = df.index
df["text_en"] = df["tweet_en"].map(norm)
df["text_id"] = df["tweet"].map(norm)
df = df[df["text_en"].str.len() > 0]
if args.limit:
df = df.iloc[:args.limit]
n = len(df)
print("[data] %d rows labelled anger (of %d annotated tweets)" % (n, len(f1)), flush=True)
id_texts = df["text_id"].tolist()
timings, stage_rows = {}, {}
# ---- stage 1: the split itself, Indonesian, laya's own criteria order ------------------------
qC = {"ekman": EKMAN_QUESTIONS["ekman"]}
ansC, s = run_stage(agent, laya_opt, qC, id_texts, args.out, "id_core", args.max_len,
args.head_max_len, args.token_budget)
timings["id_core"] = s["seconds"]; stage_rows["id_core"] = s.get("rows", 0)
# ---- stage 1b: option-order control (contempt listed first) ---------------------------------
ansS = [None] * n
if not args.no_swap:
qS = {"ekman": {"type": "choice",
"instructions": EKMAN_QUESTIONS["ekman"]["instructions"],
"criteria": {"contempt": EKMAN_QUESTIONS["ekman"]["criteria"]["contempt"],
"anger": EKMAN_QUESTIONS["ekman"]["criteria"]["anger"]}}}
ansS, s = run_stage(agent, laya_opt, qS, id_texts, args.out, "id_core_swap", args.max_len,
args.head_max_len, args.token_budget)
timings["id_core_swap"] = s["seconds"]; stage_rows["id_core_swap"] = s.get("rows", 0)
# ---- stage 2: core-feature probes, only where the choice reading could not settle it ---------
ambiguous = [i for i in range(n)
if abs(ansC[i]["ekman"]["probabilities"]["anger"]
- ansC[i]["ekman"]["probabilities"]["contempt"]) < args.margin]
print("[stage id_diag] %d/%d rows not decided by the Indonesian choice reading" % (
len(ambiguous), n), flush=True)
ansD = [dict() for _ in range(n)]
if ambiguous:
qD = {k: EKMAN_QUESTIONS[k] for k in ("superiority", "blocked_or_unfair")}
sub = [id_texts[i] for i in ambiguous]
res, s = run_stage(agent, laya_opt, qD, sub, args.out, "id_diag", args.max_len,
args.head_max_len, args.token_budget)
for i, r in zip(ambiguous, res):
ansD[i] = r
timings["id_diag"] = s["seconds"]; stage_rows["id_diag"] = s.get("rows", 0)
# ---- stage 3: the off-topic veto, as a diagnostic only ---------------------------------------
ansV = [None] * n
if not args.no_veto:
qV = {"not_anger_or_contempt": EKMAN_QUESTIONS["not_anger_or_contempt"]}
ansV, s = run_stage(agent, laya_opt, qV, id_texts, args.out, "id_veto", args.max_len,
args.head_max_len, args.token_budget)
timings["id_veto"] = s["seconds"]; stage_rows["id_veto"] = s.get("rows", 0)
# ---- combine ---------------------------------------------------------------------------------
rows = []
for i in range(n):
probs = ansC[i]["ekman"]["probabilities"]
swap = ansS[i]["ekman"]["probabilities"] if ansS[i] else None
diag = ansD[i]
sup = diag.get("superiority", {}).get("noul")
blk = diag.get("blocked_or_unfair", {}).get("noul")
label, src, m, p_a, p_c = combine_id(probs, swap, sup, blk, args.margin)
rows.append({
"row_src": int(df["row_src"].iloc[i]),
"text": id_texts[i],
"text_en": df["text_en"].iloc[i],
"source_label": "anger",
"label": label,
"label_source": src,
"ekman_p_anger": round(p_a, 4),
"ekman_p_contempt": round(p_c, 4),
"ekman_confidence": round(ansC[i]["ekman"]["confidence"], 4),
"ekman_margin_id": round(m, 4),
"p_anger_id": round(probs["anger"], 4),
"p_anger_swapped": None if swap is None else round(swap["anger"], 4),
"en_id_agree": None,
"p_superiority": None if sup is None else round(sup, 4),
"p_blocked_or_unfair": None if blk is None else round(blk, 4),
"p_not_anger_or_contempt": None if ansV[i] is None else
round(ansV[i]["not_anger_or_contempt"]["noul"], 4),
"ambiguous": bool(abs(m) < CHOICE_MARGIN),
})
out = pd.DataFrame(rows)
out.to_csv(os.path.join(args.out, "anger_ekman_rows.csv"), index=False)
prev_path = os.path.join(args.out, "timings.json")
if os.path.exists(prev_path):
prev = json.load(open(prev_path))
for k, v in prev.get("stages", {}).items():
if timings.get(k, 0) in (0, 0.0) and v:
timings[k] = v
for k, v in prev.get("stage_rows", {}).items():
stage_rows.setdefault(k, v)
with open(os.path.join(args.out, "timings.json"), "w") as f:
json.dump({"rows": n, "ambiguous_rows": len(ambiguous),
"total_laya_seconds": round(sum(timings.values()), 1), "stages": timings,
"stage_rows": {k: v for k, v in stage_rows.items() if v},
"max_len": args.max_len, "head_max_len": args.head_max_len,
"token_budget": args.token_budget, "margin": args.margin,
"language": "id-only"}, f, indent=2)
print("\n=== laya anger/contempt split (Indonesian only) ===", flush=True)
print(out["label"].value_counts().to_string())
print("\nlabel provenance:\n" + out["label_source"].value_counts().to_string())
print("\ncontempt share of the pool: %.1f%%" % (100.0 * (out["label"] == "contempt").mean()))
print("ambiguous (|margin|<%.2f): %d" % (args.margin, out["ambiguous"].sum()))
if out["p_anger_swapped"].notna().any():
print("mean P(anger): as prompted %.3f | swapped %.3f" % (
out["p_anger_id"].mean(), out["p_anger_swapped"].mean()))
flips = int(((out["p_anger_id"] >= 0.5) != (out["p_anger_swapped"] >= 0.5)).sum())
print("rows whose argmax flips with the option order: %d (%.1f%%)" % (flips, 100.0 * flips / n))
if out["p_not_anger_or_contempt"].notna().any():
print("p(not anger or contempt) > 0.5: %d" % (out["p_not_anger_or_contempt"] > 0.5).sum())
print("laya seconds: %s" % json.dumps(timings))
if __name__ == "__main__":
main()