OPD icon indicating copy to clipboard operation
OPD copied to clipboard

关于实验中有关教师和学生模型的熵扩散现象

Open overloadedHenry opened this issue 5 months ago • 1 comments

非常有趣的 OPD 分析!请问如何去复现图 13 和图 23 的可视化图?是否可以提供代码或者一些实现细节?

overloadedHenry avatar Jun 22 '26 05:06 overloadedHenry

感谢提问,使用的setting就是 JustRL -> Ds 1.5B的实验,使用的数据集是 DAPO-Math-17k,topk = 16., response length设置为15k

具体实现是你需要每隔10step存一下 student 每个 response 位置的 entropy 和 teacher forward student trace的每个位置的entropy, 把他们存为csv, 然后参考下面的代码画出heatmap

import argparse
import csv
import math
import re
from pathlib import Path

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LinearSegmentedColormap


STEP_DIR_RE = re.compile(r"step_(\d+)")
ENTROPY_COLUMNS = ("avg_teacher_entropy", "avg_entropy")


def parse_args():
    parser = argparse.ArgumentParser(
        description="Plot a response-entropy heatmap from per-step CSV files."
    )
    parser.add_argument(
        "--input_root",
        type=Path,
        default=Path("output"),
        help="Root directory containing step_*/<dataset>_response_entropy_avg.csv.",
    )
    parser.add_argument(
        "--dataset",
        type=str,
        default="deepmath",
        help="Dataset prefix in the CSV filename.",
    )
    parser.add_argument(
        "--num_bins",
        type=int,
        default=32,
        help="Number of position bins shown on the heatmap x-axis.",
    )
    parser.add_argument(
        "--output",
        type=Path,
        default=None,
        help="Optional output figure path. Defaults are chosen based on the discovered CSV layout.",
    )
    parser.add_argument(
        "--title",
        type=str,
        default=None,
        help="Optional figure title.",
    )
    parser.add_argument(
        "--subtitle",
        type=str,
        default=None,
        help="Optional subtitle displayed under the main title.",
    )
    parser.add_argument(
        "--min_step",
        type=int,
        default=None,
        help="Optional inclusive lower bound for training steps.",
    )
    parser.add_argument(
        "--max_step",
        type=int,
        default=None,
        help="Optional inclusive upper bound for training steps.",
    )
    parser.add_argument(
        "--estimated_steps",
        type=str,
        default="",
        help="Comma-separated steps to annotate as estimated, e.g. '250'.",
    )
    return parser.parse_args()


def extract_step(path: Path) -> int:
    for candidate in (path.parent.name, path.stem):
        match = STEP_DIR_RE.fullmatch(candidate)
        if match is not None:
            return int(match.group(1))
    raise ValueError(f"Could not parse training step from path: {path}")


def discover_csvs(input_root: Path, dataset: str):
    csv_name = f"{dataset}_response_entropy_avg.csv"
    legacy_csv_paths = sorted(input_root.glob(f"step_*/{csv_name}"), key=extract_step)
    flat_csv_paths = sorted(input_root.glob("step_*.csv"), key=extract_step)

    if legacy_csv_paths:
        return legacy_csv_paths, "legacy"
    if flat_csv_paths:
        return flat_csv_paths, "flat"

    raise FileNotFoundError(
        f"No CSV files matching step_*/{csv_name} or step_*.csv found under {input_root}"
    )


def filter_csvs_by_step(csv_paths: list[Path], min_step: int | None, max_step: int | None) -> list[Path]:
    filtered_paths = []
    for csv_path in csv_paths:
        step = extract_step(csv_path)
        if min_step is not None and step < min_step:
            continue
        if max_step is not None and step > max_step:
            continue
        filtered_paths.append(csv_path)

    if not filtered_paths:
        raise ValueError(
            f"No step CSVs remain after filtering with min_step={min_step} and max_step={max_step}."
        )

    return filtered_paths


def parse_step_set(step_text: str) -> set[int]:
    if not step_text.strip():
        return set()
    return {int(part.strip()) for part in step_text.split(",") if part.strip()}


def detect_entropy_column(fieldnames: list[str] | None, csv_path: Path) -> str:
    if fieldnames is None:
        raise ValueError(f"CSV has no header row: {csv_path}")

    for column in ENTROPY_COLUMNS:
        if column in fieldnames:
            return column

    raise ValueError(
        f"CSV {csv_path} does not contain any supported entropy column. "
        f"Expected one of: {', '.join(ENTROPY_COLUMNS)}"
    )


def load_step_csv(csv_path: Path):
    positions = []
    entropies = []
    counts = []

    with csv_path.open("r", encoding="utf-8", newline="") as f:
        reader = csv.DictReader(f)
        entropy_column = detect_entropy_column(reader.fieldnames, csv_path)
        for row in reader:
            positions.append(int(row["position"]))
            entropies.append(float(row[entropy_column]))
            counts.append(int(row["count"]))

    if not positions:
        raise ValueError(f"CSV is empty: {csv_path}")

    min_position = min(positions)
    max_position = max(positions)
    if min_position == 0:
        offset = 0
        total_positions = max_position + 1
    elif min_position == 1:
        offset = 1
        total_positions = max_position
    else:
        raise ValueError(
            f"Unsupported position indexing in {csv_path}: expected min(position) to be 0 or 1, got {min_position}"
        )

    entropy_by_position = np.full(total_positions, np.nan, dtype=np.float64)
    count_by_position = np.zeros(total_positions, dtype=np.float64)

    for pos, entropy, count in zip(positions, entropies, counts):
        entropy_by_position[pos - offset] = entropy
        count_by_position[pos - offset] = count

    return entropy_by_position, count_by_position, entropy_column


def pad_to_length(array: np.ndarray, target_len: int, pad_value: float):
    if len(array) >= target_len:
        return array
    padded = np.full(target_len, pad_value, dtype=np.float64)
    padded[: len(array)] = array
    return padded


def weighted_bin_row(entropy_row: np.ndarray, count_row: np.ndarray, num_bins: int):
    if num_bins <= 0:
        raise ValueError("--num_bins must be positive.")

    total_positions = len(entropy_row)
    edges = np.linspace(0, total_positions, num_bins + 1, dtype=int)
    # Treat bins with zero supporting samples as zero-entropy rather than missing.
    binned = np.zeros(num_bins, dtype=np.float64)

    for idx, (start, end) in enumerate(zip(edges[:-1], edges[1:])):
        if end <= start:
            end = min(total_positions, start + 1)
        entropy_slice = entropy_row[start:end]
        count_slice = count_row[start:end]
        valid_mask = np.isfinite(entropy_slice) & (count_slice > 0)

        if not np.any(valid_mask):
            continue

        entropy_valid = entropy_slice[valid_mask]
        count_valid = count_slice[valid_mask]
        binned[idx] = np.average(entropy_valid, weights=count_valid)

    return binned


def format_k_tick(value: float) -> str:
    if value <= 0:
        return "0K"
    rounded_value = int(round(value))
    if rounded_value % 1000 == 0:
        return f"{rounded_value // 1000}K"
    return f"{value / 1000:.1f}K"


def build_colormap():
    return LinearSegmentedColormap.from_list(
        "entropy_heat",
        [
            "#e8eef6",
            "#bfd3ea",
            "#7fa8d5",
            "#3f87d8",
            "#f3a11f",
            "#f57f2a",
            "#e74c45",
        ],
    )


def save_figure(fig, output_path: Path):
    output_path.parent.mkdir(parents=True, exist_ok=True)
    fig.savefig(output_path, bbox_inches="tight", facecolor=fig.get_facecolor())

    pdf_path = output_path.with_suffix(".pdf")
    if pdf_path != output_path:
        fig.savefig(pdf_path, bbox_inches="tight", facecolor=fig.get_facecolor())

    return pdf_path


def resolve_output_path(output: Path | None, input_root: Path, dataset: str, layout_mode: str, entropy_column: str) -> Path:
    if output is not None:
        return output

    if layout_mode == "flat" and entropy_column == "avg_teacher_entropy":
        return input_root / "teacher_entropy_heatmap.png"

    return input_root / f"{dataset}_response_entropy_heatmap.png"


def resolve_title(user_title: str | None, dataset: str, layout_mode: str, entropy_column: str) -> str:
    if user_title:
        return user_title
    if layout_mode == "flat" and entropy_column == "avg_teacher_entropy":
        return "Teacher Entropy Heatmap (Position x Training Step)"
    return f"{dataset} Response Entropy Heatmap (Position x Training Step)"


def resolve_subtitle(user_subtitle: str | None, layout_mode: str) -> str:
    if user_subtitle:
        return user_subtitle
    return ""


def plot_heatmap(
    heatmap: np.ndarray,
    step_labels: list[str],
    max_position: int,
    output_path: Path,
    title: str,
    subtitle: str,
):
    cmap = build_colormap().copy()
    cmap.set_bad("#ffffff")

    finite_values = heatmap[np.isfinite(heatmap)]
    if finite_values.size == 0:
        raise ValueError("Heatmap contains no finite values.")

    vmin = float(np.nanpercentile(finite_values, 5))
    vmax = float(np.nanpercentile(finite_values, 99))
    if not math.isfinite(vmin) or not math.isfinite(vmax) or vmin >= vmax:
        vmin = float(np.nanmin(finite_values))
        vmax = float(np.nanmax(finite_values))

    plt.rcParams.update(
        {
            "font.size": 12,
            "axes.titlesize": 18,
            "axes.labelsize": 16,
            "xtick.labelsize": 13,
            "ytick.labelsize": 14,
            "font.family": "serif",
            "font.serif": ["STIXGeneral", "Times New Roman", "DejaVu Serif"],
            "mathtext.fontset": "stix",
        }
    )

    fig, ax = plt.subplots(figsize=(14.5, 5.9), dpi=180)
    fig.patch.set_facecolor("#ffffff")
    ax.set_facecolor("#ffffff")
    fig.subplots_adjust(left=0.16, right=0.98, top=0.87, bottom=0.17)

    image = ax.imshow(
        heatmap,
        aspect="equal",
        interpolation="nearest",
        origin="upper",
        cmap=cmap,
        vmin=vmin,
        vmax=vmax,
    )

    num_rows, num_cols = heatmap.shape
    ax.set_xticks(np.arange(-0.5, num_cols, 1), minor=True)
    ax.set_yticks(np.arange(-0.5, num_rows, 1), minor=True)
    ax.grid(which="minor", color="#4a5560", linestyle="-", linewidth=1.1)
    ax.tick_params(which="minor", bottom=False, left=False)

    tick_values = [0, 3000, 6000, 9000, 12000, 15000]
    tick_positions = [
        (value / max_position) * (num_cols - 1) if max_position > 0 else 0.0
        for value in tick_values
    ]
    tick_labels = [format_k_tick(value) for value in tick_values]
    ax.set_xticks(tick_positions)
    ax.set_xticklabels(tick_labels, color="#374151")

    ax.set_yticks(np.arange(num_rows))
    ax.set_yticklabels(step_labels, color="#374151")

    for spine in ax.spines.values():
        spine.set_visible(False)

    ax.set_xlabel("Output Position", color="#374151", labelpad=8)
    ax.xaxis.set_label_coords(0.5, -0.105)
    ax.tick_params(axis="both", colors="#374151", length=0, pad=6)

    ax.set_title(title, color="#111827", fontsize=20, fontweight="bold", pad=12, loc="center")
    if subtitle:
        ax.text(
            0.5,
            1.03,
            subtitle,
            transform=ax.transAxes,
            color="#4b5563",
            fontsize=13,
            ha="center",
            va="bottom",
        )

    ax_box = ax.get_position()
    cbar_center_x = (ax_box.x0 + ax_box.x1) / 2
    cbar_width = 0.24
    cbar_left = cbar_center_x - cbar_width / 2
    label_gap = 0.03

    cax = fig.add_axes([cbar_left, 0.115, cbar_width, 0.022])
    cbar = fig.colorbar(image, cax=cax, orientation="horizontal")
    cbar.outline.set_visible(False)
    cbar.ax.tick_params(colors="#374151", length=0, labelsize=12)
    cbar.set_ticks([])
    fig.text(cbar_left - label_gap, 0.136, "Low Entropy", color="#374151", fontsize=14, ha="right", va="center")
    fig.text(cbar_left + cbar_width + label_gap, 0.136, "High Entropy", color="#374151", fontsize=14, ha="left", va="center")

    pdf_path = save_figure(fig, output_path)
    plt.close(fig)
    return pdf_path


def main():
    args = parse_args()

    csv_paths, layout_mode = discover_csvs(args.input_root, args.dataset)
    csv_paths = filter_csvs_by_step(csv_paths, args.min_step, args.max_step)
    steps = [extract_step(path) for path in csv_paths]
    estimated_steps = parse_step_set(args.estimated_steps)
    step_labels = [
        f"Step {step} (est.)" if step in estimated_steps else f"Step {step}"
        for step in steps
    ]

    entropy_rows = []
    count_rows = []
    max_position = 0
    entropy_column = None

    for csv_path in csv_paths:
        entropy_row, count_row, current_entropy_column = load_step_csv(csv_path)
        if entropy_column is None:
            entropy_column = current_entropy_column
        elif entropy_column != current_entropy_column:
            raise ValueError(
                f"Mixed entropy columns detected: {entropy_column} and {current_entropy_column}. "
                "Please keep all step CSVs on the same schema."
            )
        entropy_rows.append(entropy_row)
        count_rows.append(count_row)
        max_position = max(max_position, len(entropy_row))

    entropy_rows = [pad_to_length(row, max_position, np.nan) for row in entropy_rows]
    count_rows = [pad_to_length(row, max_position, 0.0) for row in count_rows]

    heatmap = np.vstack(
        [
            weighted_bin_row(entropy_row, count_row, args.num_bins)
            for entropy_row, count_row in zip(entropy_rows, count_rows)
        ]
    )

    output_path = resolve_output_path(args.output, args.input_root, args.dataset, layout_mode, entropy_column)
    title = resolve_title(args.title, args.dataset, layout_mode, entropy_column)
    subtitle = resolve_subtitle(args.subtitle, layout_mode)
    pdf_path = plot_heatmap(heatmap, step_labels, max_position, output_path, title, subtitle)

    print(f"Discovery mode: {layout_mode}")
    print(f"Discovered steps: {steps}")
    print(f"Entropy column: {entropy_column}")
    print(f"Max position: {max_position}")
    print(f"Saved heatmap to: {output_path}")
    print(f"Saved heatmap to: {pdf_path}")


if __name__ == "__main__":
    main()

Turingzero0 avatar Jun 24 '26 19:06 Turingzero0