|
| 1 | +<!--Copyright 2025 The HuggingFace Team. All rights reserved. |
| 2 | +
|
| 3 | +Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with |
| 4 | +the License. You may obtain a copy of the License at |
| 5 | +
|
| 6 | +http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | +
|
| 8 | +Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on |
| 9 | +an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the |
| 10 | +specific language governing permissions and limitations under the License. |
| 11 | +
|
| 12 | +⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be |
| 13 | +rendered properly in your Markdown viewer. |
| 14 | +
|
| 15 | +--> |
| 16 | + |
| 17 | +# OSF (Orthogonal Subspace Fine-tuning) |
| 18 | + |
| 19 | +Orthogonal Subspace Fine-tuning ([OSF](https://huggingface.co/papers/2504.07097)) is a PEFT method designed for continual learning that constrains parameter updates to be orthogonal to previously important directions. This approach enables full fine-tuning while preventing catastrophic forgetting without requiring additional parameters or storing previous gradients. |
| 20 | + |
| 21 | +The abstract from the paper is: |
| 22 | + |
| 23 | +*Continual learning in large language models (LLMs) is prone to catastrophic forgetting, where adapting to new tasks significantly degrades performance on previously learned ones. Existing methods typically rely on low-rank, parameter-efficient updates that limit the model's expressivity and introduce additional parameters per task, leading to scalability issues. To address these limitations, we propose a novel continual full fine-tuning approach leveraging adaptive singular value decomposition (SVD). Our method dynamically identifies task-specific low-rank parameter subspaces and constrains updates to be orthogonal to critical directions associated with prior tasks, thus effectively minimizing interference without additional parameter overhead or storing previous task gradients. We evaluate our approach extensively on standard continual learning benchmarks using both encoder-decoder (T5-Large) and decoder-only (LLaMA-2 7B) models, spanning diverse tasks including classification, generation, and reasoning. Empirically, our method achieves state-of-the-art results, up to 7% higher average accuracy than recent baselines like O-LoRA, and notably maintains the model's general linguistic capabilities, instruction-following accuracy, and safety throughout the continual learning process by reducing forgetting to near-negligible levels. Our adaptive SVD framework effectively balances model plasticity and knowledge retention, providing a practical, theoretically grounded, and computationally scalable solution for continual learning scenarios in large language models.* |
| 24 | + |
| 25 | +## How OSF Works |
| 26 | + |
| 27 | +OSF decomposes each weight matrix into high-rank (frozen) and low-rank (trainable) components using SVD: |
| 28 | + |
| 29 | +``` |
| 30 | +W = U_high * S_high * V_high^T + U_low * S_low * V_low^T |
| 31 | +``` |
| 32 | + |
| 33 | +Where: |
| 34 | +- `U_high, S_high, V_high`: Preserve important directions from previous tasks (frozen) |
| 35 | +- `U_low, S_low, V_low`: Allow adaptation to new tasks (trainable) |
| 36 | + |
| 37 | +During training, gradients are projected to be orthogonal to the high-rank subspace, ensuring updates don't interfere with previously learned knowledge. |
| 38 | + |
| 39 | +## Basic Usage |
| 40 | + |
| 41 | +```python |
| 42 | +import torch |
| 43 | +from transformers import AutoModelForCausalLM, AutoTokenizer |
| 44 | +from peft import OSFConfig, get_peft_model |
| 45 | + |
| 46 | +# Load base model |
| 47 | +model = AutoModelForCausalLM.from_pretrained("gpt2") |
| 48 | + |
| 49 | +# Configure OSF |
| 50 | +config = OSFConfig( |
| 51 | + target_modules=["c_attn", "c_proj"], # Target attention layers |
| 52 | + effective_rank=8, # Default rank for decomposition |
| 53 | + rank_pattern={"c_attn": 16} # Override rank for specific modules |
| 54 | +) |
| 55 | + |
| 56 | +# Apply OSF |
| 57 | +model = get_peft_model(model, config) |
| 58 | + |
| 59 | +# Train as usual |
| 60 | +optimizer = torch.optim.AdamW(model.parameters(), lr=3e-4) |
| 61 | + |
| 62 | +tokenizer = AutoTokenizer.from_pretrained("gpt2") |
| 63 | +tokenizer.pad_token = tokenizer.eos_token |
| 64 | + |
| 65 | +inputs = tokenizer("Hello world", return_tensors="pt", padding=True) |
| 66 | +loss = model(**inputs, labels=inputs.input_ids).loss |
| 67 | +loss.backward() |
| 68 | +optimizer.step() |
| 69 | +optimizer.zero_grad() |
| 70 | +``` |
| 71 | + |
| 72 | +## Configuration Options |
| 73 | + |
| 74 | +### Target Modules |
| 75 | + |
| 76 | +You can specify target modules in several ways: |
| 77 | + |
| 78 | +```python |
| 79 | +# Specific module names |
| 80 | +config = OSFConfig(target_modules=["q_proj", "k_proj", "v_proj", "o_proj"]) |
| 81 | + |
| 82 | +# All linear layers |
| 83 | +config = OSFConfig(target_modules="all-linear") |
| 84 | + |
| 85 | +# Model-specific defaults (automatically detected) |
| 86 | +config = OSFConfig() # Uses model-appropriate defaults |
| 87 | +``` |
| 88 | + |
| 89 | +### Effective Rank Configuration |
| 90 | + |
| 91 | +Control the decomposition rank: |
| 92 | + |
| 93 | +```python |
| 94 | +# Global rank (applies to all target modules) |
| 95 | +config = OSFConfig(effective_rank=16) |
| 96 | + |
| 97 | +# Automatic rank (50% of the smaller matrix dimension per target) |
| 98 | +config = OSFConfig(effective_rank=None) |
| 99 | + |
| 100 | +# Per-module rank overrides |
| 101 | +config = OSFConfig( |
| 102 | + effective_rank=8, |
| 103 | + rank_pattern={ |
| 104 | + "q_proj": 16, # Higher rank for query projection |
| 105 | + "gate_proj": 4 # Lower rank for gate projection |
| 106 | + } |
| 107 | +) |
| 108 | +``` |
| 109 | + |
| 110 | +## Training Advice for Continual Learning |
| 111 | + |
| 112 | +### Sequential Task Learning |
| 113 | + |
| 114 | +OSF is specifically designed for learning tasks sequentially. Between tasks, recompute the SVD so the preserved subspace reflects the latest weights. One simple way is to re-wrap the updated base model with OSF again: |
| 115 | + |
| 116 | +```python |
| 117 | +# Task 1: train on domain A with initial preserved subspace |
| 118 | +r = 8 # initial effective rank to preserve |
| 119 | +model = get_peft_model(base_model, OSFConfig(effective_rank=r)) |
| 120 | +train_task(model, task_1_data) |
| 121 | + |
| 122 | +# Task 2: recompute SVD on updated weights and increase preserved subspace |
| 123 | +base_model = model.base_model.model # unwrap updated base |
| 124 | +r += 4 # grow preserved subspace to include Task 1 knowledge |
| 125 | +model = get_peft_model(base_model, OSFConfig(effective_rank=r)) |
| 126 | +train_task(model, task_2_data) |
| 127 | + |
| 128 | +# Task 3: recompute again and expand preserved subspace further |
| 129 | +base_model = model.base_model.model |
| 130 | +r += 4 |
| 131 | +model = get_peft_model(base_model, OSFConfig(effective_rank=r)) |
| 132 | +train_task(model, task_3_data) |
| 133 | +``` |
| 134 | + |
| 135 | +### Budget Allocation for Task Sequences |
| 136 | + |
| 137 | +When training on a known sequence of n tasks, one effective strategy is to progressively allocate model capacity to balance learning new tasks while preserving previous knowledge: |
| 138 | + |
| 139 | +- **Task 1**: Use full capacity (train everything) |
| 140 | +- **Task 2**: Freeze 1/n of model capacity, train remaining (n-1)/n capacity |
| 141 | +- **Task 3**: Freeze 2/n of model capacity, train remaining (n-2)/n capacity |
| 142 | +- **Task n**: Freeze (n-1)/n of model capacity, use 1/n capacity for final task |
| 143 | + |
| 144 | +This approach ensures each task gets adequate learning capacity while progressively preserving more knowledge from previous tasks. |
| 145 | + |
| 146 | +```python |
| 147 | +# Example: 4-task sequence with progressive budget allocation |
| 148 | +n_tasks = 4 |
| 149 | +base_rank = 32 # Starting rank for full capacity |
| 150 | + |
| 151 | +for task_id in range(n_tasks): |
| 152 | + # Calculate remaining capacity for current task |
| 153 | + freeze_fraction = task_id / n_tasks |
| 154 | + remaining_capacity = 1.0 - freeze_fraction |
| 155 | + current_rank = int(base_rank * remaining_capacity) |
| 156 | + |
| 157 | + config = OSFConfig( |
| 158 | + target_modules=["q_proj", "k_proj", "v_proj", "o_proj"], |
| 159 | + effective_rank=current_rank |
| 160 | + ) |
| 161 | + |
| 162 | + print(f"Task {task_id + 1}: Using rank {current_rank} " |
| 163 | + f"({remaining_capacity:.1%} of full capacity)") |
| 164 | + |
| 165 | + # Train on current task |
| 166 | + model = get_peft_model(base_model, config) |
| 167 | + train_task(model, task_data[task_id]) |
| 168 | +``` |
| 169 | + |
| 170 | +### Best Practices |
| 171 | + |
| 172 | +1. **Effective Rank Selection**: Start with `effective_rank=None` (auto sets rank to 50% of the smaller weight dimension per target module) and adjust based on task complexity |
| 173 | +2. **Learning Rate**: Use smaller learning rates (1e-5 to 1e-4) compared to standard fine-tuning |
| 174 | +3. **Task Importance**: Use `rank_pattern` to allocate more capacity to critical modules |
| 175 | +4. **Model Architecture**: OSF works best with transformer architectures having clear attention and MLP separations |
| 176 | +5. **Capacity Planning**: For known task sequences, use progressive budget allocation (1/n, 2/n, ..., (n-1)/n freezing) to balance plasticity and stability |
| 177 | + |
| 178 | +### Memory Considerations |
| 179 | + |
| 180 | +OSF modifies weights in-place and doesn't add parameters, making it memory-efficient: |
| 181 | + |
| 182 | +```python |
| 183 | +# Memory usage remains close to base model |
| 184 | +print(f"Base model parameters: {base_model.num_parameters():,}") |
| 185 | +print(f"OSF model parameters: {osf_model.num_parameters():,}") # Similar count |
| 186 | +``` |
| 187 | + |
| 188 | +## Advanced Usage |
| 189 | + |
| 190 | +### Custom Target Modules |
| 191 | + |
| 192 | +For models with non-standard architectures: |
| 193 | + |
| 194 | +```python |
| 195 | +config = OSFConfig( |
| 196 | + target_modules=["dense", "intermediate.dense"], # Custom layer names |
| 197 | + effective_rank=12, |
| 198 | + rank_pattern={"dense": 8, "intermediate.dense": 16} |
| 199 | +) |
| 200 | +``` |
| 201 | + |
| 202 | +### Integration with Other Methods |
| 203 | + |
| 204 | +OSF can be combined with other techniques: |
| 205 | + |
| 206 | +```python |
| 207 | +# Use with gradient checkpointing for memory efficiency |
| 208 | +model.gradient_checkpointing_enable() |
| 209 | + |
| 210 | +# Apply weight decay selectively (regularizes low-rank factors to limit drift/overfitting in continual updates; keep small) |
| 211 | +optimizer = torch.optim.AdamW([ |
| 212 | + {"params": [p for n, p in model.named_parameters() if "U_low" in n], "weight_decay": 0.01}, |
| 213 | + {"params": [p for n, p in model.named_parameters() if "S_low" in n], "weight_decay": 0.001}, |
| 214 | + {"params": [p for n, p in model.named_parameters() if "V_low" in n], "weight_decay": 0.01}, |
| 215 | +], lr=1e-4) |
| 216 | +``` |
| 217 | + |
| 218 | +## OSFConfig |
| 219 | + |
| 220 | +[[autodoc]] tuners.osf.config.OSFConfig |
| 221 | + |
| 222 | +## OSFModel |
| 223 | + |
| 224 | +[[autodoc]] tuners.osf.model.OSFModel |
| 225 | + |
| 226 | +## Utility Functions |
| 227 | + |
| 228 | +### Weight Decomposition |
| 229 | + |
| 230 | +[[autodoc]] tuners.osf.utils.decompose_weight_matrix |
| 231 | + |
| 232 | +[[autodoc]] tuners.osf.utils.reconstruct_weight_matrix |
| 233 | + |
| 234 | +### Gradient Projection |
| 235 | + |
| 236 | +[[autodoc]] tuners.osf.utils.project_gradient_to_orthogonal_space |
0 commit comments