Metadata-Version: 2.4
Name: autotimm
Version: 0.6.2
Summary: Automatic Pytorch Image Models
Author: Krishnatheja Vanka
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright [yyyy] [name of copyright owner]
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
        
Project-URL: Homepage, https://github.com/theja-vanka/AutoTimm
Project-URL: Repository, https://github.com/theja-vanka/AutoTimm
Project-URL: Issues, https://github.com/theja-vanka/AutoTimm/issues
Keywords: deep-learning,computer-vision,pytorch,timm,automation,huggingface_hub,torchvision,torchmetrics
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: torch>=2.0
Requires-Dist: torchvision>=0.15
Requires-Dist: timm>=1.0
Requires-Dist: pytorch-lightning>=2.0
Requires-Dist: torchmetrics>=1.0
Requires-Dist: numpy>=1.23
Requires-Dist: opencv-python-headless>=4.8
Requires-Dist: huggingface_hub>=0.20
Requires-Dist: watermark>=2.3
Requires-Dist: rich>=13.0
Requires-Dist: albumentations>=1.3
Requires-Dist: pycocotools>=2.0
Provides-Extra: tensorboard
Requires-Dist: tensorboard>=2.14; extra == "tensorboard"
Provides-Extra: mlflow
Requires-Dist: mlflow>=2.0; extra == "mlflow"
Provides-Extra: wandb
Requires-Dist: wandb>=0.15; extra == "wandb"
Provides-Extra: all
Requires-Dist: tensorboard>=2.14; extra == "all"
Requires-Dist: mlflow>=2.0; extra == "all"
Requires-Dist: wandb>=0.15; extra == "all"
Requires-Dist: albumentations>=1.3; extra == "all"
Requires-Dist: opencv-python-headless>=4.8; extra == "all"
Requires-Dist: pycocotools>=2.0; extra == "all"
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-cov; extra == "dev"
Requires-Dist: build; extra == "dev"
Requires-Dist: twine; extra == "dev"
Requires-Dist: ruff; extra == "dev"
Requires-Dist: black; extra == "dev"
Requires-Dist: pycocotools>=2.0; extra == "dev"
Provides-Extra: docs
Requires-Dist: mkdocs>=1.5; extra == "docs"
Requires-Dist: mkdocs-material>=9.0; extra == "docs"
Requires-Dist: mkdocstrings[python]>=0.24; extra == "docs"
Dynamic: license-file

<p align="center">
  <img src="https://drive.google.com/uc?export=view&id=1IO383lY97phOg9qDVARnG9HQ2McOF7Zj" alt="AutoTimm" width="400">
</p>

<p align="center">
  <strong>Train state-of-the-art vision models with minimal code</strong>
</p>

<p align="center">
  <a href="https://pypi.org/project/autotimm/"><img src="https://img.shields.io/pypi/v/autotimm?color=blue&logo=pypi&logoColor=white" alt="PyPI"></a>
  <a href="https://pypi.org/project/autotimm/"><img src="https://img.shields.io/pypi/pyversions/autotimm?logo=python&logoColor=white" alt="Python"></a>
  <a href="https://github.com/theja-vanka/AutoTimm/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-Apache%202.0-green" alt="License"></a>
  <a href="https://github.com/theja-vanka/AutoTimm/stargazers"><img src="https://img.shields.io/github/stars/theja-vanka/AutoTimm?style=social" alt="Stars"></a>
</p>

<p align="center">
  <a href="https://theja-vanka.github.io/AutoTimm/">Documentation</a> •
  <a href="https://theja-vanka.github.io/AutoTimm/getting-started/quickstart/">Quick Start</a> •
  <a href="https://theja-vanka.github.io/AutoTimm/examples/">Examples</a> •
  <a href="https://theja-vanka.github.io/AutoTimm/api/">API Reference</a>
</p>

---

AutoTimm combines the power of [timm](https://github.com/huggingface/pytorch-image-models) (1000+ pretrained models) with [PyTorch Lightning](https://github.com/Lightning-AI/pytorch-lightning) for a seamless training experience. Train image classifiers, object detectors, and segmentation models with any timm backbone. Go from idea to trained model in minutes, not hours.

## Highlights

| | |
|---|---|
| **4 Vision Tasks** | Classification, Object Detection, Semantic Segmentation, Instance Segmentation |
| **1000+ Backbones** | Access ResNet, EfficientNet, ViT, ConvNeXt, Swin, and more from timm |
| **Hugging Face Hub** | Load timm-compatible models directly from HF Hub with `hf-hub:` prefix |
| **HF Transformers** | Direct integration with HuggingFace Transformers vision models (ViT, DeiT, BEiT, Swin) |
| **AutoTrainer Compatible** | All HF models work with AutoTrainer (checkpointing, tuning, multi-logger, etc.) |
| **Advanced Architectures** | DeepLabV3+, FCOS, Mask R-CNN style heads with feature pyramids |
| **Explicit Metrics** | Configure exactly what you track with MetricManager and torchmetrics |
| **Multi-Logger Support** | TensorBoard, MLflow, Weights & Biases, CSV — use them all at once |
| **Auto-Tuning** | Automatic learning rate and batch size finding before training |
| **Preset Manager** | Smart backend selection (torchvision vs albumentations) based on your task |
| **TransformConfig** | Unified transform configuration with presets and model-specific normalization |
| **Flexible Transforms** | Torchvision (PIL) and Albumentations (OpenCV) — both included by default |
| **Production Ready** | Mixed precision, multi-GPU, gradient accumulation out of the box |

## Installation

```bash
pip install autotimm
```

**Includes:** PyTorch, timm, PyTorch Lightning, torchmetrics, albumentations, pycocotools, and more.

<details>
<summary><strong>Optional extras for logging</strong></summary>

```bash
# Logger backends (optional)
pip install autotimm[tensorboard]  # TensorBoard logging
pip install autotimm[wandb]        # Weights & Biases
pip install autotimm[mlflow]       # MLflow tracking

# All optional extras
pip install autotimm[all]

# Development
git clone https://github.com/theja-vanka/AutoTimm.git
cd AutoTimm
pip install -e ".[dev,all]"
```

</details>

## Quick Start

### Image Classification

```python
from autotimm import AutoTrainer, ImageClassifier, ImageDataModule, MetricConfig

# Data
data = ImageDataModule(
    data_dir="./data",
    dataset_name="CIFAR10",
    image_size=224,
    batch_size=64,
)

# Metrics
metrics = [
    MetricConfig(
        name="accuracy",
        backend="torchmetrics",
        metric_class="Accuracy",
        params={"task": "multiclass"},
        stages=["train", "val", "test"],
        prog_bar=True,
    ),
]

# Model & Train
model = ImageClassifier(
    backbone="resnet18",
    num_classes=10,
    metrics=metrics,
    lr=1e-3,
)

trainer = AutoTrainer(max_epochs=10)
trainer.fit(model, datamodule=data)
```

### Semantic Segmentation

```python
from autotimm import SemanticSegmentor, SegmentationDataModule, MetricConfig

# Data
data = SegmentationDataModule(
    data_dir="./cityscapes",
    format="cityscapes",  # or "png", "coco", "voc"
    image_size=512,
    batch_size=8,
)

# Metrics
metrics = [
    MetricConfig(
        name="iou",
        backend="torchmetrics",
        metric_class="JaccardIndex",
        params={
            "task": "multiclass",
            "num_classes": 19,
            "average": "macro",
            "ignore_index": 255,
        },
        stages=["val", "test"],
        prog_bar=True,
    ),
]

# Model & Train
model = SemanticSegmentor(
    backbone="resnet50",
    num_classes=19,
    head_type="deeplabv3plus",  # or "fcn"
    loss_type="combined",        # CE + Dice
    dice_weight=1.0,
    metrics=metrics,
)

trainer = AutoTrainer(max_epochs=100)
trainer.fit(model, datamodule=data)
```

### Object Detection

```python
from autotimm import ObjectDetector, DetectionDataModule, MetricConfig

# Data
data = DetectionDataModule(
    data_dir="./coco",
    image_size=640,
    batch_size=4,
)

# Metrics
metrics = [
    MetricConfig(
        name="mAP",
        backend="torchmetrics",
        metric_class="MeanAveragePrecision",
        params={"box_format": "xyxy", "iou_type": "bbox"},
        stages=["val", "test"],
        prog_bar=True,
    ),
]

# Model & Train
model = ObjectDetector(
    backbone="resnet50",
    num_classes=80,
    metrics=metrics,
)

trainer = AutoTrainer(max_epochs=100)
trainer.fit(model, datamodule=data)
```

### Instance Segmentation

```python
from autotimm import InstanceSegmentor, InstanceSegmentationDataModule, MetricConfig

# Data
data = InstanceSegmentationDataModule(
    data_dir="./coco",
    image_size=640,
    batch_size=4,
)

# Metrics
metrics = [
    MetricConfig(
        name="mask_mAP",
        backend="torchmetrics",
        metric_class="MeanAveragePrecision",
        params={"box_format": "xyxy", "iou_type": "segm"},
        stages=["val", "test"],
        prog_bar=True,
    ),
]

# Model & Train
model = InstanceSegmentor(
    backbone="resnet50",
    num_classes=80,
    mask_loss_weight=1.0,
    metrics=metrics,
)

trainer = AutoTrainer(max_epochs=100)
trainer.fit(model, datamodule=data)
```

**[See the full documentation for more examples and features →](https://theja-vanka.github.io/AutoTimm/)**

## Import Styles

AutoTimm supports flexible import styles for convenience:

```python
# Direct imports
from autotimm import SemanticSegmentor, DiceLoss, MetricConfig

# Submodule aliases (NEW!)
from autotimm.task import SemanticSegmentor, InstanceSegmentor
from autotimm.loss import DiceLoss, CombinedSegmentationLoss
from autotimm.metric import MetricConfig, MetricManager
from autotimm.head import DeepLabV3PlusHead, MaskHead

# Namespace access
import autotimm
model = autotimm.task.SemanticSegmentor(...)
loss = autotimm.loss.DiceLoss(...)

# TransformConfig for unified transform settings
from autotimm import TransformConfig, list_transform_presets
config = TransformConfig(preset="randaugment", image_size=384)

# Preset Manager for choosing the best backend (NEW!)
from autotimm import recommend_backend, compare_backends
rec = recommend_backend(task="detection")
config = rec.to_config(image_size=640)

# Original imports (still supported)
from autotimm.losses import DiceLoss
from autotimm.metrics import MetricConfig
from autotimm.tasks import SemanticSegmentor
```

## Supported Tasks & Architectures

### Classification
- **Models**: Any timm backbone (1000+ models)
- **Head**: Linear classification head with dropout
- **Losses**: CrossEntropy with label smoothing, Mixup support
- **Datasets**: Torchvision datasets, ImageFolder, custom loaders

### Object Detection
- **Architecture**: FCOS-style anchor-free detection
- **Components**: FPN, Detection Head (classification + bbox regression + centerness)
- **Losses**: Focal Loss, GIoU Loss, Centerness Loss
- **Datasets**: COCO format, custom annotations

### Semantic Segmentation
- **Architectures**: DeepLabV3+ (ASPP + decoder), FCN
- **Losses**: CrossEntropy, Dice, Focal, Combined (CE + Dice), Tversky
- **Datasets**: PNG masks, COCO stuff, Cityscapes, Pascal VOC
- **Metrics**: IoU (Jaccard Index), pixel accuracy, per-class metrics

### Instance Segmentation
- **Architecture**: FCOS detection + Mask R-CNN style mask head
- **Components**: FPN, Detection Head, Mask Head with ROI Align
- **Losses**: Detection losses + Binary mask loss
- **Datasets**: COCO instance segmentation format
- **Metrics**: Mask mAP, bbox mAP

## Examples

Ready-to-run scripts in the [`examples/`](examples/) directory:

| Example | Description |
|---------|-------------|
| [classify_cifar10.py](examples/classify_cifar10.py) | Basic classification with MetricManager and auto-tuning |
| [classify_custom_folder.py](examples/classify_custom_folder.py) | Train on your own dataset |
| [huggingface_hub_models.py](examples/huggingface_hub_models.py) | Using Hugging Face Hub models with AutoTimm |
| [hf_hub_*.py](examples/) | Comprehensive HF Hub integration examples (classification, detection, segmentation) |
| [object_detection_coco.py](examples/object_detection_coco.py) | FCOS-style object detection on COCO dataset |
| [object_detection_transformers.py](examples/object_detection_transformers.py) | Transformer-based detection (ViT, Swin, DeiT) |
| [object_detection_rtdetr.py](examples/object_detection_rtdetr.py) | RT-DETR end-to-end detection (no NMS required) |
| [semantic_segmentation.py](examples/semantic_segmentation.py) | DeepLabV3+ semantic segmentation |
| [instance_segmentation.py](examples/instance_segmentation.py) | Mask R-CNN style instance segmentation |
| [vit_finetuning.py](examples/vit_finetuning.py) | Two-phase Vision Transformer fine-tuning |
| [multi_gpu_training.py](examples/multi_gpu_training.py) | Distributed training with DDP |
| [mlflow_tracking.py](examples/mlflow_tracking.py) | Experiment tracking with MLflow |

**[Browse all examples →](https://theja-vanka.github.io/AutoTimm/examples/)**

## Documentation

| Section | Description |
|---------|-------------|
| [Quick Start](https://theja-vanka.github.io/AutoTimm/getting-started/quickstart/) | Get up and running in 5 minutes |
| [User Guide](https://theja-vanka.github.io/AutoTimm/user-guide/data-loading/) | In-depth guides for all features |
| [HF Integration Overview](https://theja-vanka.github.io/AutoTimm/user-guide/huggingface-integration-comparison/) | Compare HF Hub timm vs HF Transformers approaches |
| [HF Hub Integration](https://theja-vanka.github.io/AutoTimm/user-guide/huggingface-hub-integration/) | Using Hugging Face Hub models |
| [HF Transformers](https://theja-vanka.github.io/AutoTimm/user-guide/huggingface-transformers-integration/) | HuggingFace Transformers vision models with Lightning |
| [API Reference](https://theja-vanka.github.io/AutoTimm/api/) | Complete API documentation |
| [Examples](https://theja-vanka.github.io/AutoTimm/examples/) | Runnable code examples |

## Explore Backbones

```python
import autotimm

# Search 1000+ timm models
autotimm.list_backbones("*efficientnet*", pretrained_only=True)
autotimm.list_backbones("*vit*")

# Search Hugging Face Hub models
autotimm.list_hf_hub_backbones(model_name="resnet", limit=10)
autotimm.list_hf_hub_backbones(author="facebook", model_name="convnext")

# Inspect a model
backbone = autotimm.create_backbone("convnext_tiny")
print(f"Features: {backbone.num_features}, Params: {autotimm.count_parameters(backbone):,}")

# Use models from Hugging Face Hub
hf_backbone = autotimm.create_backbone("hf-hub:timm/resnet50.a1_in1k")
print(f"HF Hub model loaded: {hf_backbone.num_features} features")
```

## Hugging Face Hub Integration

AutoTimm seamlessly integrates with Hugging Face Hub, allowing you to use thousands of community-contributed timm models:

```python
from autotimm import ImageClassifier, list_hf_hub_backbones

# Discover models on HF Hub
models = list_hf_hub_backbones(model_name="resnet", limit=5)
print(models)
# ['hf-hub:timm/resnet50.a1_in1k', 'hf-hub:timm/resnet18.a1_in1k', ...]

# Use HF Hub model as backbone (just add 'hf-hub:' prefix)
model = ImageClassifier(
    backbone="hf-hub:timm/resnet50.a1_in1k",
    num_classes=10,
)

# Works with all tasks
from autotimm import SemanticSegmentor, ObjectDetector

seg_model = SemanticSegmentor(
    backbone="hf-hub:timm/convnext_tiny.fb_in22k",
    num_classes=19,
)

det_model = ObjectDetector(
    backbone="hf-hub:timm/efficientnet_b0.ra_in1k",
    num_classes=80,
)
```

### Three Integration Approaches

AutoTimm supports multiple ways to work with HuggingFace models:

| Approach | Best For | AutoTrainer | Integration |
|----------|----------|-------------|-------------|
| **HF Hub timm** | CNNs, Production | ✅ Full | Native |
| **HF Direct** | Vision Transformers | ✅ Full | Manual |
| **HF Auto** | Prototyping | ✅ Full | Manual |

1. **HF Hub timm Models** (via AutoTimm) - Recommended for CNNs
   - Use timm models from HF Hub: `"hf-hub:timm/resnet50.a1_in1k"`
   - Native AutoTimm integration
   - Works with all tasks

2. **HF Transformers Direct** - Recommended for Vision Transformers
   - Use specific model classes: `ViTModel`, `DeiTModel`, `BeitModel`
   - Full control and transparency
   - Manual PyTorch Lightning integration

3. **HF Transformers Auto** - For quick prototyping
   - Use Auto classes: `AutoModel`, `AutoConfig`
   - Quick experimentation
   - Less explicit

[Learn more about choosing the right approach →](https://theja-vanka.github.io/AutoTimm/user-guide/huggingface-integration-comparison/)

### Full AutoTrainer Support

All HuggingFace integration approaches work seamlessly with AutoTimm's AutoTrainer, including:

- ✅ Checkpoint monitoring and saving
- ✅ Early stopping callbacks
- ✅ Gradient accumulation
- ✅ Mixed precision training
- ✅ Automatic LR and batch size finding
- ✅ Multiple logger support
- ✅ ImageDataModule integration

```python
from autotimm import AutoTrainer, ImageClassifier, ImageDataModule
import pytorch_lightning as pl

model = ImageClassifier(
    backbone="hf-hub:timm/convnext_base.fb_in22k_ft_in1k",
    num_classes=100,
)

trainer = AutoTrainer(
    max_epochs=100,
    precision="16-mixed",
    callbacks=[
        pl.callbacks.ModelCheckpoint(monitor="val/accuracy", mode="max"),
        pl.callbacks.EarlyStopping(monitor="val/accuracy", patience=10),
    ],
)

trainer.fit(model, datamodule=ImageDataModule(data_dir="./data"))
```

**Key Features:**
- ✅ All three approaches fully compatible with PyTorch Lightning and AutoTrainer
- ✅ 200+ automated tests with comprehensive coverage
- ✅ Production-ready with checkpoint monitoring, early stopping, and mixed precision
- ✅ No special configuration needed - all features "just work"

[Learn more about choosing the right approach →](https://theja-vanka.github.io/AutoTimm/user-guide/huggingface-integration-comparison/)

**Benefits:**
- **Centralized hosting**: Access thousands of pretrained models
- **Version control**: Use specific model versions and configurations
- **Model cards**: View training details, datasets, and performance
- **Community models**: Share and use custom trained models
- **Same API**: Works exactly like standard timm models

## Key Features

### Multiple Loss Functions

**Classification**
- CrossEntropy with label smoothing
- Mixup augmentation

**Detection**
- Focal Loss (handles class imbalance)
- GIoU Loss (bbox regression)
- Centerness Loss (prediction quality)

**Segmentation**
- Dice Loss (overlap-based)
- Combined Loss (CE + Dice)
- Focal Loss (class imbalance)
- Tversky Loss (FP/FN weighting)

### TransformConfig (NEW!)

Unified configuration for image transforms with model-specific normalization:

```python
from autotimm import ImageClassifier, TransformConfig, list_transform_presets

# List available presets
list_transform_presets()  # ['default', 'autoaugment', 'randaugment', 'trivialaugment', 'light']
list_transform_presets(backend="albumentations")  # ['default', 'strong', 'light']

# Configure transforms with model-specific normalization
config = TransformConfig(
    preset="randaugment",
    image_size=384,
    use_timm_config=True,  # Auto-detect mean/std from model
)

# Model with preprocessing built-in
model = ImageClassifier(
    backbone="efficientnet_b4",
    num_classes=10,
    transform_config=config,
)

# Preprocess images using model's config
tensor = model.preprocess(pil_image)
```

### Preset Manager (NEW!)

Intelligent backend selection based on your task requirements:

```python
from autotimm import recommend_backend, compare_backends

# Get recommendation for your task
rec = recommend_backend(task="detection")
print(rec)
# Recommended Backend: albumentations
# Recommended Preset: default
# Reasoning: Object Detection requires bbox/mask-aware transforms...

# Convert to config
config = rec.to_config(image_size=640)

# Compare backends side-by-side
compare_backends()  # Prints detailed comparison table

# Advanced: Custom requirements
rec = recommend_backend(
    task="classification",
    needs_advanced_augmentation=True,
    needs_spatial_transforms=True,
)
config = rec.to_config()
```

**Why use the Preset Manager?**
- **Smart recommendations**: Get the best backend for your specific task
- **Reasoning provided**: Understand why a backend is recommended
- **Easy integration**: Convert recommendations directly to `TransformConfig`
- **Comparison tool**: See all differences between torchvision and albumentations

### Flexible Data Loading

All transform backends and formats are included by default:

- **Torchvision**: PIL-based transforms (fast CPU)
- **Albumentations**: OpenCV-based transforms (advanced augmentations)
- **Multiple Formats**: COCO, Cityscapes, Pascal VOC, ImageFolder, PNG masks
- **Custom Datasets**: Easy integration with PyTorch DataLoaders

### Advanced Training Features

- **Auto-tuning**: LR finder and batch size finder
- **Multi-GPU**: Distributed training with DDP
- **Mixed Precision**: Automatic mixed precision (AMP)
- **Gradient Accumulation**: Train larger batch sizes
- **Early Stopping**: Prevent overfitting
- **Checkpointing**: Save best models automatically

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

```bash
# Setup development environment
git clone https://github.com/theja-vanka/AutoTimm.git
cd AutoTimm
pip install -e ".[dev,all]"

# Run tests
pytest tests/ -v
```

## Testing

Comprehensive test suite with 200+ tests.

```bash
# Run all tests
pytest tests/ -v

# Run specific test modules
pytest tests/test_classification.py
pytest tests/test_semantic_segmentation.py
pytest tests/test_segmentation_losses.py

# With coverage
pytest tests/ --cov=autotimm --cov-report=html
```

**Recent Updates (v0.6.2):**
- ✅ **Preset Manager**: Smart backend recommendation system (`recommend_backend`, `compare_backends`)
- ✅ **Core dependencies updated**: `albumentations` and `pycocotools` now included by default (no extras needed)
- ✅ Added `TransformConfig` for unified transform configuration with presets
- ✅ Added `list_transform_presets()` to discover available transform presets
- ✅ Added model `preprocess()` method for inference-time image preprocessing
- ✅ Python 3.10-3.14 support (dropped Python 3.9)
- ✅ Fixed `RuntimeError` when calling `configure_optimizers()` without attached trainer
- ✅ Improved scheduler initialization to handle cases where model is not yet attached to trainer

## Citation

If you use AutoTimm in your research, please cite:

```bibtex
@software{autotimm,
  author = {Krishnatheja Vanka},
  title = {AutoTimm: Automatic Pytorch Image Models},
  url = {https://github.com/theja-vanka/AutoTimm},
  year = {2026}
}
```

<p align="center">
  Built with <a href="https://github.com/huggingface/pytorch-image-models">timm</a> and <a href="https://github.com/Lightning-AI/pytorch-lightning">PyTorch Lightning</a>
</p>
