peal.adaptors.counterfactual_knowledge_distillation.CFKD¶
- class peal.adaptors.counterfactual_knowledge_distillation.CFKD[source]¶
Bases:
AdaptorThis class implements the counterfactual knowledge distillation approach.
The constructor wires up everything one run needs (student, dataloaders, generator, explainer, teacher, sparse dictionary);
run()executes the finetune iterations and returns the corrected student. See the module docstring for the algorithm and the per-iteration artifacts.- Parameters:
student (
torch.nn.Module, optional) – The classifier to repair. IfNoneit is built fromadaptor_config.studentwithget_predictor.datasource (
listortuple, optional) – Datasets/dataloaders handed tocreate_dataloaders_from_datasource;Nonemeans the data is built fromadaptor_config.data.generator (
InvertibleGenerator,Pathorstr, optional) – Generator instance or config path; falls back toadaptor_config.generator.base_dir (
strorPath, optional) – Run directory; falls back toadaptor_config.base_dir.teacher (
strorTeacherInterface, optional) – Teacher spec (e.g."human@8000","SegmentationMask", a dict{type: llm}) or instance; falls back toadaptor_config.teacher.adaptor_config (
dict,str,PathorCFKDConfig) – The run configuration (yaml path, dict or object).overwrite (
bool, optional) – Whether cached artifacts inbase_dirare discarded; falls back toadaptor_config.overwrite. The stored config always getsoverwrite=Falseso a resumed run reuses its cache.
- Variables:
original_student (
torch.nn.Module) – The uncorrected student, kept for the progress visualisation.student (
torch.nn.Module) – The student being finetuned (a deep copy of the input).test_dataloader (train_dataloader, val_dataloader,) – The original data;
val_batch_sizeis forced to the CFKDbatch_sizebecause validation batches go straight into the explainer.dataloader_mixer (
DataloaderMixer) – Original data plus every counterfactual dataset added so far.datastack (
DataStack) – Per-class sample buffer the batch builder pops factuals from.tracked_keys (
listofstr) – Keys of the explainer output that are collected and cached (extended withcluster_list,z_difference_list/collage_path_listattracking_level >= 4,hint_listandidx_listas needed).validation_data_config (data_config,) – Copies of the config used to load the serialised counterfactual datasets for training and validation respectively.
Methods
Load a serialised counterfactual dataset and mix it with the old data.
Explainer metrics from the teacher verdicts of one validation pass.
Unbiasedness score of the explainer from the distilled feedback accuracy.
Serialise judged counterfactuals as a dataset for finetuning.
The latest per-group test accuracies, computing them once if needed.
Finetune the student on the mixed data of one iteration.
Generate training counterfactuals until
min_train_samplesare found.Assemble one batch of factuals with (source, target) class pairs.
Prepare
base_dirand compute or reload the iteration-0 state.Training counterfactuals of an iteration, generated or loaded from cache.
Teacher verdicts for a set of counterfactuals, cached per iteration.
Validation counterfactuals and pre-feedback statistics of an iteration.
Complete the validation statistics with teacher feedback.
Run the counterfactual knowledge distillation
Render the before/after comparison figure for a binary task.
- __init__(student=None, datasource=None, generator=None, base_dir=None, teacher=None, adaptor_config='<PEAL_BASE>/configs/adaptors/symbolic_cfkd.yaml', overwrite=None)[source]¶
Build all components of a CFKD run; see the class docstring for the parameters.
Besides constructing the objects this also mutates
adaptor_config:test_datadefaults todata,in_memory/tracking_level/transition_restrictions/clustering_strategyare pushed into the explainer config,training.val_batch_sizeis set tobatch_sizeandtraining.steps_per_epochto one pass over the training set. A collage-based teacher (human, web, llm) requirestracking_level >= 4and fails an assertion otherwise.- Parameters:
student (torch.nn.Module)
generator (InvertibleGenerator | Path | str)
teacher (str | TeacherInterface)
adaptor_config (dict | str | Path | AdaptorConfig)
overwrite (bool)
- initialize_run()[source]¶
Prepare
base_dirand compute or reload the iteration-0 state.On a fresh run (
overwriteor nologsdir yet) the existingbase_diris moved to<base_dir>_old_<timestamp>, the initial validation/test (group) accuracies, sample batches and a generator sample (with FID) are written to TensorBoard underbase_dir/logs,config.yamlandplatform.txtare written and the validation counterfactuals of iteration 0 are generated. On a resumed run the cached validation values are loaded instead, every counterfactual dataset up tocurrent_iterationis re-added to the dataloader mixer and the lastmodel.cplbecomes the student. Optionally a decision-boundary plot (2-D latent datasets,tracking_level >= 4) and the progress figure (binary tasks,tracking_level >= 6) are rendered.- Returns:
(validation_stats, validation_tracked_values, writer): the statistics dict of the last completed validation pass, the tracked validation counterfactuals and theSummaryWriter.- Return type:
- get_batch(error_matrix=None, cm_idx_in=0)[source]¶
Assemble one batch of factuals with (source, target) class pairs.
Pairs are walked through the flattened
output_size x output_sizeconfusion-matrix index, skipping the diagonal, or sampled fromerror_matrixwhenuse_confusion_matrixis set. Each factual is popped from thedatastackof its source class; in"1sided"mode it is kept only when the student predicts it correctly. Hints and dataset indices are split off the label when enabled.- Parameters:
error_matrix (
torch.Tensor, optional) – Flattened error distribution over class pairs from the validation stats; only used withuse_confusion_matrix.cm_idx_in (
int) – Starting offset (in rows) of the confusion-matrix walk, so that alternate batches start from different pairs.
- Returns:
x_list(stacked tensor[B, ...]),y_list,y_target_list(tensor[B]),y_source_list,y_target_start_confidence_list(softmax of the tempered logits at the target class),hint_list(zeros unless aSegmentationMaskTeacheris used) andidx_list(zeros unless the explainer isPerfectFalseCounterfactualConfig).- Return type:
- generate_x_counterfactual_list(error_matrix, confidence_score_stats, finetune_iteration, tracked_keys)[source]¶
Generate training counterfactuals until
min_train_samplesare found.Repeatedly builds batches with
get_batch(), runsexplainer.explain_batchon them and accumulates the requested keys. Collages go tobase_dir/<iteration>/collages(an existing directory is moved aside with an_old_<timestamp>suffix); the explainer’s state directory isbase_dir/<iteration - 1>.- Parameters:
error_matrix (
torch.Tensor) – Passed toget_batch().confidence_score_stats (
object) – Currently unused.finetune_iteration (
int) – Iteration whose directory receives the collages.tracked_keys (
listofstr) – Keys of the explainer output to collect.
- Returns:
{key: list}for every key intracked_keys, with at leastadaptor_config.min_train_samplesentries each (batches are not truncated, so usually a few more).- Return type:
- retrieve_counterfactual_list(validation_stats, finetune_iteration)[source]¶
Training counterfactuals of an iteration, generated or loaded from cache.
Generates them with
generate_x_counterfactual_list()and savesbase_dir/<iteration>/tracked_values.npz(tracking_level >= 3), or loads that file (expanding old per-factual layouts withflatten_explanations). Thencollage_path_listis rebuilt from the.pngfiles in the collages directory and, if the explainer clusters,cluster_explanationsadds theclusters<k>entries.
- retrieve_feedback(tracked_values, finetune_iteration, mode)[source]¶
Teacher verdicts for a set of counterfactuals, cached per iteration.
As a side effect the distilled predictor used by the explainer metrics is prepared: with
calculate_explainer_statsthe student is distilled (distill_predictorwith a leaky-softplus activation) intobase_dir/<current_iteration>/distilled_predictoror reloaded from there; otherwise the student itself is used. The verdicts are written tobase_dir/<iteration>/<mode>_feedback.txtand read back from it on later runs.- Parameters:
- Returns:
One verdict per counterfactual (
"true","false","ood"or a teacher-specific marker string).- Return type:
- ensure_group_accuracies()[source]¶
The latest per-group test accuracies, computing them once if needed.
- calculate_unbiasedness(feedback_accuracy_distilled)[source]¶
Unbiasedness score of the explainer from the distilled feedback accuracy.
r_dominant = 1 - mean(two lowest group accuracies)estimates how often the student uses the shortcut;r_actual = 1 - feedback_accuracy_distilledhow often the explainer reveals it. The score isexp(-|log(r_actual / r_dominant)|), i.e. 1 when both rates agree.
- calculate_feedback_stats(tracked_values, feedback, finetune_iteration)[source]¶
Explainer metrics from the teacher verdicts of one validation pass.
Always computes
flip_rate(target confidence >= 0.51, relative tomax_validation_samplesat iteration 0),ood_rate,feedback_accuracy(fraction of “true” among true+false verdicts on correctly classified factuals) andcounterfactuals_per_second. With several attempts per factual only the highest-confidence attempt counts; the attempt layout (interleaved vs sequential) is inferred fromy_list.With
calculate_explainer_statsat iteration 0 the distilled predictor is additionally run on every counterfactual and cluster member, cluster collages are written tobase_dir/<iteration>/latent_cluster_collages<k>/and the following are added:flip_rate_distilled(NAFR: flips shared by student and distilled copy),non_adversarial_rate,feedback_accuracy_distilled,counterfactual_quality(datasettrack_generator_performanceon the non-adversarial flips, with quality collages inlatent_quality_collages/),unbiasedness(when group accuracies exist) and the latent sparsity/diversity stats ofexplainer.calculate_latent_difference_stats.- Parameters:
- Returns:
Metric name to float.
- Return type:
- create_dataset(x_counterfactual_list, feedback, y_source_list, y_target_list, finetune_iteration, hint_list=None, mode='', **kwargs)[source]¶
Serialise judged counterfactuals as a dataset for finetuning.
“false” counterfactuals are stored with their source class as label (the change did not alter the class, so the student must not flip); “true” ones with the target class when
use_true_counterfactualsis set. Sample names encode verdict, source, target and index. The dataset is written withtrain_dataloader.dataset.serialize_datasettobase_dir/<iteration>/<mode>_datasetand skipped if that directory already exists.- Parameters:
x_counterfactual_list (
listoftorch.Tensor) – Counterfactual inputs.feedback (
listofstr) – One verdict per counterfactual; must match in length.y_source_list (
list) – Source and target class per counterfactual.y_target_list (
list) – Source and target class per counterfactual.finetune_iteration (
int) – Iteration directory to write into.hint_list (
listoftorch.Tensor, optional) – Segmentation hints stored alongside the samples.mode (
str) –"train"or"validation".**kwargs – Other tracked values, ignored.
- Returns:
Path of the dataset directory.
- Return type:
- Raises:
Exception – If
x_counterfactual_listandfeedbackdiffer in length.
- add_dataset_to_dataloader_mixer(dataloader_old, dataset_path, mixing_ratio, writer, finetune_iteration)[source]¶
Load a serialised counterfactual dataset and mix it with the old data.
- Parameters:
dataloader_old (
DataloaderMixer) – The data used so far.dataset_path (
str) – Directory written bycreate_dataset().mixing_ratio (
float) – Weight of the new counterfactual data; the old mixer is appended with weight1 - mixing_ratio.writer (
SummaryWriter) – Sample images of the new data are logged astrain_<iteration>.finetune_iteration (
int) – Used for the log tag.
- Returns:
New mixer with
return_src_internal=Trueand hints enabled when the run uses them.- Return type:
DataloaderMixer
- finetune_student(finetune_iteration, dataset_path, writer)[source]¶
Finetune the student on the mixed data of one iteration.
Loads the validation counterfactual dataset of the iteration (written by
retrieve_validation_stats()) and appends it to the joint validation loaders, addsdataset_pathto the dataloader mixer, rebuilds the datastack and trains withModelTrainerintobase_dir/<iteration>/finetuned_model(an existing directory is moved aside).continuous_learningselects"finetune","retrain"(fresh resnet18) or"deep_feature_reweighting"(last layer only). Hints and dataset indices are disabled during training. Afterwardsmodel.cplis loaded as the new student and handed to the explainer. If the validation split is empty or training stops early,error_iteration_<n>.txtis written and the method returns without changing the student.- Parameters:
finetune_iteration (
int) – Current iteration.dataset_path (
str) – Training counterfactual dataset fromcreate_dataset().writer (
SummaryWriter) – Receives sample images of the new loaders.
- visualize_progress(paths)[source]¶
Render the before/after comparison figure for a binary task.
Uses
create_comparisonto show test samples with counterfactuals of the uncorrected and of the CFKD-corrected student side by side, with criteria for class, confounder (if the dataset exposes aConfounderattribute) and both predictions. Ranged explainer parameters (two-element lists) are replaced by their midpoint. Two images are saved per path:<path>and<path>_success.png(the latter filtered by a checkbox pattern of expected predictions).
- retrieve_validation_prestats(finetune_iteration)[source]¶
Validation counterfactuals and pre-feedback statistics of an iteration.
Runs
calculate_validation_statisticsvalidation_runstimes (interpolating ranged explainer parameters between runs) on the joint validation loaders and averages the statistics (error matrix, confidence score stats, …). Results are cached asvalidation_tracked_values.npzandvalidation_prestats.npzinbase_dir/<iteration>/attracking_level >= 3and loaded from there otherwise, withcollage_path_listrebuilt fromvalidation_collages0. If the explainer clusters, the explanations are clustered and stored asvalidation_tracked_cluster_values.npz; 2-D latent datasets additionally getval_counterfactuals_global.png.
- retrieve_validation_stats(finetune_iteration, validation_tracked_values, validation_prestats)[source]¶
Complete the validation statistics with teacher feedback.
If
base_dir/<iteration>/validation_stats.npzexists andoverwriteis off it is loaded (back-fillingunbiasednessfor old files when possible). Otherwise the teacher judges the validation counterfactuals,calculate_feedback_stats()adds the explainer metrics tovalidation_prestats, the judged counterfactuals are serialised as<iteration + 1>/validation_datasetfor the next finetuning and the merged dict is saved.- Parameters:
finetune_iteration (
int) – Iteration the validation values belong to.validation_tracked_values (
dict) – Fromretrieve_validation_prestats().validation_prestats (
dict) – Fromretrieve_validation_prestats(); extended in place.
- Returns:
Statistics including the feedback metrics.
- Return type:
- run()[source]¶
Run the counterfactual knowledge distillation
Starting at
current_iteration + 1and up tofinetune_iterations, every iteration retrieves training counterfactuals and their feedback, finalises the previous iteration’s validation statistics (logged asvalidation_*scalars), builds the counterfactual dataset, finetunes the student, logsval_accuracy/test_accuracy(plus group accuracies andgain, the relative improvement of the mean group accuracy, when enabled), computes fresh validation prestats for the next iteration, savesmodel.cpland advancescurrent_iterationinconfig.yaml. The post-loop validation pass is skipped unlessPEAL_FULL_VALIDATION_TAIL=1.- Returns:
The finetuned student.
- Return type: