"""Reruns the arithmetic in my BIPIA note from the paper's tables.

Paper: Yi et al., "Benchmarking and Defending Against Indirect Prompt
Injection Attacks on Large Language Models", KDD 2025 (arXiv 2312.14197v4).
Standard library only.
"""
from math import sqrt

# Test prompts per task (Table 1). Overall ASR weights each task by its count.
N = {"email": 11250, "web": 22500, "table": 22500, "summ": 22500, "code": 7500}
TEXT = ["email", "web", "table", "summ"]

# Table 2: Arena Elo, ASR on email QA, web QA, table QA, summarization,
# code QA, and the reported overall ASR.
TABLE2 = [
    ("GPT-4", 1181, 0.1524, 0.2792, 0.3472, 0.3917, 0.2863, 0.3103),
    ("GPT-3.5-turbo", 1115, 0.1634, 0.2347, 0.2257, 0.3658, 0.2844, 0.2616),
    ("WizardLM-70B", 1099, 0.0757, 0.0049, 0.0181, 0.1816, 0.1867, 0.0795),
    ("Vicuna-33B", 1092, 0.1088, 0.1221, 0.1317, 0.2157, 0.2876, 0.1617),
    ("Llama2-Chat-70B", 1051, 0.1290, 0.1493, 0.2058, 0.2239, 0.2167, 0.1867),
    ("WizardLM-13B", 1047, 0.0760, 0.0048, 0.0181, 0.1819, 0.1817, 0.0791),
    ("Vicuna-13B", 1041, 0.1036, 0.1029, 0.1080, 0.1646, 0.2064, 0.1294),
    ("MPT-30B-chat", 1039, 0.0981, 0.0955, 0.1438, 0.2360, 0.2673, 0.1600),
    ("Guanaco-33B", 1031, 0.0602, 0.0430, 0.0552, 0.1332, 0.3884, 0.1020),
    ("CodeLlama-34B", 1031, 0.0308, 0.0449, 0.0822, 0.2032, 0.1279, 0.1013),
    ("Mistral-7B", 1031, 0.0552, 0.0580, 0.0870, 0.1628, 0.1047, 0.0966),
    ("Llama2-Chat-13B", 1012, 0.1083, 0.1253, 0.1157, 0.2997, 0.1481, 0.1681),
    ("Vicuna-7B", 997, 0.0854, 0.0581, 0.0712, 0.1773, 0.1581, 0.1049),
    ("Llama2-Chat-7B", 985, 0.0965, 0.1230, 0.1161, 0.2645, 0.0671, 0.1498),
    ("Koala-13B", 973, 0.0653, 0.0688, 0.0782, 0.2696, 0.2073, 0.1352),
    ("GPT4All-13B-Snoozy", 959, 0.0816, 0.0472, 0.0590, 0.3155, 0.2343, 0.1410),
    ("ChatGLM2-6B", 945, 0.0260, 0.0152, 0.0211, 0.1403, 0.3060, 0.0761),
    ("MPT-7B-Chat", 938, 0.1139, 0.0480, 0.0709, 0.2023, 0.3536, 0.1294),
    ("RWKV-4-Raven-14B", 933, 0.0610, 0.0132, 0.0202, 0.1225, 0.1092, 0.0581),
    ("Alpaca-13B", 914, 0.0338, 0.0155, 0.0150, 0.2199, 0.1141, 0.0796),
    ("OpenAssistant-Pythia-12B", 905, 0.0751, 0.0317, 0.0341, 0.3175, 0.5153, 0.1546),
    ("ChatGLM-6B", 892, 0.0186, 0.0060, 0.0266, 0.0602, 0.3060, 0.0532),
    ("FastChat-T5-3B", 884, 0.0580, 0.0689, 0.0761, 0.1825, 0.1320, 0.1045),
    ("StableLM-Tuned-Alpaca-7b", 853, 0.0586, 0.0270, 0.0400, 0.0987, 0.1516, 0.0641),
    ("Dolly-V2-12B", 832, 0.0762, 0.0399, 0.0385, 0.1264, 0.3099, 0.0903),
]

# Table 3 (black-box defenses) and Table 4 (white-box defense):
# (model, method): (ROUGE-1 recall, email, web, table, summ, code, overall).
TABLE3 = {
    ("GPT-4", "Original"): (0.6985, 0.1524, 0.2792, 0.3472, 0.3917, 0.2863, 0.3103),
    ("GPT-4", "In-context learning"): (0.6590, 0.1036, 0.2382, 0.3238, 0.3075, 0.0056, 0.2408),
    ("GPT-4", "Multi-turn dialogue"): (0.7201, 0.0959, 0.2585, 0.2974, 0.1810, 0.0097, 0.2056),
    ("GPT-3.5-turbo", "Original"): (0.6554, 0.1634, 0.2347, 0.2257, 0.3658, 0.2844, 0.2616),
    ("GPT-3.5-turbo", "In-context learning"): (0.6289, 0.1779, 0.1600, 0.1910, 0.2560, 0.0789, 0.1884),
    ("GPT-3.5-turbo", "Multi-turn dialogue"): (0.6786, 0.1376, 0.2025, 0.1936, 0.2221, 0.0583, 0.1843),
    ("Vicuna-7B", "Original"): (0.6187, 0.1124, 0.0693, 0.0827, 0.2117, 0.1632, 0.1237),
    ("Vicuna-7B", "In-context learning"): (0.6065, 0.0512, 0.0394, 0.0396, 0.2148, 0.0599, 0.0885),
    ("Vicuna-7B", "Multi-turn dialogue"): (0.6084, 0.1127, 0.0410, 0.0565, 0.0817, 0.0023, 0.0617),
    ("Vicuna-13B", "Original"): (0.6134, 0.1242, 0.1272, 0.1337, 0.2052, 0.1755, 0.1531),
    ("Vicuna-13B", "In-context learning"): (0.6025, 0.2353, 0.1456, 0.1804, 0.1763, 0.0468, 0.1658),
    ("Vicuna-13B", "Multi-turn dialogue"): (0.6274, 0.1379, 0.1024, 0.1168, 0.1028, 0.0015, 0.1021),
}
# Table 4 adds the MT-Bench score after ROUGE.
TABLE4 = {
    ("Vicuna-7B", "w/o finetune"): (0.6187, 4.8063, 0.1124, 0.0693, 0.0827, 0.2117, 0.1632, 0.1237),
    ("Vicuna-7B", "BIPIA labels"): (0.5306, 4.2938, 0.0202, 0.0159, 0.0410, 0.0049, 0.0300, 0.0214),
    ("Vicuna-7B", "Original LLM"): (0.6122, 4.5687, 0.0015, 0.0062, 0.0057, 0.0043, 0.2244, 0.0240),
    ("Vicuna-7B", "GPT-4"): (0.6260, 4.8312, 0.0065, 0.0045, 0.0046, 0.0037, 0.0129, 0.0053),
    ("Vicuna-13B", "w/o finetune"): (0.6134, 5.2062, 0.1242, 0.1272, 0.1337, 0.2052, 0.1755, 0.1531),
    ("Vicuna-13B", "BIPIA labels"): (0.6109, 1.6625, 0.0217, 0.0126, 0.0370, 0.0064, 0.0207, 0.0192),
    ("Vicuna-13B", "Original LLM"): (0.6240, 4.3375, 0.0024, 0.0055, 0.0051, 0.0034, 0.0067, 0.0046),
    ("Vicuna-13B", "GPT-4"): (0.6337, 4.5500, 0.0060, 0.0044, 0.0057, 0.0036, 0.0036, 0.0047),
}


def weighted(asrs, tasks):
    return sum(a * N[t] for a, t in zip(asrs, tasks)) / sum(N[t] for t in tasks)


def pearson(x, y):
    mx, my = sum(x) / len(x), sum(y) / len(y)
    sxy = sum((a - mx) * (b - my) for a, b in zip(x, y))
    sxx = sum((a - mx) ** 2 for a in x)
    syy = sum((b - my) ** 2 for b in y)
    return sxy / sqrt(sxx * syy)


def ranks(v):
    order = sorted(range(len(v)), key=lambda i: v[i])
    r = [0.0] * len(v)
    i = 0
    while i < len(v):
        j = i
        while j + 1 < len(v) and v[order[j + 1]] == v[order[i]]:
            j += 1
        for k in range(i, j + 1):
            r[order[k]] = (i + j) / 2 + 1
        i = j + 1
    return r


def spearman(x, y):
    return pearson(ranks(x), ranks(y))


print("1. Overall ASR in Table 2 is the prompt-weighted mean of the five tasks")
worst = max(abs(weighted(r[2:7], TEXT + ["code"]) - r[7]) for r in TABLE2)
print(f"   largest gap between recomputed and reported overall ASR: {worst:.5f}")

lo = min(TABLE2, key=lambda r: r[7])
hi = max(TABLE2, key=lambda r: r[7])
print(f"   overall ASR runs from {lo[7]:.4f} ({lo[0]}) to {hi[7]:.4f} ({hi[0]})")
cols = ["email", "web", "table", "summ", "code", "overall"]
means = [sum(r[2 + i] for r in TABLE2) / len(TABLE2) for i in range(6)]
print("   column means (paper's Average row: 0.0730 0.0615 0.0771 0.1966 0.2411 0.1179):")
print("   " + "  ".join(f"{c} {m:.4f}" for c, m in zip(cols, means)))

print("\n2. Capability (Arena Elo) against ASR, Figure 2 (25 models)")
elo = [r[1] for r in TABLE2]
series = {
    "all tasks": [r[7] for r in TABLE2],
    "text tasks": [weighted(r[2:6], TEXT) for r in TABLE2],
    "code task": [r[6] for r in TABLE2],
}
paper = {"all tasks": 0.6423, "text tasks": 0.6635, "code task": -0.0254}
keep = [i for i, r in enumerate(TABLE2) if r[0] not in ("GPT-4", "GPT-3.5-turbo")]
for name, y in series.items():
    r_all = pearson(elo, y)
    r_wo = pearson([elo[i] for i in keep], [y[i] for i in keep])
    rho = spearman(elo, y)
    print(f"   {name:10s} Pearson {r_all:+.4f} (paper {paper[name]:+.4f}) | "
          f"Spearman {rho:+.4f} | Pearson without the two GPT models {r_wo:+.4f}")

print("\n   Within one family, larger model against overall ASR:")
for family in (["Llama2-Chat-7B", "Llama2-Chat-13B", "Llama2-Chat-70B"],
               ["Vicuna-7B", "Vicuna-13B", "Vicuna-33B"],
               ["WizardLM-13B", "WizardLM-70B"]):
    t2 = {r[0]: r for r in TABLE2}
    print("   " + " -> ".join(f"{m} {t2[m][7]:.4f}" for m in family))

print("\n3. Black-box defenses, change in overall ASR (Table 3)")
for model in ["GPT-4", "GPT-3.5-turbo", "Vicuna-7B", "Vicuna-13B"]:
    base = TABLE3[(model, "Original")]
    assert abs(weighted(base[1:6], TEXT + ["code"]) - base[6]) <= 1e-4
    for method in ["In-context learning", "Multi-turn dialogue"]:
        row = TABLE3[(model, method)]
        assert abs(weighted(row[1:6], TEXT + ["code"]) - row[6]) <= 1e-4
        change = (row[6] - base[6]) / base[6] * 100
        print(f"   {model:14s} {method:20s} {base[6]:.4f} -> {row[6]:.4f} ({change:+.1f}%)")

print("\n4. The Vicuna baselines in Table 3 differ from the same models in Table 2")
t2 = {r[0]: r for r in TABLE2}
for model in ["GPT-4", "GPT-3.5-turbo", "Vicuna-7B", "Vicuna-13B"]:
    a = t2[model][2:8]
    b = TABLE3[(model, "Original")][1:7]
    same = all(abs(x - y) < 1e-9 for x, y in zip(a, b))
    print(f"   {model:14s} overall ASR Table 2 {a[-1]:.4f}, Table 3 {b[-1]:.4f}  "
          f"{'identical' if same else 'DIFFERENT'}")

print("\n5. White-box defense (Table 4)")
for model in ["Vicuna-7B", "Vicuna-13B"]:
    base = TABLE4[(model, "w/o finetune")]
    for source in ["BIPIA labels", "Original LLM", "GPT-4"]:
        row = TABLE4[(model, source)]
        print(f"   {model:10s} {source:12s} overall ASR {base[7]:.4f} -> {row[7]:.4f} "
              f"({base[7] / row[7]:.1f}x lower) | MT-Bench {base[1]:.2f} -> {row[1]:.2f} "
              f"({row[1] - base[1]:+.2f}) | ROUGE-1 {base[0]:.4f} -> {row[0]:.4f} "
              f"| code ASR {base[6]:.4f} -> {row[6]:.4f}")

print("\n6. Where the 86,250 test prompts come from (Table 1)")
contexts = {"email": 50, "web": 100, "table": 100, "summ": 100, "code": 50}
attacks = {"email": 75, "web": 75, "table": 75, "summ": 75, "code": 50}
for t in N:
    assert contexts[t] * attacks[t] * 3 == N[t]
print(f"   {sum(N.values()):,} prompts = {sum(contexts.values())} external texts x "
      f"75 text or 50 code attacks x 3 positions; 125 distinct attack instructions")

print("\n7. Scorers for the 75 test text attacks (counted in the repository's")
print("   bipia/metrics/regist.py, commit a004b69; not in the paper)")
judge = 25 + 15 + (25 - 2)   # task-irrelevant, cipher/base/reverse, targeted minus two
match_text, emoji, language = 2, 5, 5
assert judge + match_text + emoji + language == 75
print(f"   LLM judge {judge}, fuzzy match {match_text}, emoji rule {emoji}, "
      f"language detection {language}; all 50 code attacks use fuzzy matching")

print("\n8. The GPT rows changed between arXiv v1 (December 2023) and v4")
# GPT-4 and GPT-3.5-turbo rows as printed in v1 (Table IV there); the other
# 23 models have the same values in both versions.
V1_GPT = {
    "GPT-4": (0.0255, 0.1212, 0.1521, 0.2048, 0.5277, 0.1740),
    "GPT-3.5-turbo": (0.1025, 0.1025, 0.1430, 0.2111, 0.4195, 0.1690),
}
v1 = [r if r[0] not in V1_GPT else (r[0], r[1]) + V1_GPT[r[0]] for r in TABLE2]
for name, vals in V1_GPT.items():
    now = next(r for r in TABLE2 if r[0] == name)
    print(f"   {name:14s} overall ASR v1 {vals[-1]:.4f}, v4 {now[7]:.4f}")
mean_v1 = sum(r[7] for r in v1) / len(v1)
mean_v4 = sum(r[7] for r in TABLE2) / len(TABLE2)
print(f"   mean overall ASR of the 25 rows: v1 {mean_v1:.4f}, v4 {mean_v4:.4f} "
      f"(both versions print 0.1179 in the Average row)")
y1 = {
    "all tasks": [r[7] for r in v1],
    "text tasks": [weighted(r[2:6], TEXT) for r in v1],
    "code task": [r[6] for r in v1],
}
paper_v1 = {"all tasks": 0.5218, "text tasks": 0.4946, "code task": 0.2188}
for name, y in y1.items():
    print(f"   {name:10s} Pearson with the v1 GPT rows {pearson(elo, y):+.4f} "
          f"(v1 paper {paper_v1[name]:+.4f}; v4 paper {paper[name]:+.4f})")
