For now, I found a few compact models and implementation examples that might be relevant:
Short answers to the three questions
1. Compact encoders and frozen features versus fine-tuning. I would keep the project’s existing compact CNN or ViT as a reference and compare it with at least one released, pathology-pretrained small encoder. Three concrete ViT-S/16 candidates are Kaiko ViT-S, Lunit DINO ViT-S, and DistillPath-KS16-HOpt0. The first two offer different pathology-pretraining references; the third is a small student initialized from Kaiko and subsequently distilled from a larger pathology teacher. None is necessarily best for an unseen patient-level task. Frozen crop embeddings followed by a small patient-level MIL head are a particularly interpretable and inexpensive first comparison. End-to-end or partial fine-tuning can be a separate branch if the frozen representation appears limiting.
2. Variable crop counts and heterogeneous tissue. Start with mean pooling and attention-based MIL using identical cached embeddings and an explicit crop budget. The classic attention-based deep MIL paper provides a simple learnable set aggregator. Vary the number of crops per patient and repeat crop sampling with different seeds; this often tells you more than immediately adding a complex head. Max/top-k or class-aware selection are conditional alternatives when evidence is sparse. If a patient has several identifiable slides, compare flat crop-to-patient pooling with slide-first aggregation rather than assuming either hierarchy is universally better.
3. Controls that separate methodological gains. Hold encoder and crop IDs fixed when comparing aggregation methods; hold MIL head, splits, crop budget, and evaluation protocol fixed when comparing encoders. A released distilled checkpoint versus its released initialization is a practical comparison of weights as distributed, not a clean causal estimate of a distillation loss: the distilled student also had additional training data and compute. To study the distillation objective itself, compare the same student initialized the same way under suitably matched training conditions, with and without the teacher signal. Report patient-level macro-F1 and class recall beside crop counts and costs, rather than treating parameter count alone as a compute control.
The earlier reply already suggests frozen pathology features and one-factor-at-a-time comparisons. To complement it, I have included specific weights, implementation references, conditional choices, and a bounded T4 engineering check. None requires access to unpublished methods or private results.
In a short Colab Tesla T4 feature-extraction test, all three public ViT-S checkpoints loaded through timm and yielded 384-dimensional pooled crop embeddings. This checks compatibility and a limited cost reference, not patient macro-F1, clinical utility, or a distillation gain. The tested scope appears below.
A practical low-compute route
- Keep the existing patient/source split. Maintain an unambiguous mapping among patient, label, crop, tissue-source group, and slide ID if one exists. With patient labels, keep the patient as the prediction and evaluation unit even if feature files are stored by slide.
- Cache frozen embeddings for the existing compact model and one or two pathology-pretrained candidates. Use identical source crops and patient membership but each checkpoint’s prescribed preprocessing. Record revisions and transforms.
- Compare mean pooling with a small attention head on those same features. This avoids rerunning the encoder and tests aggregation against a simple permutation-invariant baseline.
- Change the crop budget, not everything at once. Test a few feasible per-patient caps, repeat subsampling, and report patient macro-F1, per-class recalls, and variability. If results are stable at a small cap, that itself helps the efficiency objective.
- Spend additional compute only where the results point. If encoder choice dominates, investigate fine-tuning or a better student. If crop sampling or aggregation dominates, focus there. If the objective or teacher signal is the claimed contribution, preserve the simple baselines and add matched training controls.
Checks worth making before interpreting any gains
- Compare predictions at the patient level. If multiple slides belong to one patient, a split that is disjoint only by slide does not guarantee patient independence. Your post already identifies patient/source separation; the important point is to preserve it through feature extraction, MIL training, and reporting.
- Define the crop policy. “32 crops” could mean exactly 32 sampled, at most 32, or all available up to 32. A patient with fewer than 32 images needs an explicit policy; duplicating crops is not equivalent to keeping the smaller bag.
- Keep crop identities stable across encoders. Compare the same underlying images with each checkpoint’s intended resize/normalization; forcing identical transforms is a separate ablation.
- State which feature tensor enters MIL. For these tested ViT-S weights,
model(x) with num_classes=0 gives [B, 384]; forward_features(x) gives [B, 197, 384]. Feeding tokens instead of one pooled vector per crop changes both the model and its compute. See the official timm feature-extraction guide.
- Separate training convenience from inference cost. A feature cache saves repeated encoder work during head training, but an unseen patient’s images still require preprocessing and encoding. Teacher computation for distillation is a third, separate cost.
The expanded sections provide details and references for the branches that turn out to matter.
Compact pathology encoders, feature extraction, and a small T4 check
Concrete weights and their roles
What the public-weight T4 test actually showed
I loaded the three weights on a Tesla T4 with timm 1.0.30, PyTorch 2.11.0+cu130, and torchvision 0.26.0+cu130. Each loaded model had 21,665,664 parameters in the tested configuration and accepted preprocessed RGB [B, 3, 224, 224] tensors. Its pooled output was [B, 384]. forward_features() returned [B, 197, 384], while forward_head(..., pre_logits=True) and the classifier-free model(x) yielded matching pooled features for the tested inputs. Identical inputs produced identical features in that run.
The table uses 4, 16, and 32 crop tensors, batches of up to eight, and the median of five runs in one T4 session. Inputs were variants and repeats of one public H&E example image, not independent patients or tissue crops.
| Crop tensors |
Kaiko |
Lunit |
DistillPath |
| 4 |
22.7 ms |
22.8 ms |
22.6 ms |
| 16 |
47.3 ms |
47.7 ms |
48.4 ms |
| 32 |
95.6 ms |
95.7 ms |
96.1 ms |
Timings include host-to-GPU transfer, encoding, and mean pooling of already transformed tensors. They exclude preprocessing, disk I/O, slide tiling, and patient data loading. An in-memory path including transforms, stacking, transfer, encoding, and pooling, but excluding disk/WSI I/O, took approximately 153, 155, and 163 ms for 32 crops. These are setup-specific measurements, not clinical/deployment latency estimates or reliable speed rankings.
The supported conclusion is that all three weights worked as frozen feature extractors and had similar inference cost at the same architecture and crop count in this run. DistillPath being distilled does not automatically make it faster than Kaiko, because both use a small ViT-S encoder at inference. The potential benefit to evaluate is better downstream representations at a similar student inference budget, not a promised faster forward pass. No patient labels, MIL head training, or distillation-objective ablation were included in this check.
One pooled vector per real crop
import timm
import torch
model = timm.create_model(
"hf-hub:1aurent/vit_small_patch16_224.kaiko_ai_towards_large_pathology_fms",
pretrained=True,
num_classes=0,
).eval().to(device)
# `device` and `images` (a preprocessed crop batch) are caller-provided.
# Prepare images with the checkpoint-specific eval transform.
with torch.inference_mode():
embeddings = model(images.to(device))
assert embeddings.ndim == 2 and embeddings.shape[-1] == 384
The result is [number_of_crops, 384] in this tested family. It is not one embedding per patient until a patient-level pooling/head step is applied. If debugging output shape, compare model.forward_features(images) with model.forward_head(..., pre_logits=True) instead of assuming every forward_features() output has already been pooled. The return contract should be checked again when changing to a CNN, another ViT, or a new timm release.
Preprocessing differences are measurable
The tested model configurations used 224-pixel inputs, bicubic interpolation, and mean/std (0.5, 0.5, 0.5). The resolved crop_pct was 0.9 for Kaiko and Lunit, and 0.875 for DistillPath. This is not evidence that one preprocessing recipe is better, but it is a concrete reminder that “same resolution” does not guarantee the same input tensors.
Frozen versus partial/full fine-tuning
A frozen feature baseline is a cost-saving experimental control, not a final verdict against fine-tuning. If the target classes differ substantially from the encoder’s pretraining domain, adapting the encoder may help. Useful branches are (a) frozen encoder and trained MIL head, (b) partially updated encoder or lightweight adapter with the same head and crop policy, and (c) full fine-tuning if the hardware/data justify it. Keep the validation protocol stable and separately report training cost and new-patient inference cost. Fine-tuning changes representation learning and optimization together, so it should not be described as a pure “MIL architecture” improvement.
Variable crop counts, heterogeneous tissue, and patient-level MIL
The minimum useful aggregation comparison
Let one patient have an unordered set of crop embeddings z_1, ..., z_n. Mean pooling uses their arithmetic average; it is cheap, insensitive to ordering, and naturally handles varying n when implemented correctly. An attention MIL head assigns normalized, learned weights to instances before pooling. Both are useful baselines because they avoid expensive full interactions among all crop pairs.
Their limitations differ. Mean pooling can dilute a small number of diagnostic crops among many uninformative ones; attention can learn unequal importance but introduces optimization, calibration, and overfitting considerations. High attention weights are not automatically a validated tissue-level explanation. A max/top-k baseline can be informative if a rare positive region may determine the patient label; however, it can also respond to artifacts or outliers. Which assumption fits the task is an empirical question, not something decided from the model name.
Treat the crop budget as part of the method
A reasonable low-cost check is to pick a small set of feasible per-patient crop caps, selected according to the actual distribution rather than a universal value. State whether a cap means sampling up to that many real crops or sampling exactly that number, and explain what happens for patients with fewer available crops. Some policies use all available crops for small bags; others sample with replacement or exclude insufficient bags. Those are different populations/input distributions and must not be silently interchanged.
A compact reporting layout would be:
| Crop policy |
Mean MIL |
Attention MIL |
How to interpret |
| Small fixed cap, several seeds |
Patient macro-F1 and variation |
Same |
Is either head robust when evidence is scarce? |
| Medium cap, matched crop IDs |
Same measures |
Same |
Does more tissue coverage help at an acceptable cost? |
| Larger feasible cap |
Same measures |
Same |
Are gains saturating while encoder cost rises? |
Repeated sampling, rare evidence, and tissue balance
If the task depends on a rare lesion, a very small uniform subbag may never include the relevant crop. That is a sampling failure, which a more elaborate head cannot necessarily repair. Conversely, if evidence is diffuse, mean pooling may be sufficient and more stable than selecting only the most extreme activations. If class-conditional top-k selection is investigated, selection rules should be learned only from training data and applied without consulting held-out labels.
Padding and masks
A batching implementation often pads shorter bags so that a minibatch has a common number of crop slots. The valid-instance mask must ensure that padded slots do not enter the mean, attention normalization, or prediction. A cheap sanity check: a bag with three real features should pool identically alone or padded within a batch. If it changes, the batch implementation needs fixing before comparison.
For mean pooling, divide by the number of valid crops, not the padded width. For attention, mask invalid logits before softmax, using the mask convention of the library actually installed. All-padding bags should be rejected or handled explicitly; they are not legitimate zero-tissue patients. A permutation check provides another useful invariant: reordering real instances should leave a permutation-invariant bag model’s prediction unchanged when all accompanying metadata is reordered consistently.
Patient versus slide hierarchy
There are two materially different data structures:
Case A: one patient label, multiple crops without meaningful slide IDs
patient -> {crop 1, crop 2, ..., crop n} -> MIL -> patient prediction
Case B: one patient label, several known slides, each with its own crops
slide A crops -> slide representation
slide B crops -> slide representation
slide representations -> patient model -> patient prediction
The arrows above describe computation rather than a claim that either architecture is required. In Case A, a flat patient bag is natural. In Case B, flat pooling remains a baseline, but slide-first aggregation can preserve slide-level context and prevent a slide with many crops from automatically dominating by sheer count. Its extra complexity is meaningful only when slide IDs exist and multiple slides actually contribute to patient labels. The literature on AGE-MIL (MICCAI 2026) is relevant to that branch; its specialized dual-stream design is not synonymous with a cheap two-stage mean/attention baseline.
Short decision map
Frozen features available?
No: compare a small number of encoders and cache features first.
Yes: compare simple MIL heads under identical crop IDs.
Crop count varies widely?
Yes: state cap/short-bag policy, test repeated subbag sampling.
No: keep a simple stable bag policy unless another reason appears.
Sparse decisive regions suspected?
Yes: mean versus attention, optionally max/top-k at the same budget.
No or unknown: mean and attention are enough to start.
Several slides per patient with known slide IDs?
Yes: flat patient pooling versus slide-first pooling.
No: do not require slide hierarchy.
Only inference budget is binding?
Profile the uncached image-to-patient path; head-only timing is insufficient.
Controlled experiments: which conclusion does each comparison support?
Distinguish the layers of the method
A compact ablation plan might look like this:
| Comparison |
Keep fixed |
Can support |
Cannot establish by itself |
| Same cached encoder, mean vs attention |
Crops, patients, features, train/val split |
Value of the changed pooling/head setup |
That attention will beat mean on every tissue/class |
| Kaiko vs Lunit frozen features, same head |
Crop IDs, head architecture, head training budget, splits |
Practical effect of using different released encoders |
Causal effect of one SSL algorithm alone |
| Kaiko release vs DistillPath release |
Evaluation protocol, head, crop budget |
Value of the two available checkpoints for this task |
Pure effect of distillation, independent of extra data/training |
| Fixed model, different crop caps |
Weights, head, source split, metric |
Accuracy-cost sensitivity to sampled evidence |
Better architecture independent of more evidence |
| Same student, with vs without teacher signal |
Initialization, data exposure, training steps and budget as closely as feasible |
More direct evidence about the teacher/distillation contribution |
Universal superiority across other teachers or cohorts |
| Frozen vs partially tuned encoder |
Splits, task, output evaluation budget |
Cost-benefit of adaptation in the tested setup |
A pure pretraining or aggregation effect |
The particularly important distillation distinction
The DistillPath model card describes a Kaiko ViT-S-initialized student trained using a large teacher on additional public TCGA slide material. It reports results on several benchmarks; those published author measurements can motivate its inclusion as a reference, but they are not a result for the poster’s held-out patients. If DistillPath outperforms released Kaiko in a frozen patient-bag experiment, the defensible statement is that this released student checkpoint gave more useful features under that evaluation. It does not follow that a particular knowledge-distillation loss, by itself, produced the entire difference.
To ask the narrower causal question, compare matched student training runs: same initialization, architecture, supervised/unsupervised data exposure, crop pipeline, number of optimization steps and, where practical, a similar compute allowance; vary the distillation signal. An additional student run on the same extra data without teacher signals helps separate teacher information from added training. If a teacher must be run online, report that cost. If teacher features were computed once, count feature creation separately from student optimization.
Preserve patient-level evaluation, then characterize uncertainty
The post already specifies separation of patients and tissue-source groups and chooses macro-F1 as its primary measure. I would retain that. The remaining reporting questions are the split unit, class/group counts, which groups appear in which partitions, whether crop/slide identifiers from one patient cross a partition, and whether the final patient prediction is calculated once per patient. These checks help preserve the intended experiment; they are not accusations of leakage.
Macro-F1 is sensitive to performance across classes, but a small number of patients in a class can create high uncertainty. Report per-class recall with support counts, and optionally precision/confusion patterns where meaningful. If repeated crop sampling makes predictions change, show that variation. If confidence intervals are calculated, the resampling unit should respect patient-level dependence; bootstrapping individual correlated crops as if they were independent patients will exaggerate certainty.
What to prioritize when a result is ambiguous
- If all heads perform similarly on frozen features, do not infer that MIL research is exhausted. It may indicate that the available labels are well captured by simple aggregation at those tested crop budgets, or that encoder representation is currently more limiting.
- If attention improves recall for a rare class but not overall macro-F1, examine whether the important evidence is sparse and whether the gain persists across sampling seeds. Do not convert the attention map directly into a medical explanation.
- If changing the encoder helps consistently under the same patient split, a feature-representation branch is reasonable. It is not proof that fine-tuning or knowledge distillation caused the gain unless those factors are controlled.
- If more crops help while architecture changes do little, sampling/coverage may have higher marginal value than a larger model. But the reported inference budget must include the additional images actually encoded.
- If a distilled student wins but extra-training controls are absent, describe it as a useful released checkpoint and leave the mechanism open.
Compute accounting: cached training versus a new patient's inference
Costs that should not be combined silently
Caching is an excellent way to accelerate comparisons among MIL heads and sampling policies. It does not mean an unseen patient’s encoder cost has vanished. The same distinction matters when a large teacher is used offline for student training: final deployment may require only the small student, while the research/training process consumed additional teacher compute. Those are both legitimate operating points, but the resource claim should specify which one it describes.
Use the measurement boundary that matches the claim
The short T4 check above used one resized image source and its deterministic variants, capped batches at eight crops, and measured prepared-tensor encoder work. The roughly 96 ms for 32 prepared crops is not a universal patient-inference latency, and the roughly 153–163 ms in-memory full-path observation still omits disk I/O, WSI tile extraction, and operational patient-data loading. Another GPU, precision, crop count, transform, data loader, or batching policy can change these numbers.
If measuring deployment, time the full path from available patient images to the patient-level output on the intended device. Report a representative distribution of real bag sizes rather than only an arbitrary 32-crop configuration. If useful, report both median and upper-tail latency and peak memory; the slowest large bags may determine practical throughput even when the median bag is easy. A small MIL head might be negligible next to preprocessing and the encoder, but measure it rather than assuming that for every architecture.
Code and paper references organized by the question they answer
For mean/attention MIL and patient-data organization: Attention-based Deep MIL is a primary description of the lightweight learnable pooling idea. CLAM provides pathology MIL code, feature extraction examples, and patient/slide/split conventions; inspect the exact split configuration, because the presence of a patient-aware option does not mean every example run uses it. TorchMIL provides MIL models and variable-length data handling, with library-specific mask/label contracts. STAMP is another reference for mapping slide features and metadata into a patient-level workflow, even if a public-crop experiment does not need its full WSI pipeline.
For compact representations and teacher-student work: The Kaiko project and Lunit SSL benchmark document the origins of two small pathology backbones. The DistillPath repository and model card provide a closer small-student distillation example; MuCoDi offers a different efficient-student/distillation reference. These are starting points for specific comparisons, not an instruction to reproduce all their training pipelines.
If multiple slides per patient matter: AGE-MIL (MICCAI 2026) examines patient-level multiple-WSI reasoning. Its design uses more specialized slide/patch context than a basic frozen-feature head and should be treated as a conditional research connection, not a mandatory next model. For a broader evaluation framework, PathForge may help organize pathology-feature and MIL benchmarks, but it can be much more machinery than a two-head experiment requires.
Reproducibility, conditional risks, and what remains unknown
Minimal experiment manifest
Even a small study benefits from recording the following, preferably in a machine-readable run file:
# Illustrative schema, not actual values from this research.
dataset:
unit_of_prediction: patient
patient_split_id: <split identifier>
tissue_source_group_rule: <definition if shareable>
crop_manifest_id: <stable file/hash or internal identifier>
slide_id_available: <true/false>
magnification_or_mpp: <value or unknown>
model:
encoder_repo: <HF repository or local model>
checkpoint_revision: <commit SHA>
timm_version: <version>
torch_version: <version>
torchvision_version: <version>
feature_boundary: <pooled output or explicitly defined alternative>
preprocessing: <resolved resize/crop/interpolation/normalization>
embedding_dim: <measured width>
bag:
crop_budget_rule: <cap or exact count, short-bag policy>
sampling_seed: <seed(s)>
aggregator: <mean/attention/other>
padding_mask_convention: <if relevant>
evaluation:
unit: patient
primary_metric: macro_F1
additional_metrics: <class recalls, counts, uncertainty>
compute:
device: <GPU/CPU>
precision: <dtype>
batch_or_chunk_size: <size>
timing_scope: <precisely timed stages>
Pretraining overlap and evaluation claims
Pathology checkpoints may have encountered public collections such as TCGA during pretraining or distillation. DistillPath explicitly documents additional TCGA-derived training. If the downstream evaluation includes overlapping patients or imagery, it is worth clarifying the level of overlap before claiming an entirely unseen cohort. General domain pretraining, unlabeled representation exposure, direct patient overlap, and supervised leakage are different cases; they should not be conflated. Nothing in the original post establishes an actual leak. An audit here is a conditional protection for the interpretation of results, not a criticism of the dataset design.
Also, matching 224-pixel inputs does not by itself match physical tissue scale (magnification or microns per pixel). The model cards specify non-commercial or other license conditions. Publicly downloadable weights are not necessarily unrestricted. Check the applicable license before redistribution or deployment. None of the presented smoke tests or patient-level experimental proposals constitutes clinical validation or a claim about safety in medical decision-making.
Stain, acquisition, scale, and source groups
H&E data can differ by site, scanner, tissue preparation, staining, compression, and physical magnification. An encoder may react to those properties independently of the clinical target. If source-group generalization matters and metadata support it, per-group patient counts and appropriately controlled group-wise evaluation can help interpret results. The phrase “tissue-source groups” is not detailed enough to infer a particular source of bias or mandate a stain-normalization algorithm.
Runtime compatibility is local to the actual stack
These specific released ViT-S weights use timm loading examples; they are not evidence of a Transformers v4/v5 compatibility problem. More directly useful here is recording timm, PyTorch, torchvision, preprocessing, dtype, and exact Hub revision. If a separate pipeline component later uses Transformers processors or PEFT adapters, that component may need its own compatibility tests, but those issues should not be projected onto these checkpoints without observation.
What is still unresolved
The post does not specify patient/class counts, crop-count distribution, physical image scale, slide IDs, precise source-group definition, or whether training or deployment cost is the main constraint. The proposed branches can be used without demanding those private facts from the author. The T4 test also lacks patient labels, realistic heterogeneous bags, and controlled head/student training, so it cannot choose a winning patient classifier.
If the near-term goal is a strong, small public reference, the frozen encoder comparison, mean-versus-attention head, and crop-budget sensitivity check are enough to establish a useful baseline. If a new distillation objective is central, preserve those comparisons and add student-training controls when affordable. If the problem really has several slides per patient, the slide-first branch becomes more important; if strict deployment latency dominates, measure the full uncached path on the target machine.