CoolFace
Modelpublic

notingemiu/llama-3.2-3b-ukrainian-alpaca-lora

sourceHugging Facellama3.2updated 3mo agoView on Hugging Face
0likes4downloads
Model Card

Llama-3.2-3B — Ukrainian Instruction LoRA Adapter

A LoRA adapter that fine-tunes Llama-3.2-3B-Instruct to follow instructions in Ukrainian — responding consistently in Ukrainian to questions and tasks, instead of defaulting to English or code-switching.

Trained on the `saillab/alpaca-ukrainian-cleaned` dataset (a translation of Stanford Alpaca into Ukrainian) using Unsloth on a free Google Colab T4 GPU.

What it does

Input: A user question or instruction in Ukrainian. Output: An answer in Ukrainian, in an instruction-following assistant style.

Examples (real outputs, including failures)

This section is intentionally honest — both successes and failures are shown, because the failures are pedagogically more useful than the wins.

Example 1 — Conceptual explanation (strong)

Q: Розкажи коротко про різницю між машинним навчанням та глибоким навчанням.

A:

Машинне навчання — це процес, який використовує алгоритми та підхід, щоб виявляти та навчати шаблонів у даних, без будь-якої конспікування або розуміння. Глибоке навчання — це тип машинного навчання, який використовує глибоку нейронну мережу (ГНН) для виявлення та навчання шаблонів у даних. ГНН складається з декількох шарів, які дозволяють моделі виявляти та навчати складніші шаблони, ніж традиційні алгоритми.

Structurally correct, terminology mostly accurate (one invented word — "конспікування"). Ukrainian is grammatical and natural.

Example 2 — Creative writing (weak)

Q: Напиши вірш про осінь у Карпатах, 4 рядки.

A:

В Карпатах осінь, як пала, Думає про те, що з'являється, Зими спати, та дожди стихають. Залижки заліза, золоті, Світло, що пронизує, і сніг, що хрустить під ногою.

No rhyme, structure deviates from the requested 4 lines, and includes nonsensical imagery ("залижки заліза"). Creative writing is a known weak spot of small models after light instruction tuning.

Example 3 — Domain-specific knowledge (hallucination)

Q: Як приготувати борщ? Список основних інгредієнтів та послідовність дій.

A (excerpt):

Інгредієнти: 1. Тушон (барбарис) 2. Зелена капуста 3. Сіль 4. Чай 5. Угорський перець ... 8. Сок гrapeфруіта ... 21. Зброяна сметана ...

Severe hallucination. The model invents ingredients (grapefruit juice, "armed sour cream", chai, "rouletonny shar"), omits beetroot, occasionally code-switches into English ("grape"). The Ukrainian instruction-tuned base does not encode authentic Ukrainian cuisine knowledge — and 250 LoRA steps on translated Alpaca data does not teach it.

Example 4 — Technical term explanation (hallucination)

Q: Поясни простими словами, що таке RAG у контексті LLM.

A:

РAG означає «збережена гілка» у контексті Large Language Model (LLM). Це означає, що в моделі LLM є окрема гілка, яка збережена та не змінюється, коли модель створюється...

Completely wrong. RAG stands for Retrieval-Augmented Generation. The base Llama-3.2-3B does know RAG in English but the Ukrainian-tuned adapter pushes confident wrong answers in Ukrainian.

Key finding: LoRA changes behavior, not knowledge

This adapter is a clean demonstration of one of the most important properties of LoRA fine-tuning:

*LoRA changes the model's behavior (respond in Ukrainian, follow instruction format), but does not add new knowledge.*

The model is now more compliant in Ukrainian — but on topics where Llama-3.2-3B never had reliable knowledge (Ukrainian cuisine specifics, recent technical terms in Ukrainian), it confidently produces wrong answers. The 2,000 training examples shifted the response distribution; they did not encyclopedically teach Ukrainian-language facts.

Production implication: for factual answers about a specific domain, this adapter must be combined with Retrieval-Augmented Generation (RAG) — retrieve relevant Ukrainian documents at inference time, supply them as context, and let the fine-tuned model phrase the answer. Fine-tuning alone is insufficient.

Training details

ParameterValue
Base modelunsloth/Llama-3.2-3B-Instruct
MethodLoRA (PEFT) via Unsloth
Datasetsaillab/alpaca-ukrainian-cleaned — 2,000 examples (random subset, seed=42)
Trainable params24.3M / 3.24B (0.75%)
LoRA configr=16, alpha=16, dropout=0, target modules: Q/K/V/O + gate/up/down
Loss maskingtrain_on_responses_only — only assistant tokens contribute to loss
Optimizeradamw_8bit, lr=2e-4, linear schedule, warmup 5 steps
Batchper-device 2 × grad-accum 4 = effective 8
Steps250 (= 1 epoch on 2,000 examples)
HardwareGoogle Colab T4 (free)
Training time~10 minutes
Final lossconverged from ~2.0 to ~0.9

Known limitations

  • —No factual knowledge gained. Hallucinations on domain-specific Ukrainian topics (cuisine, recent tech terms, regional facts).
  • —Weak at creative writing. Poetry/short forms are not reliably structured.
  • —Trained on translated Alpaca, not native Ukrainian text. The dataset is a machine/community translation of English Stanford Alpaca, so cultural nuances of native Ukrainian instruction-style are not perfectly captured.
  • —No formal evaluation. Unlike text-to-SQL, instruction-tuning is hard to score with exact-match. A proper evaluation would require LLM-as-judge (e.g. GPT-4 / Claude) on a held-out set — planned for v2.
  • —English/Russian code-switching can leak through on rare/technical questions ("grape", numeric chars).

When this adapter is useful

✅ Good for:

  • —Routing Ukrainian-language assistant responses in RAG-based chatbots (the adapter handles tone/language; RAG handles facts)
  • —Simple Q&A on generic, well-known topics that the base Llama already knows in English
  • —Demonstrations of LoRA mechanics

❌ Not appropriate for:

  • —Standalone factual answers about Ukrainian cuisine, history, geography
  • —Authoritative information without retrieval
  • —Creative writing (poetry, fiction)
  • —Mission-critical generation without an evaluation layer

How to use

python
from peft import PeftModel
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch

base = "unsloth/Llama-3.2-3B-Instruct"
adapter = "notingemiu/llama-3.2-3b-ukrainian-alpaca-lora"

tokenizer = AutoTokenizer.from_pretrained(adapter)
model = AutoModelForCausalLM.from_pretrained(
    base, torch_dtype=torch.float16, device_map="auto"
)
model = PeftModel.from_pretrained(model, adapter)

SYSTEM_PROMPT = "Ти — корисний помічник, що відповідає українською мовою грамотно та чітко."

messages = [
    {"role": "system", "content": SYSTEM_PROMPT},
    {"role": "user", "content": "Що таке нейронна мережа? Поясни простими словами."},
]
inputs = tokenizer.apply_chat_template(
    messages, tokenize=True, add_generation_prompt=True, return_tensors="pt"
).to(model.device)
out = model.generate(
    input_ids=inputs, max_new_tokens=300, temperature=0.7, do_sample=True, top_p=0.9
)
print(tokenizer.decode(out[0], skip_special_tokens=True))

Companion model

This adapter is paired with `notingemiu/llama-3.2-3b-text2sql-lora` — a text-to-SQL LoRA on the same base model. Together they form a small portfolio demonstrating two distinct LoRA use-cases: format/skill specialization (text-to-SQL) and language/style adaptation (Ukrainian instruction-following).

Author

Built as part of a portfolio for AI/LLM Engineer roles. Feedback welcome.