Python MIT License Open Source Project

Fine Tune LLM with LoRA in Python on a CPU: Student Q&A Bot (Free Code)

Fine tune LLM with LoRA in Python on a laptop CPU: build a student Q&A bot with SmolLM2 or Qwen and measure exact match before and after. Free source code.

Project Specifications & Technical Summary

Difficulty Beginner
License MIT License

Want to fine tune LLM with LoRA but think you need an expensive GPU? You don’t. In this tutorial you will take a small open language model, teach it to answer computer-science questions in a few words, and measure exactly how much better it got, all on an ordinary laptop CPU. Training takes about two minutes. The result is a working student Q&A bot and a project you can explain line by line in your viva.

This project is for BTech, MCA and MTech students who want an AI final-year or mini project that goes beyond calling an API. You will fine tune LLM with LoRA end to end: a dataset builder, a config validator, a LoRA training loop with Hugging Face PEFT, an evaluation script with perplexity and exact match, and a merge/export step. In our run, exact match on questions the model had never seen phrased that way went from 1.2% to 72.0%. All 99 pytest tests run in seconds without downloading a model, and the complete source code is free on GitHub under the MIT License.

What Does It Mean to Fine Tune LLM with LoRA?

A large language model (LLM) such as SmolLM2 or Qwen has already learned a lot of English and general knowledge during pretraining. Fine-tuning means training it a little more on your own examples so it behaves the way you want: a fixed answer style, your syllabus facts, your output format.

Full fine-tuning updates every weight in the model. Even a 135-million-parameter model then needs gigabytes of memory for gradients and optimizer state, and a 7B model needs serious GPUs. LoRA (Low-Rank Adaptation), introduced by Hu et al. in 2021, takes a smarter route:

  • Freeze all the original weights. They never change.
  • Next to selected weight matrices (the attention projections and MLP layers), add two small matrices A and B whose product B·A has a low rank r, such as 8 or 16.
  • Train only A and B. In this project that is 4.88 million of 139.4 million parameters, about 3.5%.
  • After training, you can keep the adapter as a separate 8.7 MB file or merge B·A back into the frozen weights, so inference is exactly as fast as the original model.
How LoRA works when you fine tune LLM with LoRA: frozen weight W plus trainable low-rank matrices B and A inside one attention layer
Inside one layer: the big matrix stays frozen and only the small A and B matrices learn.

Because B starts at zero, the model at step 0 is exactly the base model, and training only nudges it. That is why LoRA is stable, cheap, and the default way people fine tune LLM with LoRA today. QLoRA goes one step further by loading the frozen model in 4-bit precision, which matters for 7B+ models on a GPU, but for a 135M model on a CPU, plain LoRA is enough.

What You Will Build

Everything you need to fine tune LLM with LoRA lives in one Python package called lora_qa, with a command-line tool called lora-qa:

CommandWhat it does
lora-qa build-dataCleans raw JSONL or CSV Q&A, removes duplicates and writes train, val and test splits with a leakage check.
lora-qa check-configValidates a YAML training config before any model loads, with “did you mean” hints for typos.
lora-qa trainFine-tunes the model with LoRA and saves the adapter, the loss history and a summary.
lora-qa compareScores the base model and the LoRA model on the test set: perplexity, exact match and token F1.
lora-qa mergeMerges the adapter into the base model and exports a standalone safetensors model.
lora-qa askAsks the bot questions from the terminal.
Fine tune LLM with LoRA project pipeline in Python: raw Q&A data, build-data, LoRA training, compare evaluation and merge export
The five stages of the project, each one a lora-qa command.

The bot is trained on 82 computer-science facts that come up in exams and placement interviews: data structures, operating systems, DBMS, computer networks, Python, machine learning and software engineering. Each fact is written as four different questions, for example “What is the time complexity of binary search?” and “Give the Big-O running time of binary search.” with the short answer O(log n).

Why Students Should Learn to Fine Tune LLM with LoRA in 2026

Fine-tuning has moved from research labs to job descriptions. Naukri’s AI Skills: Complete Guide for Indians (2026) (24 June 2026), based on 14,500 live AI job ads, lists LLM fine-tuning + RAG as a requirement in 48% of AI job descriptions, and reports a median salary bump of about 38% for LLM fine-tuning skills in Q1 2026 offer letters. It also names fine-tuning, RAG and AI agent design as the fastest-growing AI skills.

FACE Prep’s 2026 AI Career Roadmap for Indian engineering students (Edition 1, May 2026) lists fine-tuned models among the portfolio projects that change a recruiter’s mind, and its guide to free AI learning resources (June 2026) points students to LoRA fine-tuning courses and free Colab or Kaggle GPUs. Most tutorials still assume a GPU, though. This project shows you can learn the whole workflow on a CPU first, then scale up on free Colab.

Tech Stack and Prerequisites

Here is everything you need to fine tune LLM with LoRA on your own laptop. All of it is free and open source.

ItemDetails
LanguagePython 3.10 to 3.13
LibrariesPyTorch (CPU build is fine), Hugging Face Transformers, PEFT, safetensors, PyYAML
ModelsSmolLM2-135M-Instruct for laptops, Qwen2.5-0.5B-Instruct for 16 GB RAM or free Colab. Both are Apache 2.0.
HardwareAny 4 to 8 core laptop with 8 GB RAM. No GPU needed. A GPU is used automatically if present.
Testingpytest, pytest-cov, ruff, GitHub Actions on Python 3.10 to 3.13
KnowledgeBasic Python and some idea of what a neural network is. No prior LLM experience needed.

Project File Structure

Fine-Tune-LLM-with-LoRA-Python/
├── lora_qa/
│   ├── config.py      # TrainConfig dataclass + validation
│   ├── data.py        # dataset builder, prompt template, label masking
│   ├── modeling.py    # load model, add LoRA, tiny test model
│   ├── train.py       # training loop
│   ├── metrics.py     # exact match, token F1, perplexity
│   ├── evaluate.py    # batch generation, scoring, comparison table
│   ├── merge.py       # merge_and_unload + export
│   └── cli.py         # the lora-qa command
├── configs/           # cpu-smollm2-135m.yaml, colab-qwen2.5-0.5b.yaml, tiny-smoke.yaml
├── data/raw/cs_student_qa.jsonl
├── notebooks/colab_quickstart.ipynb
├── results/           # real run logs, eval JSON and comparison tables
├── tests/             # 99 tests on a tiny random model
└── .github/workflows/ci.yml

Step-by-Step: Fine Tune LLM with LoRA in Python

Step 1: Install the project

To fine tune LLM with LoRA on a CPU, create a virtual environment and install the CPU build of PyTorch first. It is a much smaller download than the default CUDA build (see the PyTorch install selector for other options):

git clone https://github.com/GetProjectsIdea/Fine-Tune-LLM-with-LoRA-Python.git
cd Fine-Tune-LLM-with-LoRA-Python
python -m venv .venv
source .venv/bin/activate          # Windows: .venv\Scripts\activate
pip install torch --index-url https://download.pytorch.org/whl/cpu
pip install -e ".[dev]"

Step 2: Build a clean dataset (and avoid leakage)

Raw data rarely arrives clean. data.py accepts grouped JSONL (one fact with several questions), simple question/answer pairs, or a CSV file. It normalises spaces, drops empty or overly long answers, removes duplicate questions and merges pairs that share the same answer.

The most important decision is how you split the data. With the default paraphrase split, every fact keeps two phrasings for training, one new phrasing goes to validation and one to test. That tests what a course Q&A bot really needs: answering a known fact when a student asks it differently. A fact split holds out whole facts instead, which tests whether the model can answer things it never learned. A leakage check makes sure no question appears in two splits.

if strategy == "paraphrase":
    for f in sorted(facts, key=lambda x: x.id):
        qs = list(f.questions)
        rng.shuffle(qs)
        if len(qs) >= 4:
            out["test"].append(rec(f, qs[0]))
            out["val"].append(rec(f, qs[1]))
            out["train"].extend(rec(f, q) for q in qs[2:])
        elif len(qs) == 3:
            out["test"].append(rec(f, qs[0]))
            out["train"].extend(rec(f, q) for q in qs[1:])
$ lora-qa build-data data/raw/cs_student_qa.jsonl
{ "facts": 82, "strategy": "paraphrase", "rows": {"train": 164, "val": 82, "test": 82}, "dropped": {} }

Step 3: Format prompts and mask the question tokens

Every example becomes a short prompt followed by the answer. The model should learn to produce the answer, not to repeat the question, so the loss is computed only on the answer tokens and the end-of-sequence token. Prompt positions get the label -100, which PyTorch’s cross-entropy ignores. Learning the end token is what teaches the bot to stop after a few words.

def encode_example(tokenizer, question: str, answer: str, max_len: int) -> dict:
    """Return input_ids and labels where only answer tokens (+EOS) are learned."""
    prompt_ids = tokenizer(format_prompt(question), add_special_tokens=False)["input_ids"]
    answer_ids = tokenizer(normalise_space(answer), add_special_tokens=False)["input_ids"]
    eos = tokenizer.eos_token_id
    if eos is None:
        raise ValueError("tokenizer needs an eos_token")
    answer_ids = answer_ids + [eos]
    if len(answer_ids) >= max_len:
        answer_ids = answer_ids[: max_len - 2] + [eos]
        prompt_ids = prompt_ids[-1:]
    budget = max_len - len(answer_ids)
    if len(prompt_ids) > budget:
        prompt_ids = prompt_ids[-budget:]  # keep the end of the prompt (the question)
    input_ids = prompt_ids + answer_ids
    labels = [IGNORE_INDEX] * len(prompt_ids) + answer_ids
    return {"input_ids": input_ids, "labels": labels}

Step 4: Validate the config before loading a model

Nothing is more frustrating than a run that crashes after 20 minutes because of a typo. TrainConfig is a dataclass loaded from YAML. It rejects unknown keys with a suggestion (lora_rank becomes “did you mean lora_r?”), checks every range and reports all problems at once. It also warns about risky but legal values, such as an unusual lora_alpha / lora_r ratio.

# Laptop CPU: SmolLM2-135M-Instruct, about 2-3 minutes on an 8-core laptop.
base_model: HuggingFaceTB/SmolLM2-135M-Instruct
data_dir: data/processed
max_seq_len: 96
lora_r: 16
lora_alpha: 32
lora_dropout: 0.05
target_modules: [q_proj, k_proj, v_proj, o_proj, gate_proj, up_proj, down_proj]
learning_rate: 0.0005
batch_size: 8
grad_accum_steps: 1
epochs: 6
warmup_ratio: 0.05
eval_every: 20
seed: 42
device: cpu
dtype: float32
output_dir: outputs/smollm2-135m-lora
$ lora-qa check-config bad.yaml
Invalid config:
  - unknown key 'learnig_rate' (did you mean 'learning_rate'?)

Step 5: Add LoRA adapters with PEFT

The Hugging Face PEFT library injects the adapters. We first check that the requested target_modules actually exist in the model, because module names differ between architectures. SmolLM2 and Qwen use q_proj, k_proj, v_proj and o_proj for attention and gate_proj, up_proj and down_proj for the MLP.

def add_lora(model, cfg: TrainConfig):
    """Freeze the base model and inject trainable low-rank adapters."""
    from peft import LoraConfig, get_peft_model

    names = {n.rsplit(".", 1)[-1] for n, _ in model.named_modules()}
    missing = [m for m in cfg.target_modules if m not in names and m != "all-linear"]
    if missing:
        raise ValueError(f"target_modules {missing} not found in model. Available linear layers include: "
                         + ", ".join(sorted(n for n in names if n.endswith("proj"))[:12]))
    lora_cfg = LoraConfig(
        r=cfg.lora_r,
        lora_alpha=cfg.lora_alpha,
        lora_dropout=cfg.lora_dropout,
        target_modules=cfg.target_modules if cfg.target_modules != ["all-linear"] else "all-linear",
        bias=cfg.lora_bias,
        task_type="CAUSAL_LM",
    )
    return get_peft_model(model, lora_cfg)

The two settings you will tune most are the rank r (how much the adapter can learn) and lora_alpha (a scaling factor; the update is multiplied by alpha / r). A ratio of 1 to 2 is a safe default. The PEFT LoRA guide explains the other options.

Step 6: Write the training loop

Instead of hiding everything behind the Trainer class, train.py uses a short PyTorch loop you can read in one sitting: AdamW on the trainable parameters only, linear warmup and decay, gradient clipping, optional gradient accumulation, and validation perplexity every few steps. The heart of it looks like this:

for batch in batches(train_ex, cfg.batch_size, tok.pad_token_id, True, rng):
    batch = {k: v.to(device) for k, v in batch.items()}
    loss = model(**batch).loss / cfg.grad_accum_steps
    loss.backward()
    running.append(loss.item() * cfg.grad_accum_steps)
    micro += 1
    if micro % cfg.grad_accum_steps:
        continue
    torch.nn.utils.clip_grad_norm_(model.parameters(), cfg.max_grad_norm)
    opt.step()
    sched.step()
    opt.zero_grad(set_to_none=True)

Run it:

lora-qa train --config configs/cpu-smollm2-135m.yaml
Terminal output while you fine tune LLM with LoRA on a CPU: SmolLM2-135M training log, base vs LoRA comparison table and answers from the merged model
A real CPU run: about two minutes of training, then the before/after table and the merged model answering.

This is what it looks like to fine tune LLM with LoRA on a laptop. On an 8-core CPU, 126 steps (6 epochs over 164 examples) took 2 minutes 17 seconds. Training loss fell from 2.3 to about 0.01, and validation perplexity from 2.98 to 1.27. Watch that validation number: if it starts rising while the training loss keeps falling, the model is memorising rather than learning, and you should stop earlier or add data.

Step 7: Evaluate with perplexity and exact match

A fine-tuned model that “feels better” is not a result. You need numbers, and you need the base model’s numbers to compare with. evaluate.py computes three metrics on the test set:

  • Perplexity on the answer tokens: the exponential of the average loss. Lower means the model finds the correct answer less surprising. 1.0 would be perfect certainty.
  • Exact match: the generated answer, normalised SQuAD-style (lowercase, no punctuation or articles), must equal the reference. ^ and + are kept so “O(n^2)” and “B+ tree” stay meaningful.
  • Token F1: partial credit based on word overlap, so “Dijkstra algorithm” still earns something against “Dijkstra’s algorithm”.
def normalise_answer(text: str) -> str:
    """SQuAD-style normalisation: lowercase, drop punctuation, articles and extra spaces.

    ``^`` and ``+`` are kept so that "O(n^2)" and "B+ tree" stay meaningful.
    """
    t = str(text).lower().strip()
    t = t.replace("’", "'")
    t = t.translate(_PUNCT)
    t = _ARTICLES.sub(" ", t)
    return " ".join(t.split())


def exact_match(prediction: str, reference: str) -> float:
    return float(normalise_answer(prediction) == normalise_answer(reference))


def token_f1(prediction: str, reference: str) -> float:
    p = normalise_answer(prediction).split()
    r = normalise_answer(reference).split()
    if not p and not r:
        return 1.0
    if not p or not r:
        return 0.0
    common = sum((Counter(p) & Counter(r)).values())
    if common == 0:
        return 0.0
    precision, recall = common / len(p), common / len(r)
    return 2 * precision * recall / (precision + recall)
lora-qa compare --base-model HuggingFaceTB/SmolLM2-135M-Instruct \
    --adapter outputs/smollm2-135m-lora/adapter --out-dir outputs/eval-smollm2

Step 8: Merge the adapter and export the model

For sharing or deployment, fold the adapter into the base weights with PEFT’s merge_and_unload() and save a normal Transformers model. A test in the repo checks that the merged model produces the same logits as base + adapter, so you know the merge is lossless.

def merge_adapter(base_model: str, adapter: str, out_dir: str, dtype: str = "float32") -> dict:
    from peft import PeftModel

    base = load_base_model(base_model, dtype, "cpu")
    merged = PeftModel.from_pretrained(base, adapter).merge_and_unload()
    tok = load_tokenizer(adapter if Path(adapter, "tokenizer_config.json").exists() else base_model)
    out = Path(out_dir)
    out.mkdir(parents=True, exist_ok=True)
    merged.save_pretrained(out, safe_serialization=True)
    tok.save_pretrained(out)
    size = sum(f.stat().st_size for f in out.glob("*.safetensors"))
    info = {"base_model": base_model, "adapter": adapter, "out_dir": str(out),
            "safetensors_mb": round(size / 1e6, 2)}
    (out / "merge_info.json").write_text(json.dumps(info, indent=2))
    return info
$ lora-qa merge --base-model HuggingFaceTB/SmolLM2-135M-Instruct \
    --adapter outputs/smollm2-135m-lora/adapter --out outputs/smollm2-135m-merged
$ lora-qa ask "Which order does a stack follow?" "Who created Python?" --model outputs/smollm2-135m-merged
Q: Which order does a stack follow?
A: LIFO

Q: Who created Python?
A: Guido van Rossum

Before fine-tuning, the same base model answered “A stack follows the order of operations.” The adapter file is 8.7 MB, and the merged SmolLM2 model is 538 MB in safetensors format.

Results: What Happens When You Fine Tune LLM with LoRA

All numbers below come from real CPU runs with seed 42. The full logs, predictions and tables are in the results folder of the repository.

Model (82 test questions phrased in new ways)Trainable paramsTrain time (CPU)PerplexityExact matchToken F1
SmolLM2-135M-Instruct, base0–66.881.2%10.0%
SmolLM2-135M + LoRA (r=16, 6 epochs)4.88M (3.5%)2 min 17 s1.4272.0%73.2%
Qwen2.5-0.5B-Instruct, base0–19,259*1.2%14.2%
Qwen2.5-0.5B + LoRA (r=16, 4 epochs)2.16M (0.44%)2 min 11 s1.8357.3%62.2%

* The base Qwen model has never seen this prompt template, so it gives almost zero probability to the end-of-answer token. Perplexity includes that token on purpose, because learning when to stop is part of the task.

Fine tune LLM with LoRA results chart: exact match and token F1 before and after LoRA for SmolLM2-135M and Qwen2.5-0.5B, plus an unseen-facts test
Before vs after on questions phrased in new ways, and the honest unseen-facts check.

What the numbers tell you, honestly:

  • LoRA works, and fast. With 3.5% of the weights trainable and two minutes of CPU time, exact match on new phrasings jumped by about 71 points. Per topic, the bot scored 90% on Python questions and 62% on OS and DBMS.
  • Bigger is not automatically better. The Qwen config made only 44 optimizer steps (effective batch 16, 4 epochs) against 126 for SmolLM2, so it is under-trained here. More epochs, or a GPU on Colab, is an easy experiment.
  • Mistakes are confusions between similar facts. The bot answered “precision” for recall, “deadlock” for starvation and “stack” for the data structure used by BFS. These are the same mix-ups students make, and they show the model is choosing between learned answers.
  • LoRA does not add new knowledge. With the fact split (12 facts never seen in training), exact match only went from 0% to 10.4%, and most of that was merge sort, which the base model already knew. For unseen questions it confidently guessed a training answer such as “Agile”. To answer facts the model was never trained on, use retrieval (RAG) instead.

Fine Tune LLM with LoRA on Free Google Colab

For Qwen2.5-0.5B or larger models, open the Colab quick-start notebook, switch the runtime to a T4 GPU and run the cells. It clones the repo, builds the data, trains with configs/colab-qwen2.5-0.5b.yaml, compares and merges. The same code runs on CPU and GPU; device: auto picks the GPU when one exists. On Colab you can also try QLoRA with bitsandbytes for 1B to 3B models.

Testing Without Downloading a Model

When you fine tune LLM with LoRA in a serious project, you still need unit tests, but a real LLM is far too big for unit tests and CI. The trick is a tiny randomly initialised Llama-style model (2 layers, 32 hidden units, about 26,000 parameters) with a character-level tokenizer, both created in memory. It has the same module names as SmolLM2 and Qwen, so the real training, evaluation and merge code runs end to end in under a second.

def build_tiny_model(out_dir: str | Path, seed: int = 0, hidden: int = 32, layers: int = 2) -> Path:
    """Save a randomly initialised Llama-style model + tokenizer to ``out_dir``.

    It has the same module names (q_proj, k_proj, v_proj, o_proj) as SmolLM2 and
    Qwen, so the real training code path is exercised in seconds.
    """
    from transformers import LlamaConfig, LlamaForCausalLM

    torch.manual_seed(seed)
    tok = build_tiny_tokenizer()
    cfg = LlamaConfig(
        vocab_size=len(tok), hidden_size=hidden, intermediate_size=hidden * 2,
        num_hidden_layers=layers, num_attention_heads=4, num_key_value_heads=2,
        max_position_embeddings=512, pad_token_id=tok.pad_token_id, eos_token_id=tok.eos_token_id,
        bos_token_id=None, tie_word_embeddings=False,
    )

The 99 tests cover data cleaning and splitting (including leakage), label masking, every config rule, the metrics, a 2-step training smoke test, “only LoRA weights change”, reproducibility with a fixed seed, evaluation, and “the merged model gives the same logits as base + adapter”. GitHub Actions runs them on Python 3.10 to 3.13 with the CPU build of PyTorch.

$ pytest -v
...
============================== 99 passed in 4.46s ==============================
99 pytest tests passing for the fine tune LLM with LoRA Python project using a tiny random model with no downloads
All 99 tests run in about five seconds on a tiny random model, so CI never downloads a real LLM.

Common Errors and Fixes

These are the problems students hit most often the first time they fine tune LLM with LoRA:

ProblemFix
target_modules ['query_key_value'] not found in modelModule names depend on the architecture. The error lists the available projection layers; use those names.
Training loss goes to 0 but test scores stay lowYou are overfitting. Lower the epochs, use a smaller lora_r, or add more phrasings per fact.
Answers run on into long sentencesThe model has not learned the end token yet. Train longer and keep the EOS token in the labels (the default).
float16 training is not supported on CPUUse dtype: float32 on CPU. Use float16 or bfloat16 only on a GPU.
Out of memoryReduce batch_size and increase grad_accum_steps to keep the same effective batch size.

Learning Outcomes for Your Project Report

After you fine tune LLM with LoRA with this project, you can explain these topics confidently in your report and viva:

  • How LLM fine-tuning works and why LoRA trains only a few percent of the parameters
  • Data engineering for LLMs: cleaning, de-duplication, prompt templates, split strategies and leakage checks
  • Label masking and causal language modelling loss in PyTorch
  • Hyperparameters that matter: rank, alpha, learning rate, warmup, epochs and effective batch size
  • Evaluation design: perplexity, exact match, F1, base-vs-fine-tuned comparison and honest generalisation tests
  • Exporting a model by merging adapters, and verifying that the merge is lossless
  • Software engineering for ML: config validation, a CLI, offline tests with a tiny model and CI

Future Scope

Once you can fine tune LLM with LoRA on one dataset, these extensions make the project stronger:

  • Replace the dataset with your own college syllabus or placement-prep questions
  • Run a rank sweep (r = 4, 8, 16, 32) and plot exact match against adapter size
  • QLoRA on Colab for a 1.5B or 3B model, and compare cost against accuracy
  • Combine the fine-tuned bot with retrieval so it can answer facts it was never trained on
  • Serve the merged model with Flask or Gradio, or convert it to GGUF for Ollama
  • Check for catastrophic forgetting by testing general questions before and after fine-tuning

Frequently Asked Questions

Can I fine tune LLM with LoRA without a GPU?

Yes. With a small model such as SmolLM2-135M-Instruct, LoRA training on 164 examples took about two minutes on an 8-core laptop CPU in this project. Qwen2.5-0.5B also trains on a CPU with 16 GB RAM. For models above 1B parameters, use a free Colab or Kaggle GPU.

What is the difference between LoRA and full fine-tuning?

Full fine-tuning updates every weight in the model, which needs a lot of memory. LoRA freezes the original weights and trains two small low-rank matrices per layer, here only 3.5% of the parameters. The adapter is a few megabytes and can be merged back into the model, so inference speed stays the same.

What values should I use for LoRA rank and alpha?

Start with r = 8 or 16 and lora_alpha equal to one or two times r. A higher rank lets the adapter learn more but uses more memory and can overfit small datasets. The config validator in this project warns you when the alpha to rank ratio is unusual.

How many training examples do I need?

For a narrow task with short answers, a few hundred examples can work, as this project shows with 164 training questions. Give each fact several different phrasings, and keep a test set with phrasings the model never saw so your scores are honest.

Should I use fine-tuning or RAG for a college chatbot?

Use fine-tuning to teach a style, a format or a fixed set of facts. Use RAG when answers must come from documents that change or that the model has never seen. In this project, LoRA scored 72% exact match on known facts asked in new ways, but only 10.4% on completely unseen facts, which is exactly the case where RAG helps.

Can I submit this as my final-year project?

Yes. The code is MIT licensed. Train it on your own dataset, add one feature from the future scope list, explain LoRA, the evaluation and your results in the report, and show the before and after table and the 99 passing tests in your viva. The source is on GitHub.

Download the Source Code

The complete project (dataset builder, config validator, LoRA training loop, evaluation, merge/export, the 82-fact student Q&A dataset, real results, a Colab notebook, 99 tests and CI) is on GitHub: GetProjectsIdea/Fine-Tune-LLM-with-LoRA-Python. It is released under the MIT License, so you can use it to fine tune LLM with LoRA for coursework, college projects and your own experiments.

References

Conclusion

You now know how to fine tune LLM with LoRA from start to finish: build a clean dataset without leakage, validate the config, train a few million adapter weights on a CPU, measure the before and after honestly, and merge the result into a model you can share. Just as important, you have seen where fine-tuning stops and retrieval should take over. Clone the repository, swap in your own syllabus questions and see how far a two-minute training run can take your study bot. Happy coding!

Team Get Projects

Contributor & Author
View All Projects →

Contributor at GetProjects.org, sharing open-source codebases, tutorials, and practical software architectures.

0 Discussion Comments

Markdown Supported

Join the Discussion & Code Review

Share architectural feedback, benchmark results, or troubleshooting notes.