Skip to content

About

TensorForge is a framework for compressing pretrained deep learning models using decomposition techniques to reduce model size and computational complexity while maintaining performance.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

TensorForge logo: a hammer forging a tensor on an anvil

TensorForge

Label-free low-rank compression of pretrained vision backbones.

License: MIT

TensorForge makes a pretrained torchvision backbone (ResNet, ResNeXt, RegNet, ConvNeXt, Swin, ViT) smaller without labels and without a task head. You give it a backbone, unlabelled images from your domain, and how close the compressed backbone's embedding must stay to the original's. TensorForge replaces layers with low-rank factorisations, chooses how much to compress each layer, recovers quality by distilling the original's feature maps, and returns the smallest backbone that still meets your thresholds: the same architecture with some layers swapped for smaller blocks, ready for any head you attach to it.

Results

From the technical report (torchvision pretrained weights, default thresholds, one A100 per run), which has the full results on four datasets, the method, ablations and compression–accuracy curves:

ResNet-50 on ImageNet 1.62× fewer parameters (23.5 M → 14.5 M) for −1.36 points of top-1 (80.91% → 79.55%)
Nine backbones on ImageNet 1.15–2.69× fewer parameters (up to 2.91× fewer FLOPs) for 0.4–2.2 points of top-1
Wide ResNet-50-2 on CIFAR-100 4.95× fewer parameters (66.8 M → 13.5 M)
Every sweep run 216 / 216 runs meet their thresholds on held-out test images (ImageNet, CIFAR-100, COCO, BDD100K)

Top-1 is measured with each model's own classifier, which TensorForge never sees.

How it works

  1. Calibrate. Each candidate layer's input covariance is measured on 512 train images.
  2. Scan. Each layer is decomposed on its own at several ratios, and the damage to the pooled embedding is measured.
  3. Search. A greedy plan picks per-layer ratios within a damage budget; each candidate is built, distilled and evaluated, and a binary search on the budget finds the smallest backbone that passes.
  4. Finish. The best candidate is distilled further, reported on the test split and saved.

Details:

  • Decomposition. Linear layers and 1×1 convs → truncated SVD (two smaller linear layers / 1×1 convs); k×k convs → Tucker-2 / HOSVD (1×1 → smaller k×k → 1×1). Tucker-2 has two candidates: input and output ranks chosen separately (smallest HOSVD error bound within the layer's parameter budget) or one shared rank. The scan measures both and keeps the less damaging one for each layer and ratio.
  • Whitened (data-aware) by default. The factors are fitted to the layer's outputs on real data rather than to its weights (the exact optimum for linear layers and 1×1 convs). On pretrained ResNet-18 this cut the average per-layer damage before distillation 3× at 2× compression and 4× at 4×.
  • Distillation trains only the decomposed blocks to match the original's stage outputs (layer1–layer4 in ResNets), with a warm-up + cosine learning-rate schedule. No labels are used; all other layers stay frozen and the model stays in eval mode (frozen BatchNorm, no stochastic depth).
  • Quality is measured against the original backbone, not a downstream task: linear CKA and kNN-neighbourhood overlap (enforced), plus cosine similarity and relative MSE (reported).
  • Honest evaluation. All selection uses a val split; the test split is touched only by the final report, so its numbers are not biased by the search.

Supported backbones

torchvision weights; tensorforge --help lists the exact names.

Family Models
ResNet resnet18/34/50/101/152, wide_resnet50_2, wide_resnet101_2
ResNeXt resnext50_32x4d, resnext101_32x8d, resnext101_64x4d
RegNet regnet_x_* and regnet_y_*, from 400mf to 32gf
ConvNeXt convnext_tiny/small/base/large
Swin (MLPs only) swin_t, swin_s, swin_b
ViT (MLPs only) vit_b_16, vit_b_32, vit_l_16, vit_l_32 (224×224 input only)

Dense convs and linear layers are decomposed (in ConvNeXt, 91% of the parameters are in the pointwise linear layers). Grouped and depthwise convs (the 3×3s in ResNeXt and RegNet, the 7×7s in ConvNeXt) are left as they are; they hold few parameters (6% of resnext50_32x4d, 1% of convnext_tiny).

In Swin and ViT only the MLPs (and Swin's patch merging) are decomposed, about two thirds of the weights. The attention projections are left as they are: the attention modules pass their weights (qkv.weight, in_proj_weight) straight to a fused kernel instead of calling the layers, so a replacement would never be used. ViT has no stages, so every encoder layer is distilled. swin_v2_* (trained at 256×256) and vit_h_14 (518×518) are not included.

Another family can be added with an ArchSpec in tensorforge/archs.py (the names of its classifier, its stages and its stem).

Scope. The output is a backbone with its classifier removed: attach and train your own head. How well a head trained on top performs (especially for detection) is not measured here.

Installation

Requires Python ≥ 3.14, PyTorch ≥ 2.14 and torchvision ≥ 0.29.

git clone https://github.com/muratonuryildirim/TensorForge.git
cd TensorForge

With conda (creates an environment tensorforge with Python 3.14, PyTorch for CUDA 13.0, and TensorForge in editable mode with the dev tools):

conda env create -f environment.yml
conda activate tensorforge
python -c "import torch; print(torch.cuda.is_available())"

Or with pip, in an existing environment. Install PyTorch from its own index first for a CUDA build (.../whl/cpu for a CPU-only one):

pip install torch torchvision --index-url https://download.pytorch.org/whl/cu130
pip install -e .                 # or -e ".[dev]" for the test tools, ".[cars]" for --dataset stanfordcars

Either way you get a tensorforge command, equivalent to python -m tensorforge.

Quick start

Check the setup first. This runs the library end to end on a pretrained ResNet-18 with small splits (a few minutes on a GPU, after a ~170 MB CIFAR-100 download into ./data):

python smoke_test.py

Then compress:

tensorforge --arch resnet50                      # full run on CIFAR-100
tensorforge --arch resnet18 --scan-images 300 --search-iters 2 --distill-steps 50 --final-steps 100   # quick run, small GPU

The run writes the compressed backbone and its report (see Outputs). If no backbone passes the thresholds, only the sensitivity scan is saved (and reused by the next run), and the log suggests what to loosen.

Data

Choose the dataset with --dataset, --data-root and --data-dir. When they are not given, they default to the DATASET, DATA_ROOT and DATA_DIR environment variables (handy on a cluster).

--dataset Notes
cifar100 (default) Downloads automatically (~170 MB) into --data-root (default ./data). The download server can be slow.
stanfordcars Download manually into --data-root (torchvision can no longer fetch it); needs scipy.
folder Your own data: <data-dir>/train and <data-dir>/test, each a labelled ImageFolder.
coco COCO 2017: <data-dir>/train2017, <data-dir>/val2017 and <data-dir>/annotations/instances_{train,val}2017.json (the official layout; symbolic links are enough).
bdd100k BDD100K driving images: <data-dir>/images/100k/{train,val} and <data-dir>/labels/bdd100k_labels_images_{train,val}.json (the official layout). Each image's label is one tag: --bdd-tag scene (default), timeofday or weather.

How each split is used:

Split Used for
train (minus val) distillation (augmented); the first 512 images, without augmentation, give the whitening covariances
val: --n-val = 5,000 images held out from train sensitivity scan, budget search, every pass/fail decision
test: a fixed subset of --n-eval = 5,000 images the final report only

With --val-from-test the val images are instead a fixed random subset of the test split (--n-val of them, at most half), disjoint from the test images kept for the report, and every train image is used for distillation. Use it for data the pretrained model was trained on, such as ImageNet: held-out train images are images it has seen, on which a compressed backbone looks better than on new ones (on ImageNet, ViT-B/16 passed CKA 0.95 on held-out train images but reached 0.9496 on the val set).

Images are preprocessed the way the pretrained weights expect: their resize-before-crop ratio (e.g. 232 → 224 for ResNet-50, 256 → 224 for ResNet-18), interpolation (bicubic for Swin) and normalisation, scaled to --res.

Labels and the accuracy check

Labels are used only by the final report, never by the search. Its accuracy check is the kNN classification accuracy (knn_class): each test image is classified by a similarity-weighted vote of its --knn-k nearest neighbours among the other test images, and the prediction is correct if it is one of the image's labels. It is reported for the original and the compressed backbone, next to the accuracy of always predicting the most frequent label (majority). On ImageNet its drop follows the top-1 drop of the pretrained classifier closely (r = 0.95 over 54 runs). The report also gives precision@k (knn_precision): the share of each image's k nearest neighbours that have at least one of its labels, with its value for random neighbours (chance).

kNN accuracy needs well over k test images per class: 5,000 test images are plenty for CIFAR-100 (50 per class) but not for ImageNet (5 per class). For data with many classes use the whole test split (--n-eval none, e.g. all 50,000 ImageNet val images); the report records the median images per class and the log warns when it is not more than k.

ImageNet

Point --data-dir at a directory whose train/ and test/ are the ImageNet train and val class folders (symbolic links are enough), and add --top1 to measure top-1 accuracy with the pretrained classifier alongside the label-free metrics:

tensorforge --arch resnet50 --dataset folder --data-dir data/imagenet \
    --val-from-test --n-val 10000 --n-eval none --top1

This selects on 10,000 of the 50,000 val images and reports on the other 40,000.

COCO

COCO images show several objects, so there is no single label to classify by. With --dataset coco each image's label is its set of object categories (boxes and masks are not used, and nothing is trained): kNN accuracy counts a prediction as correct if the image contains the predicted category. Most val2017 images show a person, so always predicting "person" is already right on about half of them (majority). Selection uses held-out train2017 images, which ImageNet-pretrained backbones have not seen, and the report uses all 5,000 val2017 images:

tensorforge --arch resnet50 --dataset coco --data-dir data/coco

BDD100K

BDD100K images are dashcam frames; nearly all of them show a car, so object categories say little. Its image-level tags do: with --dataset bdd100k the label is one of them (--bdd-tag: scene, timeofday or weather), and images tagged "undefined" are left out of the label-based measures. Selection uses 5,000 held-out train images and the report 5,000 of the val images. Keep the two sets the same size: kNN overlap depends on how many images it is measured on (on BDD100K the same backbone reaches 0.73 on 5,000 images and 0.70 on 10,000), so a test split larger than the selection split makes the test pass/fail stricter than the search's:

tensorforge --arch resnet50 --dataset bdd100k --data-dir data/bdd100k

Options

Main options (tensorforge --help lists all of them):

Option Default Meaning
--arch resnet50 backbone to compress
--objective params what to minimise: params (model size; mostly compresses late layers) or flops (compute per image; shifts compression toward early, high-resolution layers)
--ratios 1.5 2 3 4 6 per-layer compression ratios to consider
--search-iters 8 budget-search iterations (each builds, distills and evaluates a candidate)
--target 0 stop once this overall reduction of the objective passes (0 = find the smallest passing backbone)
--distill-steps / --final-steps 2000 / 5000 distillation steps per search candidate / further steps for the final backbone (it continues from the chosen candidate)
--amp off mixed-precision distillation on GPU (bfloat16 where supported, e.g. A100/H100, else float16 with loss scaling)
--top1 off also measure top-1 accuracy with the original classifier, for every search candidate (val) and the final backbone (test). Only for data labelled with the classifier's classes, e.g. ImageNet in torchvision order; measured only, never a constraint
--no-whiten off plain SVD / Tucker-2 on the weights instead of whitened decomposition
--calib-images / --damp 512 / 0.01 train images for the input covariances / whitening damping
--methods svd tucker2 tucker2_equal candidate methods; the scan keeps the least damaging per layer and ratio (svd: Linear and 1×1 convs; tucker2: separate input/output ranks, tucker2_equal: one shared rank, both for k×k convs)
--min-cka / --min-knn-overlap 0.95 / 0.70 enforced quality thresholds (none = measure only)
--min-cos / --max-rel-mse none optional extra thresholds on cosine similarity / relative MSE
--res 224 input resolution (crop size and FLOP counting)
--workers / --device / --seed 4 / auto / 0 data-loader processes / cuda or cpu / random seed
--no-cache-val off read the val split from disk on every pass instead of loading it into memory once (uses ~0.6 MB of RAM per image at 224 px: 3 GB for the default 5,000; the scan is many times faster with it)

The default thresholds are starting values; calibrate them for your use.

Choosing the objective. Fewer parameters means a smaller model; fewer FLOPs means less compute per image. They differ because late ResNet stages hold most parameters but run on small feature maps, while early stages are cheap in parameters but expensive in compute. FLOPs are counted at --res (224×224 by default), but every feature map scales together with the input, so the FLOPs plan is nearly the same at any input resolution. Neither is a measured latency: on a GPU, a decomposed block (two or three convs) can run slower than the original conv at mild ratios, so time the result on the target hardware (benchmarks/latency.py).

Outputs

For --arch resnet50 (change the prefix with --out):

File Contents
resnet50_compressed.pt the compressed backbone: weights plus the layout of each decomposed layer; load with load_compressed
resnet50_report.json test-split quality (CKA, kNN overlap, kNN classification accuracy original vs compressed, cos, rel MSE; with --top1 also top-1 original vs compressed), params and GFLOPs original vs compressed, per-layer log
resnet50_plan.json the chosen per-layer ratios and methods, every search candidate with its val metrics (search), the final backbone's val metrics (final_val) and the run's full Config
resnet50_sensitivity.json the sensitivity scan; reused by later runs with the same settings

Using the compressed backbone

The .pt file holds only weights and a description of each decomposed layer (no pickled code), so it loads with PyTorch's safe default torch.load(..., weights_only=True). load_compressed rebuilds the architecture from torchvision (no pretrained download) and loads the weights:

from tensorforge import load_compressed
backbone = load_compressed("resnet50_compressed.pt", device="cuda")  # images -> pooled embedding [B, C]

# Stage feature maps, e.g. for a detector (ResNet stage names; RegNet: trunk_output.block1..4;
# ConvNeXt and Swin: features.1, .3, .5, .7 - Swin's are channels-last):
from torchvision.models.feature_extraction import create_feature_extractor
fx = create_feature_extractor(backbone, return_nodes={"layer1": "c2", "layer2": "c3",
                                                      "layer3": "c4", "layer4": "c5"})

Python API

The settings of a run are a tensorforge.Config, and each pipeline step is a library function, so you can also compress layers by hand:

from tensorforge import (Config, decompose, distill_features, embed, evaluate, load_backbone, make_splits,
                    replace_layer)

cfg = Config(arch="resnet18", dataset="folder", data_dir="/data/mydata", n_val=2000)
splits = make_splits(cfg)                              # {"train", "calib", "val", "test"}

original = load_backbone(cfg.arch)                     # frozen: the reference, never modified
work = original.clone()
block, method, _ = decompose(work.model.get_submodule("layer4.1.conv2"), ratio=2.0)
replace_layer(work, "layer4.1.conv2", block, method)   # raises DecompositionError if refused
distill_features(work, original, splits["train"], steps=300)

reference = embed(original, splits["val"])             # compute once, reuse for every candidate
print(evaluate(work, reference, splits["val"]))        # cka, knn_overlap, ..., all_pass

On a SLURM cluster

run_compress.sh runs one job on one A100. It was written for Snellius: adapt the #SBATCH lines, module load and CONDA_SH to your cluster. It activates the conda environment of environment.yml (CONDA_ENV, default tensorforge), writes the outputs to results/<NAME>_* and the log next to them, and the job's exit status is TensorForge's, so a crash shows as FAILED in sacct. Submit from the checkout. Compute nodes usually have no internet access, so download the data and the pretrained weights on a login node first:

python -c "import torchvision; torchvision.datasets.CIFAR100('data', download=True)"
python -c "from tensorforge import load_backbone; load_backbone('resnet50', device='cpu')"   # caches the weights
mkdir -p results && sbatch run_compress.sh                                           # resnet50, CIFAR-100
mkdir -p results/test && sbatch -J test/r18 --export=ALL,NAME=test/r18,ARGS="--arch resnet18 --amp" run_compress.sh

Two scripts submit the runs of the technical report with run_compress.sh, for cifar100, imagenet, coco or bdd100k (ImageNet: selection on 10,000 val images, report on the other 40,000, with top-1):

  • run_sweep.sh: the backbone sweeps. Nine backbones × both objectives × three split seeds (54 jobs, --amp), into results/sweep_<dataset>/.
  • run_curves.sh: the compression-accuracy curves. The same nine backbones at five constraint strictness levels s (CKA ≥ 1 − 0.05 s, kNN overlap ≥ 1 − 0.30 s; s = 1 is the default and comes from the sweep), into results/curves_<dataset>/. ARCHS and STRICTNESS select a subset.
./run_sweep.sh cifar100                  # results/sweep_cifar100/
./run_sweep.sh imagenet                  # needs data/imagenet/{train,test}
./run_curves.sh coco                     # needs data/coco (official COCO 2017 layout)
DRY_RUN=1 ./run_sweep.sh imagenet        # print the sbatch commands only

Benchmarks and run summaries

# One table of finished runs (every *_report.json under the given directories), e.g. after SLURM jobs:
python benchmarks/summarize.py results/ --csv results/summary.csv
# Measured inference time and memory of every *_compressed.pt under the given directories against the
# original backbone, on the GPU (fp32 / bf16, batch 1 / 64) and the CPU (1 and 4 threads); needs a GPU:
python benchmarks/latency.py results/sweep_imagenet --split 0 --out results/latency/latency.jsonl
# Damage per layer and for the whole model, plain vs whitened, shared vs separate Tucker-2 ranks,
# before distillation (section 10.1 of the technical report):
python benchmarks/decomposition.py --arch resnet18 --data-root data
# Compression-accuracy curves from run_curves.sh and sweep runs; --svg redraws the technical report's figures:
python benchmarks/curves.py ImageNet=results/curves_imagenet,results/sweep_imagenet --svg docs/figures

Development

The unit tests need no downloads (random weights, fake images). They run on GitHub on every push and pull request, with lint and type checks:

pip install -e ".[dev]"
pytest -m "not slow"     # about a minute on CPU
pytest                   # everything, including a structure check of every supported model: about two minutes
ruff check . && mypy tensorforge

Repository layout

Path Role
tensorforge/cli.py the pipeline (tensorforge, python -m tensorforge): calibration → sensitivity scan → budget search → final distillation, report and save
tensorforge/archs.py ArchSpec per architecture family (classifier, stages, stem, excluded attention modules); SUPPORTED_ARCHS
tensorforge/config.py Config: every setting of a run; DEFAULT_CONSTRAINTS
tensorforge/data.py train / val / test splits; cache_images holds a split in memory
tensorforge/models.py Backbone, load_backbone, list_layers, replace_layer, params and FLOPs
tensorforge/decomposition.py whitened SVD (Linear, 1×1 conv) / Tucker-2 (k×k conv) decomposition and input covariances
tensorforge/metrics.py embed, evaluate: CKA, kNN overlap, cosine, relative MSE; constraint checks and damage
tensorforge/distill.py feature distillation of the decomposed blocks
tensorforge/ratio_search.py sensitivity scan, greedy plan, budget search
tensorforge/report.py final report on the test split
tensorforge/io.py save_backbone / load_compressed
tests/ unit tests (pytest): decomposition maths, guards, data splits, save/reload, metrics, planning, config and CLI, every supported architecture
smoke_test.py end-to-end check on a pretrained ResNet-18 and real data
benchmarks/summarize.py one table (or CSV) of finished runs
benchmarks/latency.py measured GPU and CPU inference time and memory, original vs compressed
benchmarks/decomposition.py per-layer and whole-model damage before distillation
benchmarks/curves.py compression-accuracy curves; redraws the technical report's figures
benchmarks/add_label_agreement.py adds the label-based measures to the reports of finished runs, without re-running them
run_compress.sh SLURM job script: one compression run
run_sweep.sh / run_curves.sh submit the reported backbone sweeps / compression-accuracy curves
docs/technical-report.md the technical report: method, results on four datasets, ablations, curves
docs/figures/ the report's figures, drawn by benchmarks/curves.py --svg
environment.yml conda environment (Python 3.14, PyTorch for CUDA 13.0, TensorForge editable)
pyproject.toml package metadata and dependencies; pytest, ruff and mypy settings
logo.png project logo

License

MIT © 2026 M. Onur Yildirim

About

TensorForge is a framework for compressing pretrained deep learning models using decomposition techniques to reduce model size and computational complexity while maintaining performance.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages