Dl Transformer Finetune logo

Dl Transformer Finetune

Community
wentorai
dl-transformer-finetune

Build transformer fine-tuning plans for classification and generation

Overview

Publisherwentorai
Repositoryresearch-plugins
Skill namedl-transformer-finetune
Stars
294
Forks
42
Bundled files
Instructions only
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by wentorai on GitHub. Read the source before you install it.

Installation

Install the Dl Transformer Finetune AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/wentorai/research-plugins.git /tmp/research-plugins
mkdir -p .claude/skills
cp -r /tmp/research-plugins/skills/domains/ai-ml/dl-transformer-finetune .claude/skills/dl-transformer-finetune
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Dl Transformer Finetune in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Dl Transformer Finetune on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Dl Transformer Finetune is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

Transformer Fine-Tuning Guide

Overview

Fine-tuning pretrained transformers is the dominant paradigm in modern NLP and increasingly in vision, audio, and multimodal research. The core idea is simple: take a model pretrained on massive data, then adapt it to your specific task with a comparatively small labeled dataset. But the practical details -- which layers to freeze, which optimizer and learning rate to use, how to handle catastrophic forgetting, when to use parameter-efficient methods -- determine whether fine-tuning succeeds or fails.

This guide covers the full spectrum of fine-tuning approaches: full fine-tuning for maximum performance, parameter-efficient fine-tuning (PEFT) for resource-constrained settings, and the decision framework for choosing between them. The patterns are drawn from hundreds of published papers and the Hugging Face ecosystem that supports them.

Whether you are fine-tuning BERT for text classification in a domain-specific corpus, adapting a large language model with LoRA for instruction following, or building a multi-task model for your research pipeline, this guide provides the recipes you need.

Full Fine-Tuning

Text Classification with BERT

python
from transformers import (
    AutoModelForSequenceClassification,
    AutoTokenizer,
    TrainingArguments,
    Trainer,
)
from datasets import load_dataset
import numpy as np
from sklearn.metrics import accuracy_score, f1_score

# Load model and tokenizer
model_name = "bert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSequenceClassification.from_pretrained(
    model_name, num_labels=3
)

# Prepare dataset
dataset = load_dataset("multi_nli")

def tokenize_function(examples):
    return tokenizer(
        examples["premise"],
        examples["hypothesis"],
        truncation=True,
        max_length=128,
        padding="max_length",
    )

tokenized = dataset.map(tokenize_function, batched=True)

# Metrics
def compute_metrics(eval_pred):
    logits, labels = eval_pred
    preds = np.argmax(logits, axis=-1)
    return {
        "accuracy": accuracy_score(labels, preds),
        "f1_macro": f1_score(labels, preds, average="macro"),
    }

# Training arguments (research-grade defaults)
training_args = TrainingArguments(
    output_dir="./results",
    num_train_epochs=3,
    per_device_train_batch_size=32,
    per_device_eval_batch_size=64,
    learning_rate=2e-5,                  # Standard for BERT fine-tuning
    weight_decay=0.01,
    warmup_ratio=0.06,                   # 6% warmup
    evaluation_strategy="epoch",
    save_strategy="epoch",
    load_best_model_at_end=True,
    metric_for_best_model="f1_macro",
    fp16=True,
    dataloader_num_workers=4,
    seed=42,
    report_to="wandb",
)

trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=tokenized["train"],
    eval_dataset=tokenized["validation_matched"],
    compute_metrics=compute_metrics,
)

trainer.train()

Learning Rate Selection Guide

Model SizeRecommended LRWarmupWeight Decay
BERT-base (110M)2e-5 to 5e-56-10%0.01
BERT-large (340M)1e-5 to 3e-56-10%0.01
RoBERTa-large (355M)1e-5 to 2e-56%0.01
T5-base (220M)3e-4 to 1e-30-5%0.01
LLaMA-7B (full FT)1e-5 to 2e-53%0.0
LLaMA-7B (LoRA)1e-4 to 3e-43%0.0

Parameter-Efficient Fine-Tuning (PEFT)

LoRA (Low-Rank Adaptation)

LoRA freezes the pretrained weights and injects trainable low-rank decomposition matrices. It typically trains only 0.1-1% of parameters while achieving 95-100% of full fine-tuning performance.

python
from peft import LoraConfig, get_peft_model, TaskType
from transformers import AutoModelForCausalLM, AutoTokenizer

# Load base model
model = AutoModelForCausalLM.from_pretrained(
    "meta-llama/Llama-2-7b-hf",
    torch_dtype=torch.bfloat16,
    device_map="auto",
)

# Configure LoRA
lora_config = LoraConfig(
    task_type=TaskType.CAUSAL_LM,
    r=16,                          # Rank (8-64 typical)
    lora_alpha=32,                 # Scaling factor (usually 2*r)
    lora_dropout=0.05,
    target_modules=["q_proj", "v_proj", "k_proj", "o_proj"],
    bias="none",
)

model = get_peft_model(model, lora_config)
model.print_trainable_parameters()
# Output: trainable params: 4,194,304 || all params: 6,742,609,920 || trainable%: 0.062

QLoRA (Quantized LoRA)

python
from transformers import BitsAndBytesConfig

# 4-bit quantization config
bnb_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_compute_dtype=torch.bfloat16,
    bnb_4bit_use_double_quant=True,
)

model = AutoModelForCausalLM.from_pretrained(
    "meta-llama/Llama-2-7b-hf",
    quantization_config=bnb_config,
    device_map="auto",
)

# Apply LoRA on top of quantized model
model = get_peft_model(model, lora_config)
# Now fits on a single 24GB GPU!

PEFT Method Comparison

MethodTrainable %MemoryPerformanceBest For
Full fine-tuning100%HighBestSufficient compute + data
LoRA0.1-1%Low95-100%Most scenarios
QLoRA0.1-1%Very low93-98%Consumer GPUs
Prefix tuning~0.1%Low90-95%Generation tasks
Adapter layers1-5%Medium95-99%Multi-task
Prompt tuning<0.01%Minimal85-95%Large models, many tasks

Avoiding Catastrophic Forgetting

python
# Strategy 1: Gradual unfreezing (Howard & Ruder, 2018)
def gradual_unfreeze(model, epoch, total_layers=12):
    """Unfreeze one more layer group per epoch, from top to bottom."""
    layers_to_unfreeze = min(epoch + 1, total_layers)
    for i, (name, param) in enumerate(reversed(list(model.named_parameters()))):
        param.requires_grad = i < layers_to_unfreeze * 10  # ~10 params per layer

# Strategy 2: Discriminative learning rates
def get_layer_lrs(model, base_lr=2e-5, decay_factor=0.95):
    """Apply lower learning rates to earlier layers."""
    params = []
    num_layers = 12  # BERT-base
    for i in range(num_layers):
        lr = base_lr * (decay_factor ** (num_layers - i - 1))
        layer_params = [p for n, p in model.named_parameters()
                       if f"layer.{i}." in n]
        params.append({"params": layer_params, "lr": lr})
    return params

# Strategy 3: EWC (Elastic Weight Consolidation)
# Add a penalty term that keeps important weights close to pretrained values

Fine-Tuning Checklist for Papers

Before fine-tuning:
[ ] Report exact pretrained model name and version
[ ] Document dataset size, splits, and preprocessing
[ ] Specify hardware (GPU model, count, precision)
[ ] Set random seeds (Python, NumPy, PyTorch, CUDA)

During fine-tuning:
[ ] Use validation set for hyperparameter selection
[ ] Log training curves (loss, metrics per epoch)
[ ] Monitor for overfitting (val loss divergence)
[ ] Try at least 3 learning rates from the recommended range

Reporting:
[ ] Report mean and std across 3-5 random seeds
[ ] Include training time and compute cost
[ ] Compare against published baselines using same evaluation
[ ] Release model weights or LoRA adapters for reproducibility

Best Practices

  • Start with the recommended learning rate for your model size, then sweep 3-5 values.
  • Use LoRA first unless you have strong evidence that full fine-tuning is needed.
  • Always evaluate on a held-out test set that was not used for any hyperparameter decisions.
  • Freeze embeddings when fine-tuning for classification -- they rarely need updating.
  • Use gradient accumulation to simulate larger batch sizes on limited hardware.
  • Save the tokenizer alongside the model to ensure reproducibility.

References

Frequently asked questions

What does the Dl Transformer Finetune AI skill do?

Build transformer fine-tuning plans for classification and generation

Why use Dl Transformer Finetune on TypingMind?

Because you install it once and use it with any model. Dl Transformer Finetune is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Dl Transformer Finetune in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/wentorai/research-plugins/tree/main/skills/domains/ai-ml/dl-transformer-finetune. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Dl Transformer Finetune?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Dl Transformer Finetune?

As many as you like. As long as a model supports skills, you can use Dl Transformer Finetune with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Dl Transformer Finetune AI skill free?

Yes. It is published on GitHub by wentorai under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇