Images / figures /prompt_ablation /plot_summary.py
Jialuo21's picture
Add figures (155 files)
74349a1 verified
Raw History Blame Contribute Delete
10.6 kB
"""Plot the Part-1 Summary of prompt_ablation.txt as a line+marker chart.
Two panels (one per base model: FLUX.2-4B and Z-Image). Each variant gets one
line connecting its score across the 5 benchmarks. Balance is rendered in
saturated Google blue (thick line, large markers) to highlight it; the other
three variants share their Google brand colours but lightened.
Y-axis is normalised per benchmark to [0, 100] using each benchmark's
theoretical bounds, then the panel's y range is auto-clipped around the data
so meaningful differences are visible:
T2I-CoReBench-Composition: 0 - 100
TIIF-Bench : 0 - 100
SpatialGenEval : 0 - 100
T2I-CompBench : 1 - 5
LongBench-T2I : 1 - 5
"""
from __future__ import annotations
import re
from pathlib import Path
import matplotlib.colors as mcolors
import matplotlib.font_manager as fm
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib.offsetbox import AnchoredText
from matplotlib.ticker import MaxNLocator
# Register and select the shared STIX Two Text typeface.
_FONT = Path(__file__).resolve().parent.parent / "_fonts" / "STIX-Two-Text-Regular.ttf"
fm.fontManager.addfont(str(_FONT))
_FAMILY = fm.FontProperties(fname=str(_FONT)).get_name()
plt.rcParams.update({
"font.family": _FAMILY,
"font.serif": [_FAMILY, "DejaVu Serif"],
"mathtext.fontset": "stix",
"axes.unicode_minus": False,
})
ROOT = Path(__file__).resolve().parent
SRC = ROOT.parent.parent / "sheet_exports" / "prompt_ablation.txt"
# Ordered by mean prompt length (short -> long), measured on each test split.
# T2I-CompBench ~9 words, TIIF-Bench ~50, SpatialGenEval ~66,
# T2I-CoReBench-Composition ~129, LongBench-T2I ~539.
BENCHMARKS = [
"T2I-CompBench",
"TIIF-Bench",
"SpatialGenEval",
"T2I-CoReBench-Composition",
"LongBench-T2I",
]
BOUNDS = {
"T2I-CoReBench-Composition": (0.0, 100.0),
"TIIF-Bench": (0.0, 100.0),
"T2I-CompBench": (1.0, 5.0),
"LongBench-T2I": (1.0, 5.0),
"SpatialGenEval": (0.0, 100.0),
}
DISPLAY = {
"T2I-CompBench": "T2I-\nCompBench",
"TIIF-Bench": "TIIF-\nBench",
"SpatialGenEval": "Spatial-\nGenEval",
"T2I-CoReBench-Composition": "T2I-CoReBench-\nComposition",
"LongBench-T2I": "LongBench-\nT2I",
}
VARIANTS = ["Balance", "Attribute", "Entity", "Relation"]
COLORS = {
"Balance": "#4285F4",
"Attribute": "#EA4335",
"Entity": "#FBBC05",
"Relation": "#34A853",
}
MARKERS = {
"Balance": "o",
"Attribute": "s",
"Entity": "D",
"Relation": "^",
}
HIGHLIGHT = "Balance"
BASES = [("FLUX.2-Klein-Base-4B", "FLUX.2-4B"), ("Z-Image", "Z-Image")]
LEGEND_LABELS = {
"Balance": "Balanced",
"Attribute": "Attribute-Centric",
"Entity": "Entity-Centric",
"Relation": "Relation-Centric",
}
# ---------------------------------------------------------------------------
# 视觉调节区 STYLE: 改下面这些数字就能调节图的字号 / 线宽 / 点大小 / 间距等
# ---------------------------------------------------------------------------
STYLE = {
# 整张图的画布尺寸 (英寸): (宽, 高). 想把图整体拉高/拉宽就改这里.
"fig_size": (20.5, 6.0),
# ---- 顶部 legend (Omni-Centric / Attribute-Centric / ...) ----
"legend_fontsize": 25, # 顶部 legend 文字字号
"legend_marker_size": 20, # 顶部 legend 上的点 (圆/方/菱形/三角) 大小
"legend_line_width": 5.0, # 顶部 legend 上小线段的粗细
"legend_handle_len": 3.0, # 顶部 legend 上小线段的长度
"legend_col_spacing": 3.0, # 顶部 legend 各项之间的水平距离 (越小越挤)
"legend_text_pad": 0.8, # 顶部 legend 里 "线条" 和 "文字" 之间的间隙
"legend_y_anchor": 1.06, # 顶部 legend 的垂直位置 (>1 即在画布顶部之上)
# ---- 每个 panel 内的标题框 (FLUX.2-Klein-Base-4B / Z-Image) ----
"panel_title_fontsize": 30, # panel 内白色标题框里的文字字号
# ---- 坐标轴文字 ----
"ylabel_fontsize": 26, # 左边 "Score" 这个纵坐标标题字号
"ytick_fontsize": 23, # 纵坐标刻度数字 (10, 20, ...) 字号
"xtick_fontsize": 23, # 横坐标 benchmark 名字 (TIIF-Bench 等) 字号
# ---- 折线图本体 (panel 里的曲线和数据点) ----
"highlight_line_width": 7, # 高亮变体 (Balance/Omni-Centric) 的线粗
"highlight_marker_size": 25, # 高亮变体的数据点大小
"other_line_width": 3.5, # 其他变体 (Attribute/Entity/Relation) 的线粗
"other_marker_size": 18, # 其他变体的数据点大小
"marker_edge_width": 1.0, # 数据点白色描边的粗细
}
# ---------------------------------------------------------------------------
def load_part1_summary(path: Path) -> pd.DataFrame:
text = path.read_text()
part1 = re.search(r"=== Part 1:.*?\n(.*?)(?:\n=== Part 2:|\Z)", text, re.DOTALL).group(1)
summary = re.search(r"=== Summary ===\n(.*?)(?:\n=== |\Z)", part1, re.DOTALL).group(1)
lines = [ln for ln in summary.strip().splitlines() if ln.strip()]
header = lines[0].split("\t")
rows = [ln.split("\t") for ln in lines[1:]]
df = pd.DataFrame(rows, columns=header).set_index("Models")
return df.apply(pd.to_numeric, errors="coerce")
def normalise(value: float, bench: str) -> float:
lo, hi = BOUNDS[bench]
return (value - lo) / (hi - lo) * 100.0
def lighten(color, amount: float = 0.55):
r, g, b = mcolors.to_rgb(color)
return (r + (1 - r) * amount, g + (1 - g) * amount, b + (1 - b) * amount)
def main() -> None:
df = load_part1_summary(SRC)
fig, axes = plt.subplots(1, 2, figsize=STYLE["fig_size"], sharey=False)
x = np.arange(len(BENCHMARKS))
for ax, (base_label, base_prefix) in zip(axes, BASES):
per_v_norm: dict[str, np.ndarray] = {}
for v in VARIANTS:
row = f"{base_prefix}-{v}"
raw = np.array([df.loc[row, b] if row in df.index else np.nan for b in BENCHMARKS])
per_v_norm[v] = np.array([normalise(r, b) for r, b in zip(raw, BENCHMARKS)])
# Draw non-highlight variants first (light), then Balance on top.
ordered = [v for v in VARIANTS if v != HIGHLIGHT] + [HIGHLIGHT]
for v in ordered:
base = COLORS[v]
is_hi = v == HIGHLIGHT
if is_hi:
line_c = base
pt_face = base
pt_edge = "white"
lw = STYLE["highlight_line_width"]
ms = STYLE["highlight_marker_size"]
alpha = 1.0
z = 5
else:
line_c = lighten(base, 0.50)
pt_face = lighten(base, 0.45)
pt_edge = "white"
lw = STYLE["other_line_width"]
ms = STYLE["other_marker_size"]
alpha = 0.85
z = 3
ax.plot(x, per_v_norm[v], color=line_c, lw=lw, alpha=alpha, zorder=z)
ax.scatter(x, per_v_norm[v], color=pt_face, marker=MARKERS[v],
s=ms ** 2, edgecolor=pt_edge,
linewidth=STYLE["marker_edge_width"],
alpha=alpha, zorder=z + 1)
# Auto y range: clip tightly around the data so the lines fill the panel.
all_vals = np.concatenate(list(per_v_norm.values()))
all_vals = all_vals[~np.isnan(all_vals)]
lo, hi = float(np.min(all_vals)), float(np.max(all_vals))
pad = max((hi - lo) * 0.08, 0.5)
ax.set_ylim(lo - pad, hi + pad)
ax.set_xticks(x)
ax.set_xticklabels([DISPLAY[b] for b in BENCHMARKS],
fontsize=STYLE["xtick_fontsize"],
rotation=0, ha="center")
# Title rendered as a small framed legend-style box in the upper-left.
title_box = AnchoredText(
base_label, loc="upper right",
prop=dict(size=STYLE["panel_title_fontsize"]),
pad=0.4, borderpad=0.6, frameon=True,
)
title_box.patch.set_edgecolor("0.7")
title_box.patch.set_linewidth(0.8)
title_box.patch.set_facecolor("white")
title_box.patch.set_alpha(0.95)
ax.add_artist(title_box)
ax.tick_params(axis="y", labelsize=STYLE["ytick_fontsize"])
ax.tick_params(axis="x", labelsize=STYLE["xtick_fontsize"],
length=5, width=0.9, direction="out")
ax.grid(True, axis="both", linestyle=":", linewidth=0.8, color="0.55", alpha=1.0)
ax.set_axisbelow(True)
# Sparser, integer-only y ticks.
# Use the auto locator to pick nice integer ticks, then keep only
# those strictly inside the data range so neither the very bottom
# nor the very top of the panel is labelled.
ax.yaxis.set_major_locator(MaxNLocator(nbins=4, integer=True))
fig.canvas.draw()
ax.set_yticks([t for t in ax.get_yticks() if lo < t < hi])
# Keep only the bottom spine.
for side in ("top", "left", "right"):
ax.spines[side].set_visible(False)
ax.spines["bottom"].set_linewidth(0.8)
axes[0].set_ylabel("Score", fontsize=STYLE["ylabel_fontsize"])
handles = []
for v in VARIANTS:
is_hi = v == HIGHLIGHT
line_c = COLORS[v] if is_hi else lighten(COLORS[v], 0.50)
face = COLORS[v] if is_hi else lighten(COLORS[v], 0.45)
handles.append(plt.Line2D([0], [0], color=line_c, marker=MARKERS[v],
markerfacecolor=face, markeredgecolor="white",
markersize=STYLE["legend_marker_size"],
lw=STYLE["legend_line_width"],
label=LEGEND_LABELS[v]))
fig.legend(handles=handles, loc="upper center", ncol=len(VARIANTS),
bbox_to_anchor=(0.5, STYLE["legend_y_anchor"]),
fontsize=STYLE["legend_fontsize"],
frameon=False,
handlelength=STYLE["legend_handle_len"],
columnspacing=STYLE["legend_col_spacing"],
handletextpad=STYLE["legend_text_pad"])
fig.tight_layout(rect=(0, 0, 1, 0.95))
fig.savefig(ROOT / "prompt_type.png", dpi=200, bbox_inches="tight")
fig.savefig(ROOT / "prompt_type.pdf", bbox_inches="tight")
plt.close(fig)
print(f"wrote {ROOT / 'prompt_type.png'} and .pdf")
if __name__ == "__main__":
main()