🐍 Python Mentor

A QLoRA adapter that teaches DeepSeek-R1-Distill-Qwen-1.5B to explain Python

License Base model Method Library Status

⚠️ This repository contains a PEFT LoRA adapter, not a complete standalone model. To run it you must also load the base model, deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B, and attach this adapter to it.

🧪 Status: educational, resource-constrained experiment. In a small manual evaluation the adapter was fully correct on 3 of 10 questions. It is not production-ready and must not be treated as an authoritative Python reference. See Limitations and Results and Evaluation.


📌 At a Glance

🎯 Task Python programming education: explanations, code walkthroughs, debugging help, small examples
🧠 Base model deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B (Qwen2ForCausalLM)
🔧 Method QLoRA: 4-bit NF4 base model + trainable LoRA adapters, supervised fine-tuning
🧩 Adapter size 18,464,768 trainable parameters (1.0284% of 1,795,552,768)
📚 Training data 1,509 single-turn Python Q&A examples (1,261 train / 248 evaluation)
⏱️ Training 3 epochs, 474 steps, about 37 min 53 s on one NVIDIA Tesla T4 (Google Colab free tier)
📊 Manual evaluation 3 correct, 3 partial, 4 incorrect out of 10 questions (average 2.80 / 5)
🚫 Not claimed Hyperparameter optimization, production accuracy, state-of-the-art performance

🗺️ How the Pieces Fit Together

flowchart LR
    subgraph HUB["🤗 Hugging Face Hub"]
        BASE["Base model<br/>deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"]
        ADP["This repository<br/>LoRA adapter weights"]
    end
    BASE --> LOAD["1. Load base model"]
    ADP --> ATTACH["2. Attach adapter<br/>PeftModel.from_pretrained"]
    LOAD --> ATTACH
    ATTACH --> RUN["Python Mentor<br/>(base + adapter)"]
    RUN --> OUT["Explanations and<br/>Python code examples"]

📑 Table of Contents

  1. Model Overview
  2. Model Details
  3. Uses
  4. Bias, Risks, and Limitations
  5. How to Get Started
  6. Training Data
  7. Training Procedure
  8. Training Hyperparameters
  9. Results and Evaluation
  10. Model Architecture and Technical Specifications
  11. Compute Infrastructure and Software
  12. Environmental Impact
  13. Base Model Attribution and Licensing
  14. Citation and Author Information

Model Overview

Python Mentor is a LoRA adapter that adapts DeepSeek-R1-Distill-Qwen-1.5B toward Python programming education: explaining concepts, walking through code, helping with errors, and giving practical code examples from beginner to advanced level.

It was trained with QLoRA (a 4-bit quantized base model plus trainable LoRA adapters) using supervised fine-tuning on 1,509 Python question-and-answer examples. The work was done on a free-tier Google Colab GPU as a student learning project, and this card documents both the workflow and its limitations.

This repository is This repository is not
✅ A PEFT LoRA adapter (adapter_model.safetensors) ❌ A full standalone model
✅ A way to add Python-tutoring behavior on top of the base model ❌ A hosted inference API (publishing weights does not create one)
✅ A documented baseline from a small, resource-limited experiment ❌ A tuned, benchmarked, or production-level system

Model Details

Model Description

Property Value
Project name Python Mentor
Developed by Shehzee (Hugging Face username) · [To be confirmed: full author name(s)]
Model type LoRA adapter for a causal language model
Base model deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B
Base architecture Qwen2ForCausalLM
Fine-tuning method QLoRA (Quantized Low-Rank Adaptation), supervised fine-tuning
Adapter library / format PEFT / LoRA
Adapter weights adapter_model.safetensors
Adapter configuration adapter_config.json
Language English (natural language), Python (code)
Intended task Python programming education and assistance
License See Base Model Attribution and Licensing

Repository Files

File Purpose
adapter_model.safetensors Trained LoRA adapter weights
adapter_config.json Adapter configuration, including the base-model reference
tokenizer.json, tokenizer_config.json Tokenizer files
chat_template.jinja Chat formatting template
training_args.bin Saved training arguments
README.md This model card

Model Sources


Uses

✅ Direct Use

The adapter is intended to help people learn Python through explanations and practical code examples:

  • Explaining Python concepts (variables, data types, control flow, functions, OOP).
  • Walking through what a short piece of code does.
  • Suggesting possible causes for common errors and showing candidate fixes.
  • Producing small example programs.

Because of the weaknesses documented below, treat every answer as a draft to verify, ideally by running the code and checking the official Python documentation.

🔁 Downstream Use

  • A starting point for further fine-tuning or research on small educational coding assistants.
  • A learning reference for the QLoRA workflow (4-bit loading, LoRA configuration, SFT, adapter publishing) on limited hardware.
  • A component in a demo application, for example a Gradio app on Hugging Face Spaces. Publishing the adapter and deploying an application are separate steps (see Publishing vs. Deployment).

🚫 Out-of-Scope Use

The adapter is not suitable for:

  • Production tutoring or grading systems without human review.
  • Use as an authoritative source for Python behavior, built-in functions, or library APIs.
  • Security-critical, safety-critical, financial, medical, or legal code and decisions.
  • Automatically executing or deploying generated code without review.
  • Any use that depends on the accuracy of larger or more heavily tuned models.

Bias, Risks, and Limitations

🔍 Observed Weaknesses

A small manual evaluation of 10 Python questions (see Results and Evaluation) found:

  • Incorrect explanations of Python variables.
  • Confusion about dictionary iteration.
  • Incorrect or undefined method calls in OOP examples.
  • Incorrect explanations of built-in functions.
  • Incomplete explanations of some Python concepts.

Only 3 of the 10 sampled answers were fully correct.

⚠️ General Limitations

  • Small base model: about 1.5 billion parameters, which limits factual accuracy, reasoning, and consistency.
  • Small training set: 1,509 examples cannot cover Python broadly, and any mistakes in the data can be learned by the model. [To be confirmed: dataset provenance; see Training Data.]
  • Single-turn training only: every training example is one user message followed by one assistant answer, so multi-turn follow-up behavior was not trained.
  • Short answers: training answers average about 58.5 words (maximum 171), so long, detailed explanations are outside the training distribution.
  • Not hyperparameter-tuned: the configuration was a practical baseline, not a proven optimum.
  • Outputs are not verified: the model does not run code. It can state wrong outputs, invent methods or arguments, or produce code that fails.
  • Possible overfitting: validation loss rose in the final epoch, and the published adapter comes from the end of that epoch (see Results and Evaluation).
  • Inherited limitations: the adapter inherits the biases and failure modes of the base model and its training data.

💡 Recommendations

  • Run and test any generated code, and compare explanations with the official Python documentation.
  • Use the model as a study aid alongside other learning resources, not as the only one.
  • Keep a human reviewer in the loop in any educational or professional setting.
  • Do not present outputs as verified facts.

How to Get Started

Requirements

You need the compatible base model and this adapter loaded together.

pip install -U transformers peft accelerate torch
# Optional, only for 4-bit loading on an NVIDIA GPU:
pip install -U bitsandbytes

Inference flow

sequenceDiagram
    participant You
    participant Tok as Tokenizer
    participant Base as Base model
    participant LoRA as LoRA adapter
    You->>Tok: AutoTokenizer.from_pretrained(adapter)
    You->>Base: AutoModelForCausalLM.from_pretrained(base)
    You->>LoRA: PeftModel.from_pretrained(base, adapter)
    LoRA-->>Base: Adapter weights attached
    You->>Tok: apply_chat_template(question)
    Tok->>Base: input_ids
    Base-->>You: generate() returns the answer

Option 1: Load in half precision (FP16)

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

BASE_MODEL = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
ADAPTER_ID = "Shehzee/python-mentor-qlora"  # confirm this matches your repository ID

tokenizer = AutoTokenizer.from_pretrained(ADAPTER_ID)

base = AutoModelForCausalLM.from_pretrained(
    BASE_MODEL,
    torch_dtype=torch.float16,
    device_map="auto",
)
model = PeftModel.from_pretrained(base, ADAPTER_ID)
model.eval()

messages = [
    {"role": "user", "content": "Explain the difference between a list and a tuple in Python."}
]
inputs = tokenizer.apply_chat_template(
    messages,
    add_generation_prompt=True,
    return_tensors="pt",
    return_dict=True,
).to(model.device)

with torch.no_grad():
    output_ids = model.generate(
        **inputs,
        max_new_tokens=512,
        do_sample=True,
        temperature=0.6,
    )

new_tokens = output_ids[0][inputs["input_ids"].shape[1]:]
print(tokenizer.decode(new_tokens, skip_special_tokens=True))

Option 2: Load the base model in 4-bit (lower memory)

This mirrors the quantization settings used for training (NF4, double quantization, FP16 compute).

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

BASE_MODEL = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
ADAPTER_ID = "Shehzee/python-mentor-qlora"  # confirm this matches your repository ID

bnb_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_use_double_quant=True,
    bnb_4bit_compute_dtype=torch.float16,
)

tokenizer = AutoTokenizer.from_pretrained(ADAPTER_ID)
base = AutoModelForCausalLM.from_pretrained(
    BASE_MODEL,
    quantization_config=bnb_config,
    device_map="auto",
)
model = PeftModel.from_pretrained(base, ADAPTER_ID)
model.eval()

Generation then works exactly as in Option 1.

Notes on Usage

  • DeepSeek recommends a sampling temperature between 0.5 and 0.7 for the R1 series to avoid repetition or incoherent output. The example uses 0.6.
  • The adapter must be loaded on the same base model named in adapter_config.json. A different base model will not work correctly.
  • You can optionally merge the adapter into a full-precision copy of the base model with model.merge_and_unload(). Merged weights are a separate artifact and are not provided here.

Publishing vs. Deployment

Uploading this adapter to the Hugging Face Hub only stores and distributes the files. It does not automatically create a hosted inference API.

flowchart TD
    P["Adapter published on the Hub"] --> Q{"How do you want to run it?"}
    Q -->|"On your own machine"| L["Local inference<br/>load base model + adapter"]
    Q -->|"As a shared service"| S["Inference Endpoint or Space<br/>needs hardware, may cost money"]
    P -.->|"does NOT create"| X["A free, always-on<br/>hosted inference API"]

A free CPU Space may be too slow for comfortable use with this base model, and GPU hardware depends on the options and pricing available for Spaces. [To be confirmed: whether a Space or endpoint has been created for this project.]


Training Data

Dataset Summary

Property Value
Initial size 1,510 examples
Removed 1 malformed example (PYM-000757, a Debugging example)
Final size 1,509 examples
Training examples 1,261
Evaluation examples 248
Format JSONL, with a split column assigning each record to train or evaluation
Fields per example id, category, difficulty, messages (one user message, one assistant message), split
Categories 15
Difficulty levels Beginner 602 · Intermediate 549 · Advanced 358
flowchart TD
    A["1,510 JSONL examples"] --> B["Structure validation<br/>1 malformed example removed"]
    B --> C["1,509 examples<br/>15 categories, 3 difficulty levels"]
    C --> D["split column"]
    D --> E["1,261 training"]
    D --> F["248 evaluation"]
    E --> G["Chat-template tokenization<br/>loss only on the assistant answer"]
    F --> G
    G --> H["QLoRA training<br/>evaluation after every epoch"]
📂 Examples per category (click to expand)
Category Total Train Evaluation
Python Fundamentals 200 180 20
Debugging 129 111* 18
Data Structures 110 99 11
Functions 120 101 19
Problem Solving 120 96 24
Control Flow 100 85 15
Object-Oriented Programming 100 85 15
Code Explanation 100 80 20
Output Prediction 90 72 18
Advanced Python 80 64 16
Exception Handling 80 64 16
Code Quality 70 56 14
File Handling 70 56 14
Modules and Packages 70 56 14
Testing 70 56 14
Total 1,509 1,261 248

*Derived figure: the notebook's per-split table was computed before the malformed example was removed and lists Debugging as 112 train and 18 evaluation. The removed example was a training example (the evaluation count stayed at 248 and Debugging dropped from 130 to 129), so Debugging has 111 training examples after removal.

Preprocessing and Quality Checks

Check Result
Malformed records 1 found and removed (PYM-000757)
Every example has exactly 2 messages ✅ asserted in the notebook
Exact duplicate message records 0
Missing messages or missing column values 0
Answers containing fenced code blocks 1,405 of 1,509 (93.11%)
Answer length mean 58.5 words, median 56, maximum 171
Tokenized length (chat template) mean 133.2 tokens, maximum 357; 0 examples above 512

Because no example exceeds 512 tokens, no training example was truncated. These checks cover structure and length, not correctness: they do not verify that the explanations or code in the dataset are technically accurate.

Formatting for Training

Each example was turned into a chat-formatted sequence with the tokenizer's chat template. The prompt (user turn plus assistant prefix) is masked with label -100, so the loss is computed only on the assistant's answer tokens. Batches are padded with DataCollatorForSeq2Seq (pad_to_multiple_of=8).

Provenance

  • Source and generation method: [To be confirmed. State exactly how the examples were created (for example, which AI tool or tools helped generate them, and what human review was done), and confirm that the terms of use of those tools allow publishing a model trained on this data.]
  • Dataset availability: [To be confirmed: whether the dataset is published, and under which license.]
  • Split method: the dataset file already carried a split column; the notebook used it as given. [To be confirmed: how the split was created.]

Training Procedure

flowchart TD
    A["Load base model<br/>4-bit NF4, double quantization, FP16 compute"] --> B["prepare_model_for_kbit_training<br/>gradient checkpointing on"]
    B --> C["Attach LoRA adapters<br/>r=16, alpha=32, dropout=0.05"]
    C --> D["Freeze base weights<br/>train adapter parameters only"]
    D --> E["Hugging Face Trainer<br/>3 epochs, effective batch size 8"]
    E --> F["Evaluate after every epoch"]
    F --> G["Save final adapter and tokenizer<br/>python_mentor_qlora/final_adapter"]
    G --> H["Export and publish to the Hub"]

The model was trained with 4-bit QLoRA supervised fine-tuning:

  1. Load deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B in 4-bit.
  2. Prepare the quantized model for k-bit training (with gradient checkpointing).
  3. Attach LoRA adapters to the attention and feed-forward projection layers.
  4. Keep the original weights frozen and train only the adapter parameters.
  5. Train on the 1,261 training examples for 3 epochs with the Hugging Face Trainer, evaluating on the 248 evaluation examples after every epoch.
  6. Save the adapter and tokenizer to python_mentor_qlora/final_adapter and export it for publishing.

ℹ️ The notebook also imports TRL's SFTTrainer, but the training run itself used the standard transformers.Trainer with the tokenization described above.

Quantization Settings

Setting Value
Base-model precision during training 4-bit
Quantization data type nf4 (NormalFloat4)
Double quantization Enabled (bnb_4bit_use_double_quant=True)
Compute dtype torch.float16
GPU memory after loading the 4-bit model 1.52 GiB allocated of 14.56 GiB total

No hyperparameter tuning experiments were conducted. The configuration below was a practical baseline for a limited-resource project and is not claimed to be optimal.

LoRA Configuration

flowchart LR
    X["Input x"] --> W["Frozen weight W<br/>(4-bit)"]
    X --> A["Trainable A<br/>rank r = 16"]
    A --> B["Trainable B"]
    W --> S(("+"))
    B -->|"scaled by alpha / r = 2"| S
    S --> Y["Output"]
Parameter Value
Rank (r) 16
Alpha 32 (scaling factor alpha / r = 2)
Dropout 0.05
Bias none
Task type CAUSAL_LM
Target modules q_proj, k_proj, v_proj, o_proj, gate_proj, up_proj, down_proj
Trainable parameters 18,464,768
Total parameters 1,795,552,768
Trainable fraction 1.0284%
Base-model weights Frozen

Training Hyperparameters

Hyperparameter Value
Learning rate 2e-4
Epochs 3
Per-device training batch size 1
Per-device evaluation batch size 1
Gradient accumulation steps 8
Effective batch size 8
Maximum sequence length 512
FP16 Enabled
Gradient checkpointing Enabled
Evaluation strategy Every epoch
Checkpoint saving Every epoch, at most 2 kept
Logging Every 10 steps (report_to="none")
Optimizer Not set explicitly: the Trainer default was used
Learning-rate scheduler Not set explicitly: the Trainer default was used
Warmup, weight decay, random seed Not set explicitly: Trainer defaults were used

The resolved optimizer and scheduler values are stored in training_args.bin in this repository.


Results and Evaluation

Training Summary

Metric Value
Training status Completed successfully
Total training runtime 0:37:52.91 (about 37 minutes 53 seconds)
Training steps 474 (3 epochs × 158 steps)
Final aggregate training loss 1.0332
Training throughput 1.664 samples/s, 0.209 steps/s
Total FLOPs reported by Trainer 4,469,360 GF

Loss by Epoch

Epoch Training Loss Validation Loss
1 1.158235 1.258784
2 0.911144 1.247109
3 0.728667 1.328831
xychart-beta
    title "Loss by epoch: training (first line) vs validation (second line)"
    x-axis ["Epoch 1", "Epoch 2", "Epoch 3"]
    y-axis "Loss" 0.6 --> 1.4
    line [1.158235, 0.911144, 0.728667]
    line [1.258784, 1.247109, 1.328831]

Interpreting the Loss Curves

Training loss decreased in every epoch (1.158 to 0.729). Validation loss improved slightly from epoch 1 to epoch 2 (1.259 to 1.247) and then increased in epoch 3 (to 1.329).

A widening gap between training and validation loss often indicates overfitting, so epoch 3 may have started fitting the training set more closely than it generalized. This is only a possible explanation: no further experiments were run to isolate the cause, and loss on a small validation set is a noisy signal.

Which weights are published: the notebook did not enable best-checkpoint loading, and the adapter was saved with trainer.save_model(...) after training finished. The published adapter therefore reflects the end of epoch 3, not the epoch with the lowest validation loss (epoch 2).

None of this shows that the configuration is optimized. Fewer epochs, a different learning rate, or other settings might have worked better, but they were not tested.

Manual Evaluation

A small manual assessment of 10 Python questions was carried out on the fine-tuned model. Each response was rated Correct (5), Partial (3), or Incorrect (1).

pie showData
    title Manual evaluation outcomes (10 questions)
    "Fully correct" : 3
    "Partially correct" : 3
    "Incorrect" : 4
# Topic Result Score
1 Variables ❌ Incorrect 1
2 Data Types 🟡 Partial 3
3 Data Structures 🟡 Partial 3
4 Functions ✅ Correct 5
5 Loops ❌ Incorrect 1
6 Conditions ✅ Correct 5
7 OOP ❌ Incorrect 1
8 Exception Handling 🟡 Partial 3
9 Debugging ❌ Incorrect 1
10 Problem Solving ✅ Correct 5
Average 2.80 / 5
Outcome Count Share
Fully correct 3 30%
Partially correct 3 30%
Incorrect 4 40%

Limitations of this evaluation:

  • Ten questions is a very small sample, so the numbers are indicative only and carry high uncertainty.
  • It is a manual assessment (one question per topic), not a standardized or comprehensive benchmark.
  • No automated code-execution tests were part of this assessment.
  • No comparison with other models was performed, and none is claimed.
  • The grader and the exact question wording are [To be confirmed].

This card makes no claim of production-level accuracy, state-of-the-art performance, or superiority over any other model.


Model Architecture and Technical Specifications

Property Value
Base model deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B
Base architecture Qwen2ForCausalLM (28 Transformer layers)
Adapter type LoRA (PEFT)
Adapter rank / alpha / dropout 16 / 32 / 0.05
Adapted layers q_proj, k_proj, v_proj, o_proj, gate_proj, up_proj, down_proj
Trainable parameters 18,464,768 (1.0284% of 1,795,552,768)
Objective Causal language modeling, loss on assistant answer tokens only
Maximum training sequence length 512 tokens
Weight format safetensors

Compute Infrastructure and Software

Hardware

Component Details
Environment Google Colab (free tier)
GPU NVIDIA Tesla T4 (14.56 GiB reported by PyTorch)
Training mode 4-bit QLoRA
Training time 0:37:52.91

The notebook workflow as a whole took around two days because of free-tier GPU availability and session limits. The student-level compute budget is the reason no hyperparameter search was run.

Software (from the training notebook)

Library Version
Python 3.13
PEFT 0.21.2
Transformers 5.22.1
PyTorch 2.14.1+cu130
Accelerate 1.15.0
Datasets 4.8.5
bitsandbytes 0.50.2
TRL 1.19.0 (installed and imported; the training run used transformers.Trainer)

Environmental Impact

Carbon emissions were not measured for this project, and no energy or emissions figure is claimed. The only verifiable facts are:

  • Hardware: NVIDIA Tesla T4 on Google Colab.
  • Training time: 0:37:52.91.
  • Cloud region: [To be confirmed: not recorded].

Emissions can be estimated with the Machine Learning Impact calculator once the region is known. No estimate is included here.


Base Model Attribution and Licensing

Base Model

This adapter is built on deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B, released by DeepSeek. According to the base model's card, it is distilled from DeepSeek-R1, and its upstream base model is Qwen2.5-Math-1.5B.

License Information (checked against the official base-model repository)

  • The official base-model repository lists its license as MIT.
  • The base model's card states that the code repository and model weights are licensed under the MIT License, and that DeepSeek-R1 series models support commercial use and derivative works, including distillation.
  • The card also notes that the Qwen-based distilled models (including the 1.5B model) are derived from the Qwen 2.5 series, which was originally licensed under Apache 2.0, and were then fine-tuned with 800k samples curated with DeepSeek-R1.

Please read the LICENSE file and model card in the official base-model repository yourself, because they are the authoritative source and could change.

License of This Adapter

The metadata declares license: mit in line with the base model. [To be confirmed by the author: that MIT is the intended license for the adapter weights, and that the terms of use of the tools used to create the training data permit this release.] If you redistribute merged weights, keep the base model's license and attribution with them.


Citation and Author Information

Base Model Citation

If you use the base model, please cite the DeepSeek-R1 paper (see the arXiv page for the complete author list):

@misc{deepseekai2025deepseekr1incentivizingreasoningcapability,
  title         = {DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning},
  author        = {DeepSeek-AI},
  year          = {2025},
  eprint        = {2501.12948},
  archivePrefix = {arXiv},
  primaryClass  = {cs.CL},
  url           = {https://arxiv.org/abs/2501.12948}
}

Citing This Adapter

@misc{python_mentor_qlora,
  title        = {Python Mentor: a QLoRA adapter for DeepSeek-R1-Distill-Qwen-1.5B},
  author       = {[To be confirmed: author name(s)]},
  year         = {[To be confirmed]},
  howpublished = {\url{https://huggingface.co/Shehzee/python-mentor-qlora}}
}

Authors and Contact

  • Authors: Shehzee (Hugging Face username) · [To be confirmed: full name(s)]
  • Contact: [To be confirmed]

Framework Versions

  • PEFT 0.21.2
Downloads last month
-
Inference Providers NEW
This model isn't deployed by any Inference Provider. 🙋 Ask for provider support

Model tree for Shehzee/python-mentor-qlora

Adapter
(345)
this model

Paper for Shehzee/python-mentor-qlora