Skip to main content

Fine-tuning an LLM for Italian: LoRA, Datasets, and Evaluation

Fine-tuning an open-source Large Language Model for Italian allows you to specialize a generic model (Llama 2, Mistral, Zephyr) on specific tasks…

What do you think about this article?

Fine-tuning an LLM for Italian: LoRA, Datasets, and Evaluation
Italian NLPPhotos:RDNE Stock projectPexels

At a Glance

Fine-tuning an open-source Large Language Model for Italian allows you to specialize a generic model (Llama 2, Mistral, Zephyr) on specific tasks…

Fine-tuning an open-source Large Language Model for Italian allows you to specialize a generic model (Llama 2, Mistral, Zephyr) on specific tasks and language, while maintaining full control and data privacy. LoRA (Low-Rank Adaptation) solves the memory constraint: instead of updating billions of model parameters, you train only low-rank matrices (~1-2% of memory). On consumer GPUs (RTX 3090, RTX 4070), you can fine-tune 7B-13B models in hours. This article covers Italian dataset preparation, training setup with BitsAndBytes+PEFT, evaluation, and local deployment via Ollama.

Why Fine-tune Open-Source for Italian?

Base open-source models are trained on multilingual and generic corpora. Italian language, with rich morphosyntax and domain specificity (legal, medical, technical), requires specialization. Relying on proprietary cloud AI services for fine-tuning means losing privacy, paying per request, and depending on external APIs. Local fine-tuning offers three advantages:

  • Absolute privacy: company data stays on-premise, zero telemetry to external cloud services.
  • Zero cost: once trained, the model runs locally on Ollama without subscription.
  • Full control: hyperparameters, architecture, and datasets are yours. You iterate rapidly.

With LoRA, the storage footprint is tiny: a LoRA adaptation for Llama 2 7B is ~100 MB. You can train multiple specialized adaptations (one for support, one for copywriting, one for FAQs) and load them dynamically in memory.

Dataset Preparation for Italian Fine-tuning

Dataset quality determines 80% of the result. A model fine-tuned on poor data produces poor output, regardless of GPU and hyperparameters.

Format and Data Structure

The standard format is JSONL (JSON Lines): one text record per line, with fields `instruction` and `output`.


# Dataset format: dataset-italiano.jsonl
# JSON lines, one per record
{"instruction": "Explain what a blockchain is", "output": "A blockchain is a distributed ledger..."}
{"instruction": "Translate to Italian: Hello world", "output": "Ciao mondo"}
{"instruction": "Write a pasta carbonara recipe", "output": "Ingredients: eggs, guanciale, pecorino..."}
  

Curation and Cleaning

Before training:

  • Remove duplicates: use SHA256 hash on instruction+output concatenation.
  • Filter corrupted text: encoding errors, strange character sequences.
  • Validate structure: every record must have non-empty `instruction` and `output`.
  • Distribute by domain: 30% generic tasks, 40% domain-specific, 30% conversational.

import json
from collections import defaultdict

def clean_dataset(input_file, output_file, min_tokens=10):
    seen_hashes = set()
    records = []
    domain_counts = defaultdict(int)

    with open(input_file, 'r', encoding='utf-8') as f:
        for line in f:
            try:
                record = json.loads(line)
                if 'instruction' not in record or 'output' not in record:
                    continue

                # Remove too-short records
                if len(record['instruction'].split()) < min_tokens:
                    continue

                # Deduplication
                h = hash(record['instruction'] + record['output'])
                if h in seen_hashes:
                    continue
                seen_hashes.add(h)

                # Count domain
                domain = record.get('domain', 'general')
                domain_counts[domain] += 1
                records.append(record)

            except json.JSONDecodeError:
                continue

    # Write cleaned dataset
    with open(output_file, 'w', encoding='utf-8') as f:
        for r in records:
            f.write(json.dumps(r, ensure_ascii=False) + '\n')

    print(f"Cleaned dataset: {len(records)} records")
    print(f"Domain distribution: {dict(domain_counts)}")

# Usage
clean_dataset('dataset-raw.jsonl', 'dataset-italiano-pulito.jsonl')
  

LoRA vs QLoRA: What to Use on Consumer GPU

LoRA (Low-Rank Adaptation) is a technique that reduces trainable parameters from billions to millions. Instead of updating the weight matrix W, you train only two low-rank matrices A and B where W ≈ W_orig + α * A * B. Memory consumption: 1/4 of full-tuning.

QLoRA combines LoRA with 4-bit quantization: the base model is quantized to 4-bit, LoRA trains in low precision. Memory: 1/10 of full-tuning. On an RTX 3090 (24GB), you can fine-tune Llama 2 70B; on RTX 4070 (12GB), fine-tune Mistral 7B comfortably.

Technique GPU Memory Speed Output Quality
Full Fine-tuning 80GB (A100) Baseline Excellent
LoRA 12-20GB (RTX 4070/3090) 2-3x faster Good
QLoRA 4-bit 6-8GB (RTX 4070/3060) 1.5x LoRA Good (minimal loss)

Environment Setup: PyTorch, Transformers, PEFT


# Create virtual environment
python -m venv llm-finetuning
source llm-finetuning/bin/activate

# Install dependencies (PyTorch with CUDA 12.1)
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121
pip install transformers>=4.38.0
pip install peft>=0.8.2
pip install bitsandbytes>=0.41.0
pip install datasets
pip install accelerate>=0.27.0
pip install wandb  # For training logging

# Verify CUDA
python -c "import torch; print(torch.cuda.is_available(), torch.cuda.get_device_name(0))"
  

Complete Training Script: LoRA and QLoRA


import torch
from transformers import (
    AutoTokenizer,
    AutoModelForCausalLM,
    TrainingArguments,
    Trainer,
    DataCollatorForLanguageModeling
)
from peft import (
    get_peft_model,
    LoraConfig,
    prepare_model_for_kbit_training
)
from datasets import load_dataset
from bitsandbytes.optim import AdamW8bit

# 1. Load dataset
print("Loading dataset...")
dataset = load_dataset('json', data_files='dataset-italiano-pulito.jsonl')

# 2. Tokenization
print("Tokenizing...")
tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-v0.2")
tokenizer.pad_token = tokenizer.eos_token

def tokenize_function(examples):
    # Combine instruction + output
    texts = [
        f"### Instruction:\n{ex['instruction']}\n\n### Response:\n{ex['output']}"
        for ex in examples['instruction']
    ]
    tokenized = tokenizer(
        texts,
        max_length=2048,
        padding='max_length',
        truncation=True,
        return_tensors=None
    )
    tokenized['labels'] = tokenized['input_ids'].copy()
    return tokenized

tokenized_dataset = dataset.map(
    tokenize_function,
    batched=True,
    batch_size=32,
    remove_columns=['instruction', 'output']
)

# 3. Load base model (4-bit quantized for QLoRA)
print("Loading base model...")
quantization_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_compute_dtype=torch.float16,
    bnb_4bit_use_double_quant=True,
    bnb_4bit_quant_type="nf4"
)

model = AutoModelForCausalLM.from_pretrained(
    "mistralai/Mistral-7B-v0.2",
    quantization_config=quantization_config,
    device_map="auto",
    trust_remote_code=True
)

# Prepare model for QLoRA training
model = prepare_model_for_kbit_training(model)

# 4. Configure LoRA
lora_config = LoraConfig(
    r=16,                          # LoRA rank
    lora_alpha=32,                 # Alpha scaling
    target_modules=["q_proj", "v_proj"],  # Target query and value
    lora_dropout=0.05,
    bias="none",
    task_type="CAUSAL_LM"
)

# 5. Apply LoRA to model
model = get_peft_model(model, lora_config)
model.print_trainable_parameters()  # ~51M trainable on 7B total

# 6. Configure training
training_args = TrainingArguments(
    output_dir="./lora-mistral-italiano",
    overwrite_output_dir=True,
    num_train_epochs=3,
    per_device_train_batch_size=1,  # QLoRA on 8GB GPU
    gradient_accumulation_steps=8,  # Simulates batch_size=8
    gradient_checkpointing=True,
    learning_rate=2e-4,
    weight_decay=0.01,
    warmup_steps=100,
    max_steps=1000,  # Adapt to dataset size
    save_steps=100,
    eval_steps=100,
    save_strategy="steps",
    eval_strategy="steps",
    logging_steps=10,
    logging_dir='./logs',
    optim="paged_adamw_8bit",  # 8-bit optimizer on 4-bit model
    bf16=True,  # BFloat16 for stability
    report_to=["wandb"],
    run_name="lora-mistral-italiano-v1"
)

# 7. Trainer
trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=tokenized_dataset['train'],
    eval_dataset=tokenized_dataset.get('validation', None),
    data_collator=DataCollatorForLanguageModeling(
        tokenizer=tokenizer,
        mlm=False
    ),
    optimizers=(
        AdamW8bit(
            model.parameters(),
            lr=training_args.learning_rate,
            weight_decay=training_args.weight_decay
        ),
        None  # scheduler
    )
)

# 8. Train!
print("Starting training...")
trainer.train()

# 9. Save LoRA adaptation
print("Saving LoRA weights...")
model.save_pretrained("./lora-mistral-italiano-final")
tokenizer.save_pretrained("./lora-mistral-italiano-final")
  

Critical Hyperparameters and Tuning

  • learning_rate: 2e-4 for standard LoRA, 1e-4 for QLoRA (quantized is more sensitive).
  • r (LoRA rank): 8-16 for generic tasks, 32-64 if you want more capacity (but ~100MB per LoRA 64). Start with 16.
  • lora_alpha: usually alpha = 2 * r. If r=16, alpha=32.
  • batch_size: on RTX 4070 (12GB): batch=1 + gradient_accumulation=8 simulates batch=8 without OOM.
  • num_epochs: 2-3 for dataset >10k records. 5+ if <5k records.
  • warmup_steps: ~5-10% of total training steps.

Post-Training Quantization: GGUF for Ollama

After LoRA fine-tuning, the model is in PyTorch (two files: model.safetensors and lora weights). To deploy on Ollama, you convert to GGUF (GGML Universal Format), an optimized format for local CPU/GPU inference.

Merge LoRA with Base Model

Before converting, merge the LoRA with the base model.


from transformers import AutoModelForCausalLM, AutoTokenizer
from peft import PeftModel

# Load base model
base_model = AutoModelForCausalLM.from_pretrained(
    "mistralai/Mistral-7B-v0.2",
    torch_dtype=torch.float16,
    device_map="auto"
)

# Load LoRA weights
lora_model = PeftModel.from_pretrained(
    base_model,
    "./lora-mistral-italiano-final"
)

# Merge
merged_model = lora_model.merge_and_unload()

# Save merged in Hugging Face format
merged_model.save_pretrained("./mistral-italiano-merged", safe_serialization=True)
tokenizer.save_pretrained("./mistral-italiano-merged")
  

GGUF Conversion

You use the official `llama.cpp` tool (converted to Python).


# Clone llama.cpp
git clone https://github.com/ggerganov/llama.cpp.git
cd llama.cpp

# Convert merged model to GGUF (quantized to 5-bit for balance)
python convert-hf-to-gguf.py \
  --model-dir ../mistral-italiano-merged \
  --outfile mistral-italiano.gguf \
  --outtype f16

# Quantize to Q5_K_M (5-bit, recommended)
./quantize mistral-italiano.gguf mistral-italiano-q5.gguf Q5_K_M
  

Result: mistral-italiano-q5.gguf (~4.5 GB for Mistral 7B). On modern CPU: ~15-30 tokens/sec. On GPU: ~100-150 tokens/sec.

Deployment with Ollama (On-Premises)

Ollama is the official local runtime for GGUF models. Installation and deployment:


# Install Ollama (macOS, Linux, Windows)
# https://ollama.ai

# Create custom Modelfile for your fine-tuned GGUF
cat > Modelfile-italiano << 'EOF'
FROM ./mistral-italiano-q5.gguf

SYSTEM """You are an AI assistant specialized for the Italian language. Respond in Italian, with precision and clarity. If you don't know the answer, say so."""

PARAMETER num_ctx 2048
PARAMETER top_k 40
PARAMETER top_p 0.9
PARAMETER temperature 0.7
EOF

# Create the Ollama model
ollama create mistral-italiano -f Modelfile-italiano

# Test
ollama run mistral-italiano "Explain what photosynthesis is in 3 lines"

# Enable API (by default on localhost:11434)
ollama serve &

# Test via curl
curl http://localhost:11434/api/generate \
  -d '{"model":"mistral-italiano","prompt":"Tell me an Italian recipe"}'
  

Evaluation and Benchmarking

Post fine-tuning, evaluate the model with three criteria:

1. Automated Benchmarks

Use public evaluation datasets in Italian (e.g., ITA-CoLA, Italian XNLI).


from datasets import load_dataset
from evaluate import load

# Load Italian benchmark
benchmark = load_dataset("evalita", "sentipolc2016")

# Compile data for BLEU/ROUGE
predictions = []
references = []

# Generate responses from your fine-tuned model
# for each example in benchmark

# Compute BLEU
bleu = load("bleu")
results = bleu.compute(predictions=predictions, references=references)
print(f"BLEU: {results}")

# ROUGE for summaries
rouge = load("rouge")
rouge_results = rouge.compute(
    predictions=predictions,
    references=references,
    use_stemmer=True
)
print(f"ROUGE-L: {rouge_results['rougeL']}")
  

2. Manual Semantic Evaluation

Pick 50-100 test cases and judge: linguistic correctness (grammar, fluency), prompt adherence (relevance), completeness. Scale 1-5.


# Evaluation template
test_cases = [
    {
        "instruction": "Write a polite email to cancel a booking",
        "expected_tone": "Professional",
        "expected_length": "50-100 words"
    },
    # ...
]

# After generation, grade each output
for case in test_cases:
    output = model.generate(case['instruction'], max_tokens=300)

    # Human judgment (1-5)
    relevance = 5  # How relevant to the request?
    quality = 4    # Linguistic quality?
    completeness = 5  # Did it answer everything?

    score = (relevance + quality + completeness) / 3
    print(f"Score: {score}, Output: {output[:100]}")
  

3. Perplexity on Italian Test Set

Perplexity measures how "surprised" the model is by your test data. Lower = better.


import math

def compute_perplexity(model, eval_dataset, tokenizer):
    total_loss = 0
    total_tokens = 0

    for batch in eval_dataset:
        input_ids = tokenizer.encode(batch['text'], return_tensors='pt').to(model.device)
        with torch.no_grad():
            outputs = model(input_ids, labels=input_ids)
            loss = outputs.loss

        total_loss += loss.item() * len(input_ids[0])
        total_tokens += len(input_ids[0])

    perplexity = math.exp(total_loss / total_tokens)
    return perplexity

# Target: <10 perplexity on domain-specific test set
  

Common Troubleshooting

  • CUDA Out of Memory: reduce batch_size, increase gradient_accumulation_steps, enable gradient_checkpointing=True.
  • Training loss not dropping: learning_rate too low? Try 1e-3. Corrupted data? Validate dataset. Base model too small? Move to 13B.
  • Repetitive output: temperature too low (use 0.7+), top_p too low (use 0.9+), or LoRA rank too high (reduce from 64 to 16).
  • GGUF too large: quantize to Q4_K_M (4-bit) instead of Q5_K_M to reduce size 20-30%.
  • Ollama inference slow: enable GPU if available, reduce num_ctx or batch_size in inference.

FAQ

Q: What is the best model for fine-tuning Italian on consumer GPU?
R: Mistral 7B and Llama 2 7B are the sweet spot: small enough for RTX 4070 (12GB) with QLoRA, large enough to capture Italian linguistic complexity. If you have 24GB+ (RTX 3090), go with Llama 2 13B or Mistral 8x7B (mixture of experts).

Q: How long does fine-tuning take?
R: Depends on dataset size and GPU. With 5k instruction records, RTX 4070, batch=1+gradient_accum=8: ~2-3 hours for 3 epochs. With 50k records: ~20-30 hours.

Q: Can I combine LoRA from different tasks (support + copywriting)?
R: Yes, but with caution. Load the support LoRA, then load the copywriting one: the second overwrites the first. Better to create two separate models (storage ~200 MB each) and switch dynamically in Ollama with a load script.

Q: Does my LoRA lose quality over time in production?
R: No, LoRA is static once saved. The base model does not drift. If you suspect degradation, verify you are loading the same GGUF and LoRA on Ollama.

Q: Can I fine-tune on non-Italian data?
R: Yes, but you lose the specialization advantage. If you want a multi-domain Italian+English model, use a 60% Italian / 40% English split in the training set.

Try These Tools

Free developer tools related to this topic.

Commenti

Caricamento commenti...

Sign in to comment

Discuss this article in the community

Join the Telegram group to discuss with other developers, ask questions and share your experiences.

Did you like this article?

Explore other content on the blog or discover my projects