Skip to content

[Feature] Add ReSA - #479

Open
Aarjav0210 wants to merge 14 commits into
galilai-group:mainfrom
Aarjav0210:feat/resa
Open

Aarjav0210 wants to merge 14 commits into
galilai-group:mainfrom
Aarjav0210:feat/resa

Conversation

@Aarjav0210

@Aarjav0210 Aarjav0210 commented Oct 16, 2026 •

Copy link
Copy Markdown

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.ReSALoss and the forward.resa forward function
  • ReSA (also spt.ReSA), a method class that runs forward.resa, with the official CIFAR projector and an EMA teacher
  • benchmarks/cifar10/resa-resnet18.py (the official CIFAR recipe), benchmarks/cifar100/resa-resnet18.py, and benchmarks/cifar10/resa-resnet18-eval.py (the paper's evaluation)
  • Tests, exports, API docs, and entries in README.md, METHODS.md and RELEASES.rst

Results

ResNet-18, 1000 epochs, batch size 256 on one GPU (L40S), scored with the paper's protocol (teacher features; linear probe / 5-NN, %).

CIFAR-10 CIFAR-100
This PR 93.56 / 92.81 (2 seeds) 72.65 / 66.43
Paper 93.53 / 93.02 72.21 / 66.83
Official code, rerun on the same hardware 93.85 / 92.97 —
  • Every number is within 0.5 of the paper. Our two CIFAR-10 seeds differ by 0.11 / 0.09.
  • During training, ours stays within 0.6 points of the official code at every checkpoint.
  • The soft labels group images by class: on CIFAR-10, 61% of the credit an image shares with others goes to its own class (10% by chance).

The runs behind the table (CIFAR-10 with --seed 0 and --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-100
resa-cifar10-vs-official-light

Implementation notes

  • The loss runs in float32 with autocast off, because exp(S / 0.05) amplifies rounding error twentyfold.
  • Under DDP the teacher features are all-gathered and Sinkhorn normalizes over the global batch, so each rank's soft labels equal its rows of the single-process ones.
  • Each view gets its own backbone call, so BatchNorm statistics stay per view, as in the official code.
  • Differences from the official code:
    • Its ResNet zero-pads the input by one pixel before the CIFAR stem (34×34 feature maps); we use the library's standard CIFAR ResNet-18.
    • Our teacher also averages BatchNorm running statistics.
    • The momentum coefficient is updated once per epoch rather than every step (at most 6e-6 apart).
    • The benchmark defaults to mixed precision; the official CIFAR code uses float32.
  • Scope: the paper's CIFAR recipe (two views, no predictor). ImageNet was not run.

How it was validated

  1. Unit tests against a pinned copy of the official loss (Apache-2.0, credited in THIRD_PARTY_NOTICES.md): identical loss and gradients for 2 and 4 views, plus edge cases.
  2. A real two-process DDP test and a Manager train/stop/resume test of the ReSA class.
  3. A 20-epoch side-by-side run against the official code, then full 1000-epoch runs of both, one L40S each.
  4. Scoring with 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

  • I have read the Contributing document.
  • The documentation is up-to-date with the changes I made (check build artifacts).
  • All tests passed, and additional code has been covered with new tests.
  • I have added the PR to the RELEASES.rst file.

@Aarjav0210
Aarjav0210 force-pushed the feat/resa branch 2 times, most recently from 8a71a88 to bb0ef34 Compare October 23, 2026 16:30
@Aarjav0210

Aarjav0210 commented Oct 23, 2026 •

Copy link
Copy Markdown
Author

Test contracts

What 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 stable_pretraining/tests/.

unit/test_resa.py · TestReSALoss (the loss alone, random features)

# 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.

@Aarjav0210 Aarjav0210 changed the title [WIP] feat(methods): add ReSA [Feature] Add ReSA Oct 23, 2026
@Aarjav0210
Aarjav0210 marked this pull request as ready for review October 23, 2026 19:35

@Leon-Leyang Leon-Leyang left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @Aarjav0210, I've gone through the PR. Please check the issues below:

  • stable_pretraining/methods/resa.py:172: ReSA.forward takes (view1, view2) and repeats the steps of resa (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: ReSA isn'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.

@Aarjav0210

Copy link
Copy Markdown
Author

Thanks @Leon-Leyang, all four are addressed:

  • ReSA now passes forward.resa to Module.__init__, so it takes (batch, stage) and returns the forward function's dict. Its own forward and ReSAOutput are gone. Since it no longer takes image tensors, it is out of the shared tensor-based smoke and evaluation tests. test_resa.py tests the class on Module batches instead, and the resume test now trains the class through spt.Manager.
  • ReSA is exported from the top-level package (_LAZY_ATTRS, __all__, __init__.pyi).
  • benchmarks/cifar10/resa-resnet18-eval.py is the evaluation behind the reported linear-probe and 5-NN numbers (--dataset cifar100 for CIFAR-100).
  • The description now states the batch size (256, one GPU) and the commands behind the table.

@codecov

codecov Bot commented Dec 1, 2026

Copy link
Copy Markdown

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:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@Leon-Leyang Leon-Leyang left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @Aarjav0210, I've gone through the changes and it looks good to me.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants