Skip to main content

A package for finetuning text models.

Project description

langtune: Large Language Models (LLMs) with Efficient LoRA Fine-Tuning for Text


Langtune Logo

PyPI version Downloads License Code style: black

Modular LLMs (Large Language Models for Text) with Efficient LoRA Fine-Tuning
Build, adapt, and fine-tune text models with ease and efficiency.


🚀 Quick Links


📚 Table of Contents


✨ Features

  • 🔧 Plug-and-play LoRA adapters for parameter-efficient fine-tuning of LLMs
  • 🏗️ Modular Transformer backbone with customizable components
  • 🎯 Unified model zoo for open-source language models
  • ⚙️ Easy configuration and extensible codebase
  • 🚀 Production ready with comprehensive testing and documentation
  • 💾 Memory efficient training with gradient checkpointing support
  • 📊 Built-in metrics and visualization tools
  • 🧩 Modular training loop with LoRA support
  • 🎯 Unified CLI for fine-tuning and evaluation
  • 🔌 Extensible callbacks (early stopping, logging, etc.)
  • 📦 Checkpointing and resume
  • 🚀 Mixed precision training
  • 🔧 Easy dataset and model extension
  • Ready for distributed/multi-GPU training

🚀 Showcase

langtune is a modular, research-friendly framework for building and fine-tuning Large Language Models (LLMs) for text with efficient Low-Rank Adaptation (LoRA) support. Whether you're working on text classification, summarization, question answering, or custom NLP tasks, langtune provides the tools you need for parameter-efficient model adaptation.


🏁 Getting Started

Here's a minimal example to get you up and running:

pip install langtune
import torch
from langtune.models.llm import LanguageModel
from langtune.utils.config import default_config

# Create model
input_ids = torch.randint(0, 1000, (2, 128))
model = LanguageModel(
    vocab_size=default_config['vocab_size'],
    embed_dim=default_config['embed_dim'],
    num_layers=default_config['num_layers'],
    num_heads=default_config['num_heads'],
    mlp_ratio=default_config['mlp_ratio'],
    lora_config=default_config['lora'],
)

# Forward pass
with torch.no_grad():
    out = model(input_ids)
    print('Output shape:', out.shape)

For advanced usage, CLI details, and more, see the Documentation and src/langtune/cli/finetune.py.


🐍 Supported Python Versions

  • Python 3.8+

🧩 Why langtune?

  • Parameter-efficient fine-tuning: Plug-and-play LoRA adapters for fast, memory-efficient adaptation with minimal computational overhead
  • Modular Transformer backbone: Swap or extend components like embedding, attention, or MLP heads with ease
  • Unified model zoo: Access and experiment with open-source language models through a consistent interface
  • Research & production ready: Clean, extensible codebase with comprehensive configuration options and robust utilities
  • Memory efficient: Fine-tune large models on consumer hardware by updating only a small fraction of parameters

🏗️ Architecture Overview

langtune is built around a modular Transformer backbone, with LoRA adapters strategically injected into attention and MLP layers for efficient fine-tuning. This approach allows you to adapt large pre-trained models using only a fraction of the original parameters.

Model Data Flow

---
config:
  layout: dagre
---
flowchart TD
 subgraph LoRA_Adapters["LoRA Adapters in Attention and MLP"]
        LA1(["LoRA Adapter 1"])
        LA2(["LoRA Adapter 2"])
        LA3(["LoRA Adapter N"])
  end
    A(["Input Tokens"]) --> B(["Embedding Layer"])
    B --> C(["Positional Encoding"])
    C --> D1(["Encoder Layer 1"])
    D1 --> D2(["Encoder Layer 2"])
    D2 --> D3(["Encoder Layer N"])
    D3 --> E(["LayerNorm"])
    E --> F(["MLP Head"])
    F --> G(["Output Logits"])
    LA1 -.-> D1
    LA2 -.-> D2
    LA3 -.-> D3
     LA1:::loraStyle
     LA2:::loraStyle
     LA3:::loraStyle
    classDef loraStyle fill:#e1f5fe,stroke:#0277bd,stroke-width:2px

Architecture Components

Legend:

  • Solid arrows: Main data flow through the Transformer
  • Dashed arrows: LoRA adapter injection points in encoder layers
  • Blue boxes: LoRA adapters for parameter-efficient fine-tuning

Data Flow Steps:

  1. Input Tokens: Tokenized text data ready for processing
  2. Embedding Layer: Tokens mapped to dense vectors
  3. Positional Encoding: Learnable or fixed position embeddings added
  4. Transformer Encoder Stack: Multi-layer transformer with self-attention and MLP blocks
    • LoRA Integration: Low-rank adapters injected into attention and MLP layers
    • Efficient Updates: Only LoRA parameters updated during fine-tuning
  5. LayerNorm: Final normalization of encoder outputs
  6. MLP Head: Task-specific classification or regression head
  7. Output: Final predictions (class probabilities, regression values, etc.)

🧩 Core Modules

Module Description Key Features
Embedding Token embedding and positional encoding • Configurable vocab size
• Learnable/fixed position embeddings
TransformerEncoder Multi-layer transformer backbone • Self-attention mechanisms
• LoRA adapter integration
• Gradient checkpointing support
LoRALinear Low-rank adaptation layers • Configurable rank and scaling
• Memory-efficient updates
• Easy enable/disable functionality
MLPHead Output projection layer • Multi-class classification
• Regression support
• Dropout regularization
Config System Centralized configuration management • YAML/JSON config files
• Command-line overrides
• Validation and defaults
Data Utils Preprocessing and augmentation • Built-in tokenization
• Custom dataset loaders
• Efficient data pipelines

📊 Performance & Efficiency

LoRA Benefits

Metric Full Fine-tuning LoRA Fine-tuning Improvement
Trainable Parameters 125M 3.2M 97% reduction
Memory Usage 16GB 5GB 69% reduction
Training Time 6 hours 2 hours 67% faster
Storage per Task 500MB 12MB 98% smaller

Benchmarks on Transformer-Base with WikiText-103, RTX 3090

Supported Model Sizes

  • Transformer-Tiny: 7M parameters, perfect for experimentation
  • Transformer-Small: 30M parameters, good balance of performance and efficiency
  • Transformer-Base: 125M parameters, strong performance across tasks
  • Transformer-Large: 355M parameters, state-of-the-art results

🔧 Advanced Configuration

LoRA Configuration

lora_config = {
    "rank": 16,                    # Low-rank dimension
    "alpha": 32,                   # Scaling factor
    "dropout": 0.1,                # Dropout rate
    "target_modules": [            # Modules to adapt
        "attention.qkv",
        "attention.proj", 
        "mlp.fc1",
        "mlp.fc2"
    ],
    "merge_weights": False         # Whether to merge during inference
}

Training Configuration

# config.yaml
model:
  name: "transformer_base"
  vocab_size: 50257
  embed_dim: 768
  num_layers: 12
  num_heads: 12

training:
  epochs: 10
  batch_size: 32
  learning_rate: 1e-4
  weight_decay: 0.01
  warmup_steps: 1000

lora:
  rank: 16
  alpha: 32
  dropout: 0.1

📚 Documentation & Resources

Research Papers


🧪 Testing & Quality

Run the comprehensive test suite:

# Unit tests
pytest tests/unit/

# Integration tests  
pytest tests/integration/

# Performance benchmarks
pytest tests/benchmarks/

# All tests with coverage
pytest tests/ --cov=langtune --cov-report=html

Code Quality Tools

# Linting
flake8 src/
black src/ --check

# Type checking
mypy src/

# Security scanning
bandit -r src/

🚀 Examples & Use Cases

Text Classification

from langtune import LanguageModel
from langtune.datasets import TextClassificationDataset

# Load pre-trained model
model = LanguageModel.from_pretrained("transformer_base")

# Fine-tune on custom dataset
dataset = TextClassificationDataset(train=True, tokenizer=model.tokenizer)
model.finetune(dataset, epochs=10, lora_rank=16)

Custom Dataset

from langtune.datasets import CustomTextDataset

# Your custom dataset
dataset = CustomTextDataset(
    file_path="/path/to/dataset.txt",
    split="train",
    tokenizer=model.tokenizer
)

# Fine-tune with custom configuration
model.finetune(
    dataset, 
    config_path="configs/custom_config.yaml"
)

🧩 Extending the Framework

  • Add new datasets in src/langtune/data/datasets.py
  • Add new callbacks in src/langtune/callbacks/
  • Add new models in src/langtune/models/
  • Add new CLI tools in src/langtune/cli/

📖 Documentation

  • See code comments and docstrings for details on each module.
  • For advanced usage, see the src/langtune/cli/finetune.py script.

🤝 Contributing

We welcome contributions from the community! Here's how you can get involved:

Ways to Contribute

  • 🐛 Report bugs by opening issues with detailed reproduction steps
  • 💡 Suggest features through feature requests and discussions
  • 📝 Improve documentation with examples, tutorials, and API docs
  • 🔧 Submit pull requests for bug fixes and new features
  • 🧪 Add tests to improve code coverage and reliability

Development Setup

# Clone and setup development environment
git clone https://github.com/langtrain-ai/langtune.git
cd langtune
pip install -e ".[dev]"

# Install pre-commit hooks
pre-commit install

# Run tests
pytest tests/

Community Resources

📄 License & Citation

This project is licensed under the MIT License - see the LICENSE file for details.

Citation

If you use langtune in your research, please cite:

@software{langtune2025,
  author = {Pritesh Raj},
  title = {langtune: LLMs with Efficient LoRA Fine-Tuning},
  url = {https://github.com/langtrain-ai/langtune},
  year = {2025},
  version = {0.1.0}
}

🌟 Acknowledgements

We thank the following projects and communities:

  • PyTorch - Deep learning framework
  • HuggingFace - Transformers and model hub
  • PEFT - Parameter-efficient fine-tuning methods

Made in India 🇮🇳 with ❤️ by the langtune team
Star ⭐ this repo if you find it useful!

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

langtune-0.1.0.tar.gz (8.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

langtune-0.1.0-py3-none-any.whl (8.4 kB view details)

Uploaded Python 3

File details

Details for the file langtune-0.1.0.tar.gz.

File metadata

  • Download URL: langtune-0.1.0.tar.gz
  • Upload date:
  • Size: 8.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.11

File hashes

Hashes for langtune-0.1.0.tar.gz
Algorithm Hash digest
SHA256 ee607ade1a954794e177d2276bbd3337c409be69b30f0ed4a134027bfd5e6290
MD5 8a754256ab085da6c3621bf4faf53c9d
BLAKE2b-256 2113c500c9d9865d0c5725ab318fa70dadff19561410af4dc59eb327b0cc7aa1

See more details on using hashes here.

File details

Details for the file langtune-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: langtune-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 8.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.11

File hashes

Hashes for langtune-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 9acedfcc7234b1f5973fea99f9765b7c0f6c2e1110274a6321ce9eef638bdcad
MD5 944d6ab8b6240fc09d89a6d77b0df135
BLAKE2b-256 e7133f5974e9d96fc1a9d2043b077e14307398cf016943139eaf7e13f8cf1c20

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page