Skip to content

build_cross_task_encoder_summary

Build per-trainer encoder summaries on the shared cross-task test pool.

Each binary GRADIEND encodes every test transition in the merged pool (e.g. he->she, she->he, jewish->christian, ...) using that trainer's model. Rows with label == 0 are kept: they are cross-domain probes where the snippet's factual class is outside the trainer's pair.

When cache_only=True, unified encoder CSVs are loaded from disk only: no trainer datasets are materialized and no models are loaded for encoding. Missing or stale caches yield empty encoder_df entries with a warning. Set allow_incomplete_cache=True to intentionally use directed but incomplete cache rows in cache-only mode; this is useful for diagnostic partial plots and should not be used for final paper figures.

When force_recompute=True, existing unified encoder CSVs are ignored, fresh probe rows are encoded, and the unified cache is overwritten when artifact caching is enabled.

When seed_selection is omitted, trainers with analyze_seed_stability=True automatically use all convergent seed checkpoints and aggregate encoder responses (same rule as suite plots).

Parameters:

Name Type Description Default
trainers Dict[str, object]

Mapping from trainer id to trainer object.

required
feature_classes Optional[Sequence[str]]

Deprecated compatibility argument. The shared eval pool is inferred from trainers unless eval_rows or eval_by_class is supplied.

None
eval_rows Optional[DataFrame]

Optional prebuilt unified rows for the shared pool.

None
eval_by_class Optional[Dict[str, DataFrame]]

Optional prebuilt unified rows grouped by feature class.

None
Source code in gradiend/comparison/cross_encoding.py
def build_cross_task_encoder_summary(
    trainers: Dict[str, object],
    feature_classes: Optional[Sequence[str]] = None,
    *,
    eval_rows: Optional[pd.DataFrame] = None,
    eval_by_class: Optional[Dict[str, pd.DataFrame]] = None,
    split: str = "test",
    max_size: Optional[int] = None,
    use_cache: Optional[bool] = None,
    cache_only: bool = False,
    force_recompute: bool = False,
    seed_selection: Optional[str] = None,
    seed_aggregate: str = "mean",
    dispersion: Optional[str] = None,
    allow_incomplete_cache: bool = False,
) -> Dict[str, Any]:
    """Build per-trainer encoder summaries on the shared cross-task test pool.

    Each binary GRADIEND encodes **every** test transition in the merged pool
    (e.g. he->she, she->he, jewish->christian, ...) using that trainer's model.
    Rows with ``label == 0`` are kept: they are cross-domain probes where the
    snippet's factual class is outside the trainer's pair.

    When ``cache_only=True``, unified encoder CSVs are loaded from disk only:
    no trainer datasets are materialized and no models are loaded for encoding.
    Missing or stale caches yield empty ``encoder_df`` entries with a warning.
    Set ``allow_incomplete_cache=True`` to intentionally use directed but
    incomplete cache rows in cache-only mode; this is useful for diagnostic
    partial plots and should not be used for final paper figures.

    When ``force_recompute=True``, existing unified encoder CSVs are ignored,
    fresh probe rows are encoded, and the unified cache is overwritten when
    artifact caching is enabled.

    When ``seed_selection`` is omitted, trainers with
    ``analyze_seed_stability=True`` automatically use all convergent seed
    checkpoints and aggregate encoder responses (same rule as suite plots).

    Args:
        trainers: Mapping from trainer id to trainer object.
        feature_classes: Deprecated compatibility argument. The shared eval pool
            is inferred from ``trainers`` unless ``eval_rows`` or
            ``eval_by_class`` is supplied.
        eval_rows: Optional prebuilt unified rows for the shared pool.
        eval_by_class: Optional prebuilt unified rows grouped by feature class.
    """
    meta = comparison_seed_metadata(
        trainers,
        seed_selection=seed_selection,
        seed_aggregate=seed_aggregate,
        dispersion=dispersion,
    )
    resolved_selection = meta["seed_selection"]
    resolved_dispersion = meta["dispersion"]
    seed_aggregate = meta["seed_aggregate"]
    multi_seed = meta["multi_seed"]
    _validate_aggregate_dispersion_combo(seed_aggregate, resolved_dispersion)

    if eval_rows is None and not cache_only:
        if eval_by_class is not None:
            eval_rows = pd.concat(
                [df for df in eval_by_class.values() if isinstance(df, pd.DataFrame) and not df.empty],
                ignore_index=True,
            )
            eval_rows = eval_rows.drop_duplicates(
                subset=[c for c in eval_rows.columns if c in REQUIRED_UNIFIED],
                keep="first",
            ).reset_index(drop=True)
        else:
            eval_rows = collect_unified_test_rows(trainers, split=split)

    if cache_only and (eval_rows is None or eval_rows.empty):
        df = pd.DataFrame()
        expected_transitions: set[str] = set()
        expected_probe_keys: set[Tuple[str, str, str]] = set()
        use_cache_effective = True
    else:
        if eval_rows is None or eval_rows.empty:
            empty = {str(trainer_id): {"encoder_df": pd.DataFrame()} for trainer_id in trainers}
            if multi_seed:
                for payload in empty.values():
                    payload["encoder_dfs"] = []
                    payload["multi_seed"] = True
            return empty

        df = _sample_cross_task_eval_rows(eval_rows, max_size)
        expected_transitions = set()
        if UNIFIED_TRANSITION in df.columns:
            expected_transitions = {
                normalize_transition_id(value) or str(value)
                for value in df[UNIFIED_TRANSITION].astype(str).unique().tolist()
            }
        expected_probe_keys = {
            _probe_key_from_unified_row(row)
            for _, row in df.iterrows()
        }
        use_cache_effective = _artifact_use_cache_from_trainers(trainers, use_cache)

    summary: Dict[str, Any] = {}
    for trainer_id, trainer in trainers.items():
        trainer_key = str(trainer_id)
        base = unwrap_trainer(trainer)
        seed_entries = analysis_seed_entries(trainer, seed_selection=resolved_selection)
        if resolved_selection == "best" or len(seed_entries) <= 1:
            encoder_df = _build_cross_task_encoder_df_for_seed(
                base,
                trainer_id=trainer_key,
                df=df,
                split=split,
                max_size=max_size,
                use_cache_effective=use_cache_effective,
                expected_transitions=expected_transitions,
                expected_probe_keys=expected_probe_keys,
                allow_disk_cache=True,
                cache_only=cache_only,
                force_recompute=force_recompute,
                allow_incomplete_cache=allow_incomplete_cache,
            )
            summary[trainer_key] = {
                "encoder_df": encoder_df,
                **meta,
                "multi_seed": False,
            }
            continue

        best_seed_path = base.get_best_seed_run_path() if hasattr(base, "get_best_seed_run_path") else None
        encoder_dfs: List[pd.DataFrame] = []
        for seed_val, seed_path in seed_entries:
            allow_disk_cache = (
                best_seed_path is None
                or os.path.normcase(seed_path) == os.path.normcase(str(best_seed_path))
            )
            encoder_df = _build_cross_task_encoder_df_for_seed(
                base,
                trainer_id=trainer_key,
                df=df,
                split=split,
                max_size=max_size,
                use_cache_effective=use_cache_effective and allow_disk_cache,
                expected_transitions=expected_transitions,
                expected_probe_keys=expected_probe_keys,
                load_directory=seed_path,
                allow_disk_cache=allow_disk_cache,
                cache_only=cache_only,
                force_recompute=force_recompute,
                allow_incomplete_cache=allow_incomplete_cache,
            )
            if not encoder_df.empty:
                encoder_dfs.append(encoder_df)
            logger.info(
                "Cross-task encoder summary for %s seed %s (%d/%d)",
                trainer_key,
                seed_val,
                len(encoder_dfs),
                len(seed_entries),
            )

        aggregated_df = aggregate_encoder_dataframes(encoder_dfs)
        summary[trainer_key] = {
            "encoder_df": aggregated_df,
            "encoder_dfs": encoder_dfs,
            **meta,
            "multi_seed": True,
            "n_seeds": len(encoder_dfs),
        }
    if not cache_only:
        root_dir = _root_experiment_dir(trainers)
        if root_dir and expected_transitions:
            write_cross_task_transition_order(root_dir, sorted(expected_transitions))
    return summary