Metadata-Version: 2.4
Name: vyntri
Version: 1.5.1
Summary: Rapid analytic adaptation of pretrained vision representations, CPU-first.
Author: Vyntri Contributors
License-Expression: MIT
Project-URL: Homepage, https://github.com/AreebShahid07/vyntri
Project-URL: Source Code, https://github.com/AreebShahid07/vyntri
Project-URL: Bug Tracker, https://github.com/AreebShahid07/vyntri/issues
Keywords: image-classification,analytic-learning,few-shot,continual-learning,pretrained-features,cpu,machine-learning
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Education
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Scientific/Engineering :: Image Recognition
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.24.0
Requires-Dist: torch>=2.0.0
Requires-Dist: torchvision>=0.15.0
Requires-Dist: pillow>=10.0.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Dynamic: license-file

# Vyntri

**Image classification without a training loop.** Extract features from a frozen pretrained backbone, adapt them analytically, and fit a closed-form classifier -- in a few lines of Python.

```python
from vyntri import Vyntri
from vyntri.data import split

s = split("./my-dataset", train=0.7, test=0.2, seed=42)
model = Vyntri()
model.fit(train=s.train, val=s.val)
model.predict("./image.jpg")  # PredictionResult(path='./image.jpg', label='cats', confidence=...)
```

Runs on CPU. No gradient training by default. Useful defaults require little or no tuning.

---

## Table of Contents

- [Why Vyntri?](#why-vyntri)
- [Quick Start](#quick-start)
- [How It Works](#how-it-works)
- [After Fitting](#after-fitting)
- [Configuration](#configuration)
- [Backbones](#backbones)
- [Fine-Tuning](#fine-tuning)
- [API Reference](#api-reference)
- [Examples](#examples)
- [Installation](#installation)

---

## Why Vyntri?

| | Gradient fine-tuning | Vyntri |
|---|---|---|
| **Fitting** | Iterative optimization over many epochs | One feature-extraction pass plus closed-form solves |
| **Hardware** | GPU strongly recommended | CPU is sufficient for the analytic path |
| **Hyperparameters** | Learning rate, schedule, epochs, augmentation, ... | Few, with sensible defaults |
| **Adding data later** | Retrain | `update()` from sufficient statistics, no old raw features needed |

Vyntri replaces the training loop with analytic (closed-form) adaptation and classification on top of frozen pretrained features. Fitting cost is dominated by feature extraction, which is cached and reused. How well this works depends on how well the pretrained features suit your images; always check accuracy on a held-out test split.

---

## Quick Start

### 1. Prepare your dataset

Organize images into folders by class name:

```
my-dataset/
  cats/
    cat_001.jpg
    cat_002.jpg
  dogs/
    dog_001.jpg
  birds/
    bird_001.jpg
```

Each class needs enough images to appear in every split; more images per class generally give more reliable results.

### 2. Split, fit, and predict

```python
from vyntri import Vyntri
from vyntri.data import split

# Create an explicit train/val/test split (no files copied)
s = split("./my-dataset", train=0.7, test=0.2, seed=42)

model = Vyntri()
model.fit(train=s.train, val=s.val)

result = model.predict("./test-photo.jpg")
print(result.label)       # e.g. cats
print(result.confidence)  # value in [0, 1]
```

You can also pass a folder that already contains `train/`, `val/` and `test/` subfolders: `model.fit("./root")` trains on `train/` and validates on `val/`, and `model.evaluate("./root")` uses `test/`.

### 3. Evaluate on the held-out test set

```python
result = model.evaluate(s.test)
print(result.accuracy)    # overall accuracy in [0, 1]
print(result.macro_f1)    # macro-averaged F1
print(result.per_class)   # per-class precision/recall/F1
```

### 4. Save and reload

```python
model.save("./my-model.vyntri")
model = Vyntri.load("./my-model.vyntri")
model.predict("./new-image.jpg")
```

---

## How It Works

```
Image
  |
Pretrained backbone (frozen)    <- extracts features, no training
  |
Analytic adaptation              <- closed-form discriminative projection (FK by default)
  |
Shrinkage estimation             <- stabilizes the covariance estimate
  |
Analytic Ridge classifier        <- closed-form weights
  |
Prediction
```

Every step of the default pipeline is **analytic** -- solved in closed form rather than learned through gradient descent:

- **No training loop** -- no learning-rate schedules or epoch counts to tune
- **CPU-friendly** -- the solves are small dense matrix operations
- **Sensible defaults** -- few or no parameters to tune for common workflows
- **Designed for determinism** -- analytic fitting on fixed data and config produces consistent results

The pretrained backbone provides general visual features. The analytic path never modifies it -- it only fits the adaptation and classifier on top. Optional gradient fine-tuning is available separately (see [Fine-Tuning](#fine-tuning)).

---

## After Fitting

### Model info

```python
model.classes_           # ["birds", "cats", "dogs"]
model.class_to_idx_      # {"birds": 0, "cats": 1, "dogs": 2}
model.feature_dim_       # 576 (backbone feature dimension)
model.state              # "fitted", "updated", "fine_tuned", ...
```

### Predictions

```python
result = model.predict("./image.jpg")
result.label            # predicted class name
result.confidence       # value in [0, 1]
```

### Batch predictions

```python
results = model.predict_batch(["./img1.jpg", "./img2.jpg", "./img3.jpg"])
for path, label, conf in zip(results.paths, results.labels, results.confidences):
    print(f"{path}: {label} ({conf:.1%})")
```

`predict_batch()` also accepts a folder of images and an optional `out_path` (`.csv` or `.json`).

### Inspect internals

```python
model.config             # Current configuration
model.fitted_config      # Config that produced this fit
model.projection_        # Fitted adaptation object (e.g. FKProjection)
model.classifier_        # Fitted AnalyticRidge classifier
model.validation_accuracy_   # None when fit without validation data
```

---

## Configuration

```python
from vyntri import Vyntri, Config
from vyntri.data import split

# All parameters can be passed directly as kwargs
model = Vyntri(
    backbone="auto",
    adaptation="fk",
    shrinkage="diagonal",
    cache_dir="./vyntri-cache",
)

s = split("./dataset", train=0.7, test=0.2, seed=42)
model.fit(train=s.train, val=s.val)
```

```python
Config.describe()  # Returns structured docs for all parameters
```

### Key configuration groups

| Group | Options | What they control |
|---|---|---|
| **Backbone** | backbone, candidates, input_size | Feature extraction model, auto-selection subset, crop size |
| **Adaptation** | adaptation, shrinkage, shrinkage_alpha, projection_dim, eigenvalue_floor, floor_ratio | Discriminative projection and covariance shrinkage |
| **Classifier** | regularization | Ridge regularization strength |
| **Runtime** | device, dtype, batch_size, num_workers, seed | Execution and determinism |
| **Cache** | cache_dir, cache_enabled | Feature caching |

See [docs/api.md](docs/api.md) for every field and its default.

---

## Backbones

Vyntri supports five torchvision backbones (ImageNet weights are downloaded on first use):

| Backbone | Feature dim | Notes |
|---|---|---|
| mobilenet_v3_small | 576 | Default, smallest and fastest |
| resnet18 | 512 | |
| resnet50 | 2048 | |
| efficientnet_b0 | 1280 | |
| convnext_tiny | 768 | |

```python
from vyntri import Vyntri
from vyntri.data import split

s = split("./dataset", train=0.7, test=0.2, seed=42)

# Use a specific backbone
model = Vyntri(backbone="efficientnet_b0")
model.fit(train=s.train, val=s.val)

# Or let Vyntri auto-select from a subset (requires validation data)
model = Vyntri(
    backbone="auto",
    candidates=["resnet18", "efficientnet_b0", "convnext_tiny"],
)
model.fit(train=s.train, val=s.val)
print(f"Selected: {model.backbone_name_}")
```

Auto-selection scores candidates with LogME on frozen features, validates the top candidates on the validation split, and never looks at the test split.

---

## Fine-Tuning

Optional gradient fine-tuning, for when the analytic fit is not accurate enough on your domain:

```python
from vyntri import Vyntri
from vyntri.data import split

s = split("./dataset", train=0.7, test=0.2, seed=42)
model = Vyntri(backbone="resnet50")
model.fit(train=s.train, val=s.val)
model.fine_tune(s, epochs=10, lr=1e-3, scope="last_layer")
print(model.evaluate(s.test).accuracy)
```

`fine_tune()` needs validation data for checkpoint selection: pass a `SplitResult` that has a validation subset, or a folder with `train/` and `val/`.

| Scope | What unfreezes | Notes |
|---|---|---|
| last_layer | New linear head only | Default -- cheapest |
| last_block | Head + the backbone's last feature block | More capacity, more compute |
| full | Head + the entire backbone | Most expensive; easiest to overfit on small datasets |

**Note:** `last_layer` is practical on CPU for small datasets; deeper scopes are much faster on a GPU.

---

## API Reference

| Method | Description |
|---|---|
| `vyntri.data.split(path, train, val, test, seed)` | Create explicit train/val/test subsets of a folder-per-class dataset |
| `Vyntri(**kwargs)` | Create model instance |
| `model.fit(train, val=None, ...)` | Fit on a dataset (FolderDataset, Path, or str) |
| `model.predict(image)` | Classify a single image |
| `model.predict_batch(images)` | Classify a folder or list of images |
| `model.evaluate(dataset)` | Evaluate on a test set (path or FolderDataset) |
| `model.save(path)` / `Vyntri.load(path)` | Serialize/deserialize |
| `model.fine_tune(dataset, scope, epochs, lr)` | Optional fine-tuning (SplitResult with val, or a path with `train/` and `val/`) |
| `model.update(dataset)` | Add new data/classes (FolderDataset, Path, or str) |
| `model.analyze(dataset)` | Inspect a dataset without fitting |
| `model.select_backbone(dataset)` | Rank backbones on a folder with `train/` and `val/` |
| `model.clear_cache()` | Remove cached features |

| Property | Description |
|---|---|
| `model.classes_` | Class names list |
| `model.class_to_idx_` | Class to index mapping |
| `model.state` | Current model state |
| `model.config` | Current configuration |
| `model.fitted_config` | Config used for the last fit |
| `model.feature_dim_` | Backbone feature dimension |
| `model.validation_accuracy_` | Validation accuracy from fit (`None` without validation data) |

Full reference: [docs/api.md](docs/api.md).

---

## Examples

Runnable scripts live in [`examples/`](examples/) and Jupyter walkthroughs in [`notebooks/`](notebooks/).

### Image classification

```python
from vyntri import Vyntri
from vyntri.data import split

s = split("./flowers", train=0.7, test=0.2, seed=42)
model = Vyntri()
model.fit(train=s.train, val=s.val)
print(model.classes_)  # e.g. ["daisy", "rose", "sunflower", "tulip"]

result = model.predict("./test-rose.jpg")
print(result.label, result.confidence)
```

### Incremental learning

```python
from vyntri import Vyntri
from vyntri.data import split
from vyntri.data.dataset import FolderDataset

s = split("./dataset-v1", train=0.7, test=0.2, seed=42)
model = Vyntri()
model.fit(train=s.train, val=s.val)

# update() accepts FolderDataset, Path, or string
new_data = FolderDataset("./dataset-v2")
model.update(new_data)  # Adds new images and classes without retaining old raw features
```

### Comparing backbones

```python
from vyntri import Vyntri
from vyntri.data import split

s = split("./dataset", train=0.7, test=0.2, seed=42)
for name, bb in [("mobile", "mobilenet_v3_small"), ("resnet", "resnet50")]:
    model = Vyntri(backbone=bb)
    model.fit(train=s.train, val=s.val)
    print(name, model.validation_accuracy_)
```

---

## Installation

```bash
pip install vyntri
```

**Requirements:** Python 3.9+, PyTorch, torchvision

**Optional for deeper fine-tuning scopes:** CUDA-capable GPU

---

## Migration notes

### v1.5.1: Patch release

No public API changes; upgrading from v1.5.0 needs no code changes.

- **Fix:** a scheduled `fit()` (`target_accuracy=` / `max_time_seconds=`) no longer crashes in the `refine_last_layer` stage when validation features come from the feature cache.
- The "explicit split has no `val/` folder" error now points to `vyntri.data.split()`.
- Documentation, examples, notebooks, and the benchmark script updated to match the current API.

### v1.5.0: Backbone expansion and API cleanup

- **New backbones:** `efficientnet_b0` (1280-d) and `convnext_tiny` (768-d)
- **`candidates` parameter:** control which backbones `auto` evaluates
- **`whitening=` removed:** use `adaptation=` only
- **`val_fraction` removed:** use `vyntri.data.split()` for explicit roles
- **Result objects now print nicely:** `print(result)` gives readable output

```python
# v1.4.0: auto-selection over all registered backbones (still works)
model = Vyntri(backbone="auto")
model.fit(train=s.train, val=s.val)

# v1.5.0: optionally restrict the candidates
model = Vyntri(
    backbone="auto",
    candidates=["resnet18", "efficientnet_b0", "convnext_tiny"],
)
model.fit(train=s.train, val=s.val)
print(model.evaluate(s.test))  # Human-readable output
```

### v1.4.0: Explicit dataset roles and adaptation

`fit()` takes a training dataset and an optional `val=` dataset. `SplitResult` is no longer accepted directly — pass `s.train` and `val=s.val`.

### v1.3.0: API consistency and stability

- `update()`, `fine_tune()`, and `analyze()` accept `FolderDataset`, `Path`, or strings (`fine_tune()` additionally needs validation data).
- `save()`/`load()` preserves training history and class registry.
- `loaded.state` reflects the pre-save state (`"fitted"`, `"updated"`, or `"fine_tuned"`).
- Scheduled fit with no validation set no longer crashes.
- Corrupt images raise `DatasetError` instead of raw PIL tracebacks.

### v1.2.0: Explicit dataset splitting

`vyntri.data.split()` replaces implicit automatic splitting.

---

## License

MIT -- see [LICENSE](LICENSE).
