Ablation API¶
The matrix methods can be called on the class without PyTorch. The constructor,
seeding, training, and DistilBERT surgery require imvpy[deep-learning].
Evaluator¶
imvpy.ablation_imv.AblationIMV
¶
Train binary PyTorch variants and compare aligned predictions with IMV.
The training helper supports models that accept dictionary batches and return
loss and two-class logits. The static matrix methods are
framework-independent and compare prediction DataFrames from any binary
probabilistic model.
The class automatically detects and uses GPU if available, otherwise uses CPU.
Parameters:
-
random_seed(int, default:42) –Random seed for reproducibility
Notes
The constructor, seeding, training, and :meth:reduce_bert_layers need
PyTorch. The static methods :meth:calculate_imv_matrix and
:meth:average_imv_matrices score saved prediction frames without an
instance or the deep-learning extra.
Source code in src/imvpy/ablation_imv/evaluator.py
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 | |
Reproducibility¶
imvpy.ablation_imv.AblationIMV.set_seed
¶
Set random seed for reproducibility.
Parameters:
-
seed(int, default:None) –Random seed. If None, uses self.random_seed
Notes
Seeds Python, NumPy, PyTorch CPU, CUDA, and MPS generators. This does not guarantee bit-identical accelerator kernels across hardware or versions.
Source code in src/imvpy/ablation_imv/evaluator.py
DistilBERT surgery¶
imvpy.ablation_imv.AblationIMV.reduce_bert_layers
staticmethod
¶
Reduce the number of transformer layers in a DistilBERT model.
Performs layer ablation by removing transformer layers from the end of the network. This is a common ablation technique to measure the importance of model depth.
Parameters¶
model : transformers.DistilBertForSequenceClassification The DistilBERT model to modify (or similar architecture) num_layers_to_keep : int Number of layers to keep counting from the beginning. Must be >= 1 and <= original number of layers.
Returns¶
model Modified model with reduced layers (in-place modification)
Example
from transformers import DistilBertForSequenceClassification model = DistilBertForSequenceClassification.from_pretrained( ... "distilbert-base-uncased", num_labels=2 ... )
DistilBERT has 6 layers by default, reduce to 3¶
model = AblationIMV.reduce_bert_layers(model, num_layers_to_keep=3) print(len(model.distilbert.transformer.layer)) # Output: 3
Note
- Modifies model in-place but also returns it for convenience
- Works with DistilBERT; may need adaptation for BERT, RoBERTa, etc.
- Keep at least 1 layer for meaningful model function
- Earlier layers capture more basic features; later layers capture complex patterns
Source code in src/imvpy/ablation_imv/evaluator.py
Training and prediction¶
imvpy.ablation_imv.AblationIMV.train_and_evaluate
¶
train_and_evaluate(model, train_dataloader, test_dataloader, num_epochs=3, lr=2e-05, optimizer_class=None, scheduler_fn=None, max_grad_norm=None, seed=None, verbose=True)
Train and evaluate a model with automatic GPU/CPU detection.
Parameters:
-
model(Module) –Binary model accepting each batch as keyword arguments and returning an object with scalar
lossand two-columnlogitsattributes. -
train_dataloader(DataLoader) –Training data loader
-
test_dataloader(DataLoader) –Test data loader
-
num_epochs(int, default:3) –Number of training epochs
-
lr(float, default:2e-5) –Learning rate
-
optimizer_class(class, default:None) –Optimizer class (e.g., AdamW). If None, uses torch.optim.Adam
-
scheduler_fn(callable, default:None) –Function called as
scheduler_fn(optimizer=optimizer, num_training_steps=num_training_steps). Its result must implementstep(). -
max_grad_norm(float, default:None) –If provided, clip the total gradient norm to this positive finite value before each optimizer step. Non-finite gradients raise an error instead of producing invalid predictions.
-
seed(int, default:None) –Random seed for this run
-
verbose(bool, default:True) –Print training progress
Returns:
-
dict–Dictionary containing: - 'model': trained model - 'test_predictions': DataFrame with negative/positive probability, true label, and predicted label columns - 'test_accuracy': float - 'test_precision': float - 'test_recall': float
Source code in src/imvpy/ablation_imv/evaluator.py
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 | |
Directional matrix¶
imvpy.ablation_imv.AblationIMV.calculate_imv_matrix
staticmethod
¶
calculate_imv_matrix(predictions_dict, target_column='True Label', prob_column='Positive Probability')
Calculate pairwise IMV comparison matrix for multiple model variants.
Creates a matrix where element (i,j) represents the IMV of model i compared to model j (how much better model i is than model j). Useful for comparing multiple ablation variants simultaneously.
Parameters¶
predictions_dict : dict of {str: pd.DataFrame} Dictionary mapping model variant names to their prediction DataFrames. Each DataFrame must contain target_column and prob_column.
Example structure:
{
'6-layer': df_6layer,
'4-layer': df_4layer,
'2-layer': df_2layer
}
str, default='True Label'
Name of the column containing true binary labels
prob_column : str, default='Positive Probability' Name of the column containing predicted probabilities for positive class
Raises¶
ValueError If no variants are supplied, required columns are missing, or labels and row counts are not identical across prediction frames.
Returns¶
pd.DataFrame, shape (n_models, n_models) Pairwise IMV comparison matrix where: - Rows represent "enhanced" models - Columns represent "basic" models - Element (i,j) = IMV comparing model i to model j - Diagonal elements are 0 (model vs itself)
Interpretation
- IMV(i,j) > 0: Model i has more information than model j
- IMV(i,j) = 0: Models are equivalent
- IMV(i,j) < 0: Model j is better than model i
- The matrix is directional and generally not antisymmetric
Example
predictions = { ... 'Full': df_full, ... 'Ablated-Layer': df_ablated, ... 'Baseline': df_baseline ... } imv_matrix = AblationIMV.calculate_imv_matrix(predictions) print(imv_matrix.round(3))
Full Ablated-Layer Baseline¶
Full 0.000 0.049 0.183¶
Ablated-Layer -0.047 0.000 0.127¶
Baseline -0.154 -0.113 0.000¶
Note that (Full, Baseline) = 0.183 while (Baseline, Full) = -0.154: the two cells divide by different baseline weights, so they are not negatives of each other. Read down a column only after checking that the column's baseline is the one you meant.
Source code in src/imvpy/ablation_imv/evaluator.py
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 | |
Matrix averaging¶
imvpy.ablation_imv.AblationIMV.average_imv_matrices
staticmethod
¶
Average multiple IMV matrices across random seeds or folds.
Combines IMV matrices from multiple runs to get stable estimates and reduce variance from random initialization. Useful for getting reliable ablation study results.
Parameters¶
matrices_list : list of pd.DataFrame List of IMV matrices to average. All matrices must have the same shape, index, and columns (same model variant names).
Returns¶
pd.DataFrame Averaged IMV matrix with same structure as input matrices
Raises:
-
ValueError–If matrices_list is empty
Example
Run ablation study with multiple seeds¶
matrices = [] for seed in [42, 43, 44, 45, 46, 47, 48, 49, 50, 51]: ... # Train models with different seeds ... predictions = run_ablation_study(seed=seed) ... imv_mat = AblationIMV.calculate_imv_matrix(predictions) ... matrices.append(imv_mat)
Get stable averaged results¶
avg_matrix = AblationIMV.average_imv_matrices(matrices) print(avg_matrix)
Note
- Element-wise averaging (not matrix algebra)
- Preserves index and column labels from first matrix
- Recommended: Use at least ten complete seeds when fits are stochastic
- Standard deviation can be computed separately with np.std()