merge-and-rebase
Repo Tour
Research codebase for:
- OpenCLIP fine-tuning
- checkpoint merging
- task-vector transport / rebase
- vision + text evaluation
One-Sentence Summary
This repo is a config-driven lab for:
- training task-specific models,
- turning them into deltas,
- merging or transporting those deltas,
- evaluating the result on shared suites.
The Big Mental Model
Three verbs explain almost everything:
finetune/: create task-specific checkpointsmerge/andrebase/: transform updateseval/: run experiments and report metrics
If you keep those three buckets in mind, the folder structure makes sense quickly.
What uv Is
uv is a fast Python packaging toolchain.
In practice, it combines the jobs people often split across:
python -m venvpip- lockfile management
- one-shot run commands
So in this repo, uv is the default way to create the environment and install the package.
uv Vs conda
A useful mental model is:
condamanages environments plus many non-Python binaries and system-style dependenciesuvis focused on Python packaging, virtualenvs, andpip-style installs
So uv feels closer to:
venv+pip, but faster and more integrated
When To Prefer uv Here
uv is the better fit for this repo because the project already ships:
pyproject.toml- optional dependency groups
uv.lock
That means the repo is already describing itself in standard Python packaging terms.
When People Still Use conda
conda can still be a good choice when you need:
- non-Python libraries managed at the environment level
- a prebuilt CUDA / system dependency stack
- mixed-language scientific environments
But for this codebase, the happy path is still:
- create a normal virtualenv with
uv - install the repo in editable mode
uv Workflow Compared With conda
conda style:
conda create -n merge-rebase python=3.12
conda activate merge-rebase
pip install -e ".[dev,data,test]"
uv style:
uv venv .venv
source .venv/bin/activate
uv pip install -e ".[dev,data,test]"
Useful uv Commands
uv venv .venv
uv pip install -e .
uv pip install -e ".[data]"
uv pip install -e ".[dev,data,test]"
uv run pytest
uv run ruff check .
The repo mostly uses uv for install and then regular python -m ... entrypoints.
Install: Minimal
uv venv .venv
source .venv/bin/activate
uv pip install -e .
Use this if you only want the base package and code imports.
Install: For Real Experiments
uv pip install -e ".[data]"
Use .[data] when you want:
- Hugging Face datasets
- PIL image support
- normal train/eval data pipelines
Install: Dev Mode
uv pip install -e ".[dev,data,test]"
Use this if you also want:
ruffpytest- the full repo workflow
What Editable Install Means
uv pip install -e . means:
- Python imports resolve to
src/merge_and_rebase/ - you can edit code without reinstalling
- good for iterative research work
Example:
- edit
src/merge_and_rebase/eval/vision_merge.py - rerun the command immediately
Top-Level Layout
Important paths:
src/merge_and_rebase/: actual package codeconfigs/: ready-made JSON experiment configsdocs/: the slides and docs artifactstests/: regression testsscripts/: small helper scriptsREADME.md: quickstart
Main Entrypoints
python -m merge_and_rebase.finetune.train_vision
python -m merge_and_rebase.finetune.train_text
python -m merge_and_rebase.eval.vision_merge
python -m merge_and_rebase.eval.vision_rebase
python -m merge_and_rebase.eval.diagnostics.vision_connectivity
python -m merge_and_rebase.eval.llm_merge
These are the commands people usually run, not library calls.
Typical Repo Flow
flowchart TD
A[config file]
B[entrypoint script]
C[data + model setup]
D[checkpoint or delta transformation]
E[evaluation metrics]
F[saved artifact]
A --> B --> C --> D --> E --> F
That same pattern appears in vision, text, merge, and rebase.
End-to-End Vision Story
A common workflow looks like this:
- fine-tune one checkpoint per task
- load those checkpoints together
- convert them into task vectors
- merge them with a chosen method
- evaluate the merged model on the suite
Flow Diagram
flowchart TD
A[vision config YAML]
B[train_vision.py]
C[fine-tuned checkpoints .pt]
D[vision_merge.py or vision_rebase/]
E[merged or transported checkpoint]
F[per-task accuracy + normalized accuracy]
A --> B --> C --> D --> E --> F
Fine-Tuning Example Command
python -m merge_and_rebase.finetune.train_vision \
--vision-config src/merge_and_rebase/finetune/configs/vision.yaml \
--suite vision8
What this means:
- use the vision config preset
- pick the
vision8dataset suite - train one task at a time in the configured order
Fine-Tuning Code Path
Small version of what train_vision.py does:
cfg_file = _load_config(args.vision_config)
tasks = resolve_tasks(args, cfg_file)
for task in tasks:
summary = train_task(
task=task,
build_cfg=build_cfg,
strategy=strategy,
...,
)
This is why the repo feels config-driven: the outer script mostly resolves config, then loops through tasks.
What train_vision.py Does
Per task, it roughly does:
- resolve config
- load the HF dataset
- build OpenCLIP
- build zero-shot text features
- choose a training strategy
- train and validate
- save checkpoint + JSON summary
Vision Config Shape
The config style is:
common:
backbone: ...
train: ...
strategy: ...
output: ...
datasets:
CIFAR10:
train:
epochs: 10
So there is a shared default block plus per-dataset overrides.
Vision Config Example
common:
backbone:
clip_model: ViT-B-32
clip_pretrained: openai
strategy:
name: full
train:
lr: 1e-4
epochs: 5
This is the default experiment template that train_vision.py expands task by task.
Vision Strategies
Built-in vision strategies:
full: train all parameterslinear_probe: train only the classification headpeft_lora: LoRA on the OpenCLIP visual backbone
Strategy Example
strategy:
name: peft_lora
forward_mode: linearized_ntk
peft:
r: 16
lora_alpha: 16
target_modules: [q_proj, k_proj, v_proj, out_proj]
This tells the repo to fine-tune only low-rank adapters on selected visual modules while training in the linearized NTK regime.
Method Presets: TAK and DELTA
Two research presets build on strategies + regularizers:
- TAK (
configs/TAK/):linearized_ntk+parameterization: delta+kfac_ggncurvature penalty from the other tasks - DELTA (
configs/DELTA/): non-linear student,compositeof distillationfrom an online linearized teacher along θ₀ + α·τekfac_ggnpenalty on ImageNet21KP
Full FT and LoRA variants, for ViT-B/32, B/16, and L/14 on vision8/14/20.
Text Pre-Stages
train_vision.py can optionally tune the text side before vision training.
Options:
text_embeddings_finetunetext_prompt_tuning
Purpose:
- adapt zero-shot text features before tuning the image encoder
Text Pre-Stage Example
strategy:
name: full
text_prompt_tuning:
enabled: true
context_length: 16
epochs: 1
This is the CoOp-style route: learn prompt context vectors first, then run the main vision strategy.
What Gets Saved After Vision Training
For each task, the repo saves:
- a checkpoint
.pt - a summary
.json - optionally a PEFT adapter directory
Typical checkpoint payload includes:
- backbone info
- metrics
- strategy name
- tuned text features when present
Example Output Layout
src/checkpoints/finetune/
ViT-B-32/
openai/
CIFAR10/
full_best_ep.pt
full.json
This makes downstream merge runs easy because every task has a predictable checkpoint location.
From Checkpoint To Task Vector
Core idea:
task vector = tuned checkpoint - base checkpoint
In code, this logic lives in:
merge/task_vectors.py
That file handles:
- filtering keys
- checking compatibility
- flattening / unflattening
- norms and masking
Tiny Task-Vector Example
If a base weight is:
W_base = [1.0, 2.0]
and a tuned weight is:
W_tuned = [1.2, 1.7]
then the task vector is:
D = W_tuned - W_base = [0.2, -0.3]
Task-Vector Code Snippet
This is the actual API shape used in the repo:
tv = TaskVector.from_checkpoints(base_sd, tuned_sd, strict=True)
delta = tv.delta
norm = tv.l2_norm()
So the merge code usually starts from checkpoint pairs, not handwritten tensors.
Merge Example Command
python -m merge_and_rebase.eval.vision_merge \
--config configs/vision8_task_arithmetic.json
This is the main vision merge entrypoint.
It expects a config that tells it:
- which base model to use
- which tuned checkpoints to load
- which merge method to apply
Merge Code Snippet
The core pattern looks like this:
method = get_method(cfg["method"])
prepared = method.prepare(
base=base_sd,
tuned=tuned_sds_list,
weights=weights,
)
merged_sd = method.apply(prepared=prepared, alpha=alpha)
That prepare -> apply split is what makes alpha search cheap.
What vision_merge.py Does
High level:
- build the base OpenCLIP model
- load tuned checkpoints
- align keys to the base model
- prepare the merge method
- evaluate merged weights on each task
Merge Config Example
{
"suite": "vision8",
"method": "task_arithmetic",
"alpha_search": true,
"tuned_ckpts": {
"CIFAR10": "...pt",
"EuroSAT": "...pt"
}
}
This is the kind of JSON that drives merge experiments.
Alpha Search
Instead of assuming the merge scale should be 1.0, the repo can scan a range.
Example:
alpha in {0.0, 0.1, 0.2, ..., 2.0}
This is useful because many merge methods produce the best accuracy at a non-default scale.
Alpha Search Example
Conceptually:
merged(alpha) = base + alpha * merged_delta
Example outcomes:
alpha = 0.0: just the base modelalpha = 1.0: standard merge outputalpha = 1.4: sometimes stronger transfer
Text Features In Vision Eval
Vision eval has an important choice:
- use zero-shot prompt templates
- use tuned text features saved in checkpoints
Controlled by:
text_features_source = autozero_shottuned_ckpt
Text Feature Example
If a checkpoint contains tuned text features:
autouses themtuned_ckptrequires themzero_shotignores them and rebuilds from templates
This matters because a merged vision model may pair better with either tuned or zero-shot text embeddings.
Merge Methods: Simple Family
Methods that are easiest to explain first:
task_arithmeticweighted_averageties_mergedare_merge
These mostly work directly on task deltas or aligned states.
Merge Methods: Matrix / SVD Family
More structure-heavy methods:
tsv_mergeisoc_mergeisocts_mergecart_mergepcb_merge
These are more research-oriented and often manipulate matrices or flattened deltas in a specific way.
Method Example: Task Arithmetic
Task arithmetic is the simplest mental model:
D_merge = w1 * D1 + w2 * D2 + ...
merged = base + D_merge
Good first method to read in code:
merge/methods/task_arithmetic.py
Method Example: TIES
TIES roughly does:
- prune small entries
- resolve signs across tasks
- merge only sign-consistent entries
That makes it less naive than pure summation when task deltas conflict.
PEFT Checkpoints
The repo also supports LoRA / PEFT checkpoints.
That means merge code sometimes works with:
- full state dicts
- PEFT adapter state
- PEFT adapter directories
Important helper files:
io/peft_helpers.pyeval/merge_utils.pyeval/utils.py
PEFT Subspaces
For PEFT merges, there are subspace options:
identitycoreknots
These live in:
merge/subspaces/
They project LoRA updates into a mergeable space, then lift them back.
Subspace Example Intuition
Without a subspace, you can think in terms of merging raw adapter tensors.
With a subspace, you instead do:
adapter updates -> project -> merge in low-rank space -> lift back
That is why core_space.py and knots_space.py matter.
Rebase Example Command
python -m merge_and_rebase.eval.vision_rebase \
--config configs/vision8_gradfix_rebase.json
This is for the case where you want to move a merged update from source base A onto target base B.
Rebase Code Snippet
Conceptually, the rebase path looks like this:
deltas = [TaskVector.from_checkpoints(source_base, tuned).delta for tuned in tuned_sds]
merged_delta = compose_weighted_deltas(deltas, weights)
transport = GradFixRebase()
prepared = transport.prepare(
target_model=target_model,
target_dataloader=grad_loader,
recipe=clip_contrastive_recipe(...),
)
rebased_delta = transport.apply(prepared, delta=merged_delta)
The important idea is: merge first, then transport the merged delta.
What Rebase Means
Normal merge says:
- combine updates around one base model
Rebase says:
- take an update defined around base A
- transport it so it can be applied to base B
That is the role of rebase/.
Rebase Mental Model
source base A
+ merged task vector D_merge
-> transport(D_merge, A, B)
-> D_transport
-> target base B + D_transport
So the update moves, not just the raw checkpoint.
Built-In Rebase Methods
identity: no transport, just reuse the deltaorthogonal_shift: remove the part aligned withB - Agradfix: compute gradient signs on the target side and mask the delta
GradFix In Plain English
GradFix asks:
- when we evaluate on the target model, which parameter directions seem helpful?
Then it:
- computes gradient signs on target data
- compares those signs to the transported delta
- keeps or forces entries based on agreement
GradFix Example
Imagine one transported delta entry is -0.4.
If GradFix says the target gradient sign prefers negative movement too:
- keep it in
normalmode
If the signs disagree:
- zero it out in
normal - or flip/force it in
force
Why grad_recipes.py Exists
GradFix is model-agnostic.
So it needs model-specific recipes for:
- how to compute the loss
- which parameters to track
That is why the repo has:
clip_contrastive_recipecausal_lm_recipeseq_classification_recipe
Forward Modes In Vision Eval
Vision evaluation supports different forward modes:
standardlinearized_ntk
Defined in:
models/forward_modes.py
This is one of the more research-specific features in the repo.
What linearized_ntk Means Here
It replaces the normal forward pass with a first-order linearization around base weights.
In practice:
- useful when checkpoints were trained with
strategy.forward_mode: linearized_ntk - helps evaluation match the intended linearized training regime
Core helper:
utils/linearization.py
Connectivity Experiments
eval/vision_connectivity.py is for interpolation analysis.
Typical questions it answers:
- what happens along the line between checkpoint A and B?
- is there a barrier in accuracy or loss?
- what does the plane spanned by two deltas look like?
Text / LLM Side
There is a parallel text track too.
Main files:
finetune/train_text.pydata/text_loaders.pymodels/text_lm.pyeval/llm_merge.py
The main benchmark family here is NLI.
Text Training Example
python -m merge_and_rebase.finetune.train_text \
--text-config src/merge_and_rebase/finetune/configs/text-peft.yaml \
--suite nli6
This trains sequence-classification models on the NLI task suite.
Text Training Code Path
Small version of the text runner loop:
cfg_file = _load_config(args.text_config)
tasks = resolve_tasks(args, cfg_file)
for task in tasks:
summary, head = train_task(
task=task,
build_cfg=build_cfg,
strategy=strategy,
...,
)
It mirrors train_vision.py, but on tokenized NLI data and HF text models.
What train_text.py Does
It roughly:
- loads the HF text model
- loads tokenized NLI data
- applies a strategy
- trains per task
- saves checkpoints and extracted task heads
Supported text strategies:
fulllinear_probepeft_lora
Text Merge Example
python -m merge_and_rebase.eval.llm_merge \
--config configs/llm_merge_llama3_8b_knots_hf.json
This is the text-side analogue of vision_merge.py, with extra logic for adapters and task heads.
Data Package
data/ is split cleanly:
vision_loaders.py: HF image datasets, transforms, splits, classnamestemplates.py: zero-shot prompt templatestext_loaders.py: NLI task specs, tokenization, loaders
Read these early if you want to understand what the experiments are actually feeding into the models.
Models Package
models/ is where the repo wraps backbone libraries.
Key files:
openclip_classifier.pytext_lm.pygrad_recipes.pypatch_openclip_attention.pyforward_modes.py
This package is the interface between raw libraries and repo-specific experiments.
Finetune Package
finetune/ is where training policy lives.
Key ideas:
- config-driven task loops
- strategy registry
- optional text pre-stages
- regularizers
- checkpoint export formats
If you want to add a new training mode, start here.
Merge Package
merge/ is the math core.
Important files:
task_vectors.pybase.pyregistry.pymethods/subspaces/
If you want to add a new merge algorithm, this is the package to study first.
Rebase Package
rebase/ is smaller but conceptually important.
It defines:
- the transport interface
- built-in transport methods
- GradFix utilities
If merge is “combine deltas,” rebase is “move deltas between coordinate systems.”
Eval Package
eval/ is the orchestration layer.
It contains:
- main experiment scripts
- shared CLI glue
- caching helpers
- reporting helpers
- PEFT materialization logic
This is where most full experiments come together.
IO + Utility Layer
Small but critical helpers:
io/ckpt.py: normalize and align checkpointsio/peft_helpers.py: detect/load PEFT formatsutils/helpers.py: parse config inputsutils/linearization.py: JVP-based linearization
These files make the rest of the code less repetitive.
Configs + Tests + Scripts
The repo is easier to learn if you use these as documentation:
configs/: runnable examplestests/: edge cases and intended behaviorscripts/: one-off utilities like checkpoint download helpers
Often the fastest way to learn a feature is to find its test first.
How The Registry Pattern Works
This repo uses a lightweight plugin pattern.
The idea is:
- define a protocol such as
MergeMethodorStrategy - keep a global dictionary keyed by
name - expose
register(...),get_* (...), andlist_* (...) - import implementation modules so they register themselves
That is how new components become visible to the entrypoints.
Registry Example: Merge Methods
The merge registry is essentially:
_METHODS: dict[str, MergeMethod] = {}
def register(method):
_METHODS[method.name] = method
def get_method(name):
return _METHODS[name]
Then each method module ends with something like:
register(TaskArithmeticMerge())
Why This Design Is Nice
Why use registries instead of giant if/elif trees?
- entrypoints stay small
- implementations live next to their own logic
- CLI/config can refer to components by name
- adding a component usually means adding one new file, not editing many call sites
Extension Points In This Repo
The main plugin-style families are:
- merge methods
- rebase methods
- finetuning strategies
- PEFT subspaces
- regularizers
Each family has:
- a base protocol
- a registry file
- implementation modules that call
register(...)
How Discovery Actually Happens
The important trick is side-effect import.
Example:
merge/registry.pyimportsmerge.methodsmerge.methodsimports the concrete method files- each concrete file calls
register(...)
So by the time get_method(...) is used, the registry has already been populated.
Side-Effect Import Example
The pattern looks like this:
# registry.py
from . import methods as _methods
# task_arithmetic.py
register(TaskArithmeticMerge())
The import is not used directly for values. It exists so Python executes the module and triggers registration.
How To Add A Merge Method
Steps:
- create a file in
merge/methods/ - implement a class with a unique
name - implement
merge(...), or betterprepare(...)+apply(...) - call
register(YourMethod()) - make sure the module is imported by
merge/methods/__init__.py
Then the method becomes usable from config and CLI.
Merge Method Template
from dataclasses import dataclass
from ..base import TensorDict
from ..registry import register
@dataclass(frozen=True)
class MyMerge:
name: str = "my_merge"
def merge(self, *, base: TensorDict, tuned, weights=None, **kwargs):
...
register(MyMerge())
If you support alpha search, add prepare(...) and apply(...) too.
When To Implement prepare And apply
Use the prepared form when:
- one expensive computation can be reused
alphaonly rescales or recomposes the result
That is exactly why methods like task arithmetic fit the pattern well.
How To Add A Finetuning Strategy
Steps:
- create a file in
finetune/strategies/ - implement a class with
name - implement
configure(...) - set
requires_gradfor the right parameters - return
(optimizer, scheduler, info) - call
register(YourStrategy()) - import the module from
finetune/strategies/__init__.py
Strategy Template
from dataclasses import dataclass
from .registry import register
@dataclass(frozen=True)
class MyStrategy:
name: str = "my_strategy"
def configure(self, *, model, lr, weight_decay, device, **kwargs):
# choose trainable params
# build optimizer
# build scheduler
return opt, scheduler, {"trainable_params": n}
register(MyStrategy())
What configure(...) Is Responsible For
A strategy owns training policy.
That usually means:
- which params are trainable
- whether forward is patched or wrapped
- optimizer choice
- scheduler choice
- reporting summary info
So if you add a strategy, think “training policy module,” not just “optimizer preset.”
How To Add A Regularizer
Regularizers live in finetune/regularizers/ and are registered by name.
Built-ins:
distillation: teacher feature/logit matching, optionally along θ₀ + α·τkfac_ggn: K-FAC curvature penalty on τ over reference tasks (used by TAK)ekfac_ggn: eigenvalue-corrected K-FAC variantcomposite: sums several child regularizers (used by DELTA)
Regularizer Template
A new regularizer implements the Regularizer protocol from regularizers/base.py:
from dataclasses import dataclass
from .registry import register
@dataclass(frozen=True)
class MyRegularizer:
name: str = "my_regularizer"
def finalize_model(self, *, model, device, regularization_cfg=None, **kwargs):
return {} # optional model patching
def prepare(self, *, model, device, regularization_cfg=None, **kwargs):
return prepared_state, {} # expensive, once per task
def apply(self, prepared, *, model, step, batch_index, **kwargs):
return loss_tensor # added to the task loss
register(MyRegularizer())
Registering It
Built-ins are imported for side-effect registration in regularizers/__init__.py. Add one line there:
from . import my_regularizer as _my_regularizer # noqa: F401
It then works standalone or as a child of composite.
How To Add A Rebase Method
Steps:
- create a file in
rebase/methods/ - implement
transport(...), orprepare(...)+apply(...) - give it a unique
name - call
register(YourTransport()) - ensure
rebase/methods/__init__.pyimports it
Rebase Method Template
from dataclasses import dataclass
from ..registry import register
@dataclass(frozen=True)
class MyTransport:
name: str = "my_transport"
def transport(self, *, source_base, target_base, delta, **kwargs):
return dict(delta)
register(MyTransport())
Use prepared state if transport needs expensive target-side setup.
How To Add A PEFT Subspace
Steps:
- create a file in
merge/subspaces/ - implement
prepare(...),project(...), andlift(...) - give it a unique
name - call
register(YourSpace()) - import it from
merge/subspaces/__init__.py
This is the PEFT analogue of adding a merge method.
Subspace Template
from dataclasses import dataclass
from .registry import register
@dataclass(frozen=True)
class MySpace:
name: str = "my_space"
def prepare(self, *, lora_by_task, peft_cfg):
...
def project(self, prepared, *, lora_by_task, peft_cfg):
...
def lift(self, prepared, *, merged_core, lora_template, peft_cfg):
...
register(MySpace())
Checklist When Adding Any Component
Whenever you add a new plugin-like component, check these five things:
- unique
name - correct protocol methods implemented
register(...)called- import path that triggers registration exists
- config / CLI name matches the registered
name
If one of these is missing, the component will not be discoverable.
Common Failure Modes
Typical mistakes:
- forgot to call
register(...) - forgot to import the module for side effects
- reused an existing
name - implemented the wrong return shape
- config references the filename instead of the registered
name
Those are exactly the kinds of issues the registry pattern makes easier to debug.
Best Files To Read First
Recommended reading order:
README.mdfinetune/train_vision.pyeval/vision_merge.pymerge/task_vectors.pyrebase/methods/gradfix.pymodels/openclip_classifier.py
That gives you setup, training, merging, transport, and model wrapping in a manageable order.
Best Files For The Text Track
If you care about the NLI / LLM path too, then read:
finetune/train_text.pyeval/llm_merge.pydata/text_loaders.pymodels/text_lm.py
That is the shortest path to the text side of the repo.
Takeaway
The repo is deep, but the architecture is consistent:
- configs describe experiments
- entrypoints assemble them
- loaders and wrappers build inputs/models
- merge/rebase transform updates
- eval reports outcomes
That repeatable pattern is what makes the codebase navigable.