Repository navigation
[Feature] Add ReSA - #479
Open
Aarjav0210 wants to merge 14 commits into
Open
Aarjav0210 wants to merge 14 commits into
Aarjav0210 wants to merge 14 commits into
Conversation
Aarjav0210
force-pushed
the
feat/resa
branch
2 times, most recently
from
October 23, 2026 16:30
8a71a88 to
bb0ef34
Compare
Author
Test contractsWhat the ReSA tests check, one row per contract: what is tested, the action, and the effect the assert expects. Tolerances are the ones in the code. Paths are under
|
| # | Test | What is tested | Action | Expected effect |
|---|---|---|---|---|
| 1 | test_matches_official_loss_and_gradients (2 and 4 views) |
Parity with the official CIFAR loss | Same random features and projections through ReSALoss and through the official code reduced to one process; gradients on the student projections |
Losses equal within 1e-5; every gradient within 1e-6 |
| 2 | test_identity_assignment_reduces_to_infonce |
The InfoNCE special case | Pass assignment=torch.eye(n) |
Equals the mean of the two cross-view InfoNCELoss (τ = 0.4) terms within 1e-5 |
| 3 | test_assignment_is_a_float32_soft_label_matrix |
Soft-label properties | assignment(h_s, h_t) on 64 samples |
64 × 64, float32, no gradient, non-negative, rows sum to 1 |
| 4 | test_gradients_reach_only_student_projections |
Where gradients go | All inputs require grad; backward | Student projections get non-zero grads; backbone features and teacher projections get none |
| 5 | test_bf16_autocast_computes_in_float32 |
The autocast guard | bf16 inputs under bf16 autocast | Loss is float32 and matches the float32 official loss within 1e-5 |
| 6 | test_collapsed_batch_stays_finite |
Collapse edge case | All rows identical, student equals teacher; backward | Loss and grads finite |
| 7 | test_huge_features_stay_finite |
Extreme magnitudes | Features scaled by 1e4; backward | Loss and grads finite |
| 8 | test_raises_on_mismatched_embeddings |
Input validation | Teacher with 10 rows vs 64 student rows | ValueError "same shape" |
| 9 | test_raises_without_a_cross_view_pair |
Input validation | One student view and one teacher view | ValueError "at least one student view" |
| 10 | test_two_rank_loss_matches_full_batch |
Real two-process DDP | Two gloo processes, each with 8 of 16 rows | Each rank's assignment equals its rows of the full-batch one; the ranks' mean loss equals the single-process loss; each rank's grads ÷ 2 equal the full-batch grads for its rows |
unit/test_resa.py · TestReSAForward (the resa forward function, mocked wrappers, real loss)
| # | Test | What is tested | Action | Expected effect |
|---|---|---|---|---|
| 11 | test_training_returns_loss_embedding_and_assignment |
Training output dict | Two views of 8 images, stage train | Finite scalar loss; embedding 16 × 512 detached; assignment 8 × 8; labels of length 16; self.log called once |
| 12 | test_teacher_sees_only_the_first_two_views |
Multi-view routing | Four views | Student backbone called 4 times, teacher 2 times |
| 13 | test_eval_returns_teacher_embedding_without_loss |
Evaluation path | training=False, single-view batch |
No loss key; embedding 8 × 512; student never called |
| 14 | test_raises_with_a_single_view |
Input validation | One view | ValueError "at least 2 views" |
| 15 | test_raises_without_resa_loss |
Configuration validation | Module without resa_loss |
ValueError naming resa_loss |
unit/test_resa.py · TestReSAMethod (the ReSA class on Module batches)
| # | Test | What is tested | Action | Expected effect |
|---|---|---|---|---|
| 16 | test_fit_batch_trains_the_student |
The class's training step, as Module.training_step calls it |
ReSA("vit_tiny_patch16_224", projector_dims=(256, 256, 64)); {"views": [...]} with two 224-pixel views of 2 images, stage fit; backward |
Keys loss, embedding, resa_assignment, label; finite scalar loss; embedding 4 × 192; a student backbone parameter gets a non-zero gradient, no teacher parameter gets one |
| 17 | test_validate_batch_returns_teacher_embedding_without_loss |
Evaluation with a prebuilt encoder | ReSA(<24-d ViT>, projector_dims=(16, 8)).eval(); {"image", "label"} with 2 images, stage validate |
Keys embedding and label only; embedding equals the teacher backbone's output; nothing logged |
Shared unit tests ReSA joins
| # | Test | What is tested | Action | Expected effect |
|---|---|---|---|---|
| 18 | unit/test_method_boundary_contracts.py::test_projector_requires_an_output_dimension[resa] |
Projector validation | _build_resa_projector(4, []) |
ValueError "at least one" |
| 19 | unit/test_forward_functions.py::test_resa_forward_with_benchmark_transforms (new) |
The forward function on a real transformed batch | One PIL image through the file's SimCLR-style MultiViewTransform (two 224-pixel views with crop, colour jitter, grayscale, flip); mocked wrappers, real ReSALoss, stage train |
Result has embedding and resa_assignment; loss is finite |
| 20 | unit/test_module_and_forward_edges.py::test_ssl_evaluation_preserves_labels_and_does_not_require_loss[resa-False] |
Single-view evaluation through the forward function | Linear(3, 4) backbone in a TeacherStudentWrapper, training=False, one view dict, stage validate |
Embedding equals the backbone applied to the images; labels pass through unchanged; no loss key |
| 21 | same test, [resa-True] |
Multi-view evaluation through the forward function | Same, with a list of two view dicts | Embedding equals the backbone on both views concatenated; labels concatenated in order; no loss key |
Regression (through Manager)
| # | Test | What is tested | Action | Expected effect |
|---|---|---|---|---|
| 22 | regression/test_methods.py::test_method_trains_and_registers[resa] |
A full Manager run of the forward function | One epoch on a tiny conv backbone and projector in EMA wrappers, Adam | A completed run in the registry with a run directory and stored hyper-parameters |
| 23 | regression/test_methods.py::test_method_matches_reference[resa] |
Drift in loss, forward function or optimizer wiring | Same run, seed 42 | fit/loss_epoch equals 2.295149 within 1e-5 (reference captured with _capture_refs.py) |
| 24 | regression/test_resa_resume.py::test_resa_restart_matches_uninterrupted_training |
The ReSA class trains and resumes through Manager |
The class with a tiny conv encoder. Run A: 3 epochs straight. Run B: stop after epoch 1, checkpoint, fresh model with every parameter +10, resume to 3 epochs | Both reach 12 steps; full state dict matches run A, including teacher weights, BatchNorm statistics and EMA buffers; EMA coefficient below 1; teacher differs from student |
Row 1 is two test cases, so test_resa.py reports 18. Rows 18 and 20–23 are ReSA entries in tests the repo already runs for every method. All 24 pass locally.
Leon-Leyang
requested changes
Nov 24, 2026
Leon-Leyang
left a comment
Collaborator
There was a problem hiding this comment.
Hi @Aarjav0210, I've gone through the PR. Please check the issues below:
stable_pretraining/methods/resa.py:172:ReSA.forwardtakes(view1, view2)and repeats the steps ofresa(stable_pretraining/forward.py:381). It should take(batch, stage)and return a dict with"loss", calling the forward function instead of repeating it.stable_pretraining/__init__.py:ReSAisn't exported from the top-level package (_LAZY_ATTRS,__all__,stable_pretraining/__init__.pyi).- Please add the evaluation script behind the reported linear-probe and 5-NN numbers under
benchmarks/. - PR description: the batch size of the reported runs isn't stated.
Author
|
Thanks @Leon-Leyang, all four are addressed:
|
Codecov Report✅ All modified and coverable lines are covered by tests. @@ Coverage Diff @@
## main #479 +/- ##
=======================================
Coverage 98.17% 98.18%
=======================================
Files 163 165 +2
Lines 16406 16469 +63
=======================================
+ Hits 16107 16170 +63
Misses 299 299 🚀 New features to boost your workflow:
|
Leon-Leyang
approved these changes
Dec 3, 2026
Leon-Leyang
left a comment
Collaborator
There was a problem hiding this comment.
Hi @Aarjav0210, I've gone through the changes and it looks good to me.
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
Adds ReSA (Representation Self-Assignment) from Weng et al., Clustering Properties of Self-Supervised Learning, ICML 2025 (arXiv:2501.18452). ReSA is contrastive learning with soft targets: Sinkhorn-Knopp turns the student–teacher similarities of the encoder features into soft labels, and the projections learn to match them across views. With one-hot labels it reduces to InfoNCE.
losses.ReSALossand theforward.resaforward functionReSA(alsospt.ReSA), a method class that runsforward.resa, with the official CIFAR projector and an EMA teacherbenchmarks/cifar10/resa-resnet18.py(the official CIFAR recipe),benchmarks/cifar100/resa-resnet18.py, andbenchmarks/cifar10/resa-resnet18-eval.py(the paper's evaluation)README.md,METHODS.mdandRELEASES.rstResults
ResNet-18, 1000 epochs, batch size 256 on one GPU (L40S), scored with the paper's protocol (teacher features; linear probe / 5-NN, %).
The runs behind the table (CIFAR-10 with
--seed 0and--seed 1, CIFAR-100 with seed 0):python benchmarks/cifar10/resa-resnet18.py --seed 0 python benchmarks/cifar100/resa-resnet18.py python benchmarks/cifar10/resa-resnet18-eval.py --ckpt path/to/last.ckpt # add --dataset cifar100 for CIFAR-100Implementation notes
exp(S / 0.05)amplifies rounding error twentyfold.How it was validated
THIRD_PARTY_NOTICES.md): identical loss and gradients for 2 and 4 views, plus edge cases.Managertrain/stop/resume test of theReSAclass.benchmarks/cifar10/resa-resnet18-eval.py, which follows the official evaluation code, on the final checkpoint.Test details are in the "Test contracts" comment below.
Checklist