Metadata-Version: 2.4
Name: aria-trl
Version: 1.1.1
Summary: Continual learning for LLM fine-tuning via ARIA mechanisms (PlasticityGatedMLP, SPC, Task Adapters)
Home-page: https://github.com/rsd-darshan/ARIA-TRL
Author: Darshan Poudel
Author-email: Darshan Poudel <poudeldarshan44@gmail.com>
License: MIT
Project-URL: Homepage, https://github.com/rsd-darshan/ARIA-TRL
Project-URL: Repository, https://github.com/rsd-darshan/ARIA-TRL.git
Project-URL: Issues, https://github.com/rsd-darshan/ARIA-TRL/issues
Keywords: continual-learning,llm,fine-tuning,catastrophic-forgetting,fast-slow-pathways,fisher-consolidation
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: torch>=2.0.0
Requires-Dist: transformers>=4.30.0
Requires-Dist: trl>=0.7.0
Requires-Dist: datasets>=2.10.0
Requires-Dist: numpy>=1.23.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: black>=23.0; extra == "dev"
Requires-Dist: isort>=5.12; extra == "dev"
Requires-Dist: mypy>=1.0; extra == "dev"
Provides-Extra: examples
Requires-Dist: wandb>=0.15.0; extra == "examples"
Dynamic: author
Dynamic: home-page
Dynamic: license-file
Dynamic: requires-python

# aria-trl: Continual Learning for LLM Fine-tuning

[![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/downloads/)
[![PyTorch 2.0+](https://img.shields.io/badge/PyTorch-2.0%2B-ee4c2c.svg)](https://pytorch.org/)
[![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](https://github.com/rsd-darshan/ARIA-TRL/blob/master/LICENSE)

**aria-trl** brings ARIA's continual learning mechanisms to Hugging Face's TRL library, enabling fine-tuning of large language models on sequential tasks without catastrophic forgetting.

## Overview

Fine-tuning LLMs sequentially on multiple tasks typically leads to **catastrophic forgetting** — the model forgets earlier tasks while learning new ones. aria-trl prevents this through three ARIA mechanisms:

1. **PlasticityGatedMLP**: Dual fast/slow pathways in FFN layers
   - Fast pathway: volatile, learns task-specific patterns
   - Slow pathway: stable, retains task-generic knowledge
   - Learned gate routes computation per token

2. **Slow-Pathway Consolidation (SPC)**: Fisher-weighted regularization
   - Estimates diagonal Fisher Information after each task
   - Protects consolidated knowledge from being overwritten
   - 50% fewer parameters than standard EWC

3. **Task-Specific Adapters**: Lightweight LoRA-like modules
   - One residual adapter per task
   - Frozen after training to prevent overwriting
   - Minimal parameter overhead

## Version History

aria-trl has been validated twice, each with a methodology improvement over the last:

- **[ARIA-TRL v1](https://github.com/rsd-darshan/ARIA-TRL-v1)** — first validation: standard fine-tuning vs. aria-trl, 3-task sequential benchmark, 3 seeds. aria-trl won on both accuracy (+0.0028) and forgetting (46% less). Superseded by v2's more rigorous comparison.
- **[ARIA-TRL v2](https://github.com/rsd-darshan/ARIA-TRL-v2)** — current validation: adds a real EWC baseline, 8 seeds (3 dev + 5 held-out fresh). aria-trl ties EWC on accuracy and clearly beats it on forgetting. This is the result detailed below, and what the current `aria_trl` package reflects.

Each linked repo is a frozen snapshot of the code and README exactly as they stood at that milestone — this repo keeps moving forward.

## Current Results

### Summary

`distilgpt2` was fine-tuned three ways on the same 3-task continual learning benchmark,
with identical data across all three: **standard sequential fine-tuning** (no protection),
**EWC** (textbook Fisher-weighted consolidation, no fast/slow split), and **aria-trl**
(the three mechanisms described below). Validated in two stages — 3 seeds used during
development, then 5 fresh seeds chosen after the fact and never used while tuning —
reported separately below, not just combined.

**Across all 8 seeds, aria-trl matches EWC on accuracy (within noise) and cuts forgetting
to near zero — while beating unmitigated fine-tuning outright on both metrics.**

> **Reproducing this:** these numbers come from
> [`examples/kaggle_benchmark.py`](https://github.com/rsd-darshan/ARIA-TRL/blob/master/examples/kaggle_benchmark.py), which originally inlined a
> corrected version of the mechanism after three implementation defects (Fisher penalty
> leaking into the fast pathway, gate warmup never activating, cold-started heads) were found
> and fixed while building a fair EWC comparison; see
> [`paper/ARIA_TRL_paper.pdf`](https://github.com/rsd-darshan/ARIA-TRL/blob/master/paper/ARIA_TRL_paper.pdf) Section 2 for details. **These fixes
> have since been ported into the installable `aria_trl/` package.** Porting surfaced a
> fourth, more severe defect specific to the package (not present in the benchmark script):
> `PlasticityGatedMLP` was never copying the pretrained FFN weights into the new fast/slow
> pathways, so every `ContinualSFTTrainer` run silently fine-tuned from randomly-initialized
> FFN layers instead of the pretrained checkpoint — fixed as part of this port. The ported
> package was verified end-to-end on a full seed-42 run: task-0 accuracy went from
> 0.463 (below chance, pre-fix) to 0.762, with ACC and BWT close to the benchmark script's
> numbers and within the seed-to-seed variance already documented above — not byte-identical,
> which isn't a realistic bar across two independently-structured codebases, but the same
> architecture producing statistically consistent results.

### Setup

- **Model:** `distilgpt2`, 5 epochs per task (all three methods)
- **Tasks (in order):** SST-2 (Movies) → Yelp Review Full (Restaurants) → dair-ai/emotion (Social)
- **Dev seeds:** 42, 123, 7 &nbsp;·&nbsp; **Fresh seeds (held out):** 2024, 777, 555, 99, 1234

https://github.com/user-attachments/assets/d720c09b-cad2-484d-a5b4-0e8943961408

### Results

| Metric | Standard FT | EWC | aria-trl |
|---|---|---|---|
| ACC (dev, n=3) | 0.7639 | 0.7903 | 0.7861 |
| ACC (fresh, n=5) | 0.7992 | 0.7942 | 0.7975 |
| **ACC (combined, n=8)** | 0.7859 | 0.7927 | **0.7932** |
| BWT (dev, n=3) | −0.0563 | −0.0334 | −0.0104 |
| BWT (fresh, n=5) | −0.0362 | −0.0313 | −0.0038 |
| **BWT (combined, n=8)** | −0.0438 | −0.0320 | **−0.0063** |

aria-trl's combined-8 ACC is +0.0005 ahead of EWC — smaller than either method's own
seed-to-seed std (0.008–0.018), i.e. a statistical tie, not a win. BWT is +0.0257 ahead of
EWC and +0.0375 ahead of Standard FT — the least forgetting of the three at every
validation stage. This is not a clean sweep: 3 of the 8 seeds are simultaneous losses on
both metrics for aria-trl, reported honestly rather than averaged away — see the paper for
the per-seed breakdown.

<p align="center"><img src="https://raw.githubusercontent.com/rsd-darshan/ARIA-TRL/master/assets/fig1_summary_bars.png" width="85%" alt="ACC and BWT summary bar chart, 8 seeds"></p>

<p align="center"><img src="https://raw.githubusercontent.com/rsd-darshan/ARIA-TRL/master/assets/fig2_dev_vs_fresh_validation.png" width="85%" alt="Dev vs fresh seed validation"></p>

The same pattern — aria-trl tied with EWC on ACC, ahead on BWT — holds independently in the development seeds and the fresh, previously-unseen seeds.

<p align="center"><img src="https://raw.githubusercontent.com/rsd-darshan/ARIA-TRL/master/assets/fig3_forgetting_curves_8seed.png" width="85%" alt="Per-seed forgetting curves, 8 seeds"></p>

Task-0 accuracy after each step, all 8 seeds shown individually. Seeds 777 and 1234 are where aria-trl's retention advantage does not hold.

<p align="center"><img src="https://raw.githubusercontent.com/rsd-darshan/ARIA-TRL/master/assets/fig4_accuracy_matrix.png" width="85%" alt="Accuracy matrix heatmap"></p>

Full accuracy matrix, seed 42 — aria-trl's off-diagonal (older-task) values sit closer to their diagonal values than either baseline's.

Full per-seed numbers: [`results/kaggle_benchmark_results.json`](https://github.com/rsd-darshan/ARIA-TRL/blob/master/results/kaggle_benchmark_results.json). Full write-up with method, defects found, and limitations: [`paper/ARIA_TRL_paper.pdf`](https://github.com/rsd-darshan/ARIA-TRL/blob/master/paper/ARIA_TRL_paper.pdf). Benchmark script: [`examples/kaggle_benchmark.py`](https://github.com/rsd-darshan/ARIA-TRL/blob/master/examples/kaggle_benchmark.py).

## Features

- ✅ **Drop-in Hugging Face Trainer subclass** — minimal code changes
- ✅ **Configurable slow-pathway learning rate** — optional `slow_lr_ratio` on top of gradient dampening
- ✅ **Gradient dampening** — slow grads scaled by (1−π̄)
- ✅ **Per-task adapters & heads** — isolates task-specific classification boundaries
- ✅ **Full checkpoint support** — save/load with consolidation state
- ✅ **Validated against EWC** — 8-seed sequential classification benchmark

## Installation

```bash
pip install aria-trl
```

Or install from source:

```bash
git clone https://github.com/rsd-darshan/ARIA-TRL.git
cd ARIA-TRL
pip install -e .
```

## Quick Start

```python
from aria_trl import ContinualSFTTrainer, ARIAConfig
from transformers import AutoModelForSequenceClassification, AutoTokenizer, TrainingArguments

# Load model
model = AutoModelForSequenceClassification.from_pretrained("distilgpt2", num_labels=2)
tokenizer = AutoTokenizer.from_pretrained("distilgpt2")

# Configure ARIA
aria_config = ARIAConfig(
    plasticity_lambda=0.01,      # bimodal gate specialization
    spc_lambda=100.0,            # Fisher consolidation strength
    adapter_dim=64,              # task adapter bottleneck
    # slow_lr_ratio defaults to 1.0 (gate-driven gradient dampening is the
    # only slow-pathway throttle by default; lower this only on top of that,
    # not instead of it) and warmup_steps defaults to None (auto-computed
    # from your actual dataset size and batch size).
)

# Training arguments
args = TrainingArguments(
    output_dir="./checkpoints",
    learning_rate=2e-4,
    num_train_epochs=3,
    per_device_train_batch_size=8,
)

# Create trainer
trainer = ContinualSFTTrainer(
    model=model,
    tokenizer=tokenizer,
    args=args,
    train_dataset=task1_train,
    eval_dataset=task1_eval,
    aria_config=aria_config,
)

# Train on task 1
trainer.train()

# Consolidate before next task (Fisher estimation)
trainer.consolidate_task(task_id=0)

# Train on task 2
trainer.add_task(task_id=1)
trainer.train_dataset = task2_train
trainer.eval_dataset = task2_eval
trainer.train()

# Consolidate again
trainer.consolidate_task(task_id=1)

# Evaluate on all tasks to measure forgetting
metrics = trainer.evaluate_all_tasks(all_tasks)
```

## Core Components

### ARIAConfig

Configuration for ARIA continual learning:

```python
from aria_trl import ARIAConfig

config = ARIAConfig(
    plasticity_lambda=0.01,          # Bimodal specialization loss weight
    spc_lambda=100.0,                # Fisher regularization strength
    adapter_dim=64,                  # Task adapter bottleneck dimension
    slow_lr_ratio=1.0,               # Slow pathway LR multiplier (on top of
                                      # gate-driven gradient dampening, which
                                      # is the default throttle — see below)
    warmup_steps=None,               # None = auto-compute one epoch's worth
                                      # of steps from your dataset/batch size
    consolidation_steps_per_task=None # Fisher estimation steps (None=all)
)
```

### PlasticityGatedMLP

Replaces transformer FFN layers automatically. Routes per-token computation:

```
output = π * fast_pathway(x) + (1−π) * slow_pathway(x)
```

where π ∈ (0,1) is learned and regularized to specialize (0 or 1).

### TaskFastAdapter

Per-task residual adapter (LoRA-like):

```
h_new = h + adapter(h)
```

Bottleneck design: `h → compress → ReLU → expand`, zero-initialized expansion.

### FisherConsolidator

Estimates diagonal Fisher Information on validation data after each task:

```python
consolidator = FisherConsolidator(model, device)
consolidator.consolidate(task_id, eval_loader)
loss = consolidator.compute_spc_loss(global_step)
```

## Metrics

Compute continual learning metrics with:

```python
from aria_trl.utils import compute_continual_metrics

metrics = compute_continual_metrics(task_accuracies)
# Returns: avg_accuracy, forgetting, forward_transfer
```

- **Average Accuracy**: Mean accuracy on all tasks at end
- **Forgetting**: How much old tasks degrade (lower is better)
- **Forward Transfer**: How much new tasks benefit from old tasks

## Example: DistilGPT2 on Sequential Tasks

See [`examples/distilgpt2_example.py`](https://github.com/rsd-darshan/ARIA-TRL/blob/master/examples/distilgpt2_example.py) in the GitHub repository for a quickstart example (or [`examples/kaggle_benchmark.py`](https://github.com/rsd-darshan/ARIA-TRL/blob/master/examples/kaggle_benchmark.py) for the full 8-seed SST-2 → Yelp → Emotion benchmark):

```bash
python examples/distilgpt2_example.py
```

Trains on 3 sequential tasks (sentiment, toxicity, spam) and prints metrics.

## How ARIA Prevents Forgetting

### The Problem
Standard fine-tuning on sequential tasks overwrites weights learned on earlier tasks:

```
Task 1:  [update all weights]
Task 2:  [update all weights again] ← Task 1 weights overwritten
Task 3:  [update all weights again] ← Task 1 & 2 weights overwritten
Eval:    [accuracy on Task 1 ↓↓↓]   ← Catastrophic forgetting!
```

### The Solution
ARIA separates fast (volatile) and slow (stable) pathways:

```
Fast pathway:  [updates freely, learns task-specific patterns]
Slow pathway:  [updates slowly, consolidated by Fisher regularization]
Gate π:        [routes each token: fast for new patterns, slow for stability]

Result: Old tasks remain in slow pathway, new tasks learn in fast pathway
```

## Design Philosophy

aria-trl's design prioritizes:

1. **Compatibility**: Subclasses Hugging Face `Trainer`, compatible with standard transformer models
2. **Simplicity**: Three mechanisms, no complex multi-model ensembles
3. **Efficiency**: Task adapters add <1% parameters, Fisher diagonal reduces memory
4. **Interpretability**: Gate π shows per-token plasticity, easy to debug

## Papers & Motivation

- **ARIA** (PyTorch): [paper (PDF)](https://github.com/rsd-darshan/ARIA/blob/main/paper/aria.pdf) · [repo](https://github.com/rsd-darshan/ARIA) — core continual learning research on Split-MNIST and Split-CIFAR-10
- **aria-trl** (TRL): [paper (PDF)](https://github.com/rsd-darshan/ARIA-TRL/blob/master/paper/ARIA_TRL_paper.pdf) — this package; brings ARIA mechanisms to LLM fine-tuning via Hugging Face
- **NCG**: ["Novelty-triggered Capacity Growth"](https://github.com/rsd-darshan/NCG) — reactive capacity expansion (predecessor)
- **EWC**: ["Elastic Weight Consolidation"](https://arxiv.org/abs/1612.00796) — standard baseline for catastrophic forgetting

## Limitations & Future Work

- **Task-incremental setting**: Uses per-task adapters and classification heads (task identity known at evaluation time)
- **Fisher diagonal only**: Full Fisher or Kronecker-factored approximations are future work
- **DistilGPT2 tested**: Larger models (7B+) need memory optimization
- **Binary classification**: Multi-class and open-ended language modeling tasks need further validation

## Contributing

Contributions welcome! Please:

1. Fork the repo
2. Create a feature branch (`git checkout -b feature/my-feature`)
3. Commit your changes
4. Push to remote and open a PR

## License

MIT License — see [LICENSE](https://github.com/rsd-darshan/ARIA-TRL/blob/master/LICENSE) for details.

## Citation

If you use aria-trl in your research, please cite:

```bibtex
@software{poudel2026aria_trl,
  title   = {aria-trl: Continual Learning for LLM Fine-tuning},
  author  = {Poudel, Darshan},
  year    = {2026},
  url     = {https://github.com/rsd-darshan/ARIA-TRL}
}
```

## Contact

- **GitHub**: [@rsd-darshan](https://github.com/rsd-darshan)
- **Email**: poudeldarshan44@gmail.com

---

**aria-trl** — continual learning, without the catastrophe.
