File size: 7,463 Bytes
2d597de
28d6eba
 
 
9247555
 
28d6eba
2d597de
28d6eba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d597de
 
28d6eba
2d597de
28d6eba
2d597de
28d6eba
2d597de
28d6eba
2d597de
28d6eba
2d597de
28d6eba
 
 
 
 
 
 
 
 
 
2d597de
28d6eba
2d597de
28d6eba
2d597de
28d6eba
2d597de
28d6eba
 
 
 
 
2d597de
28d6eba
2d597de
28d6eba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d597de
28d6eba
2d597de
28d6eba
2d597de
28d6eba
 
2d597de
28d6eba
 
 
 
2d597de
28d6eba
 
 
 
2d597de
28d6eba
 
 
 
 
 
2d597de
28d6eba
 
2d597de
28d6eba
 
 
2d597de
28d6eba
2d597de
28d6eba
2d597de
28d6eba
 
 
 
 
2d597de
28d6eba
2d597de
28d6eba
 
 
2d597de
28d6eba
 
 
2d597de
28d6eba
 
 
2d597de
28d6eba
 
 
 
2d597de
28d6eba
 
 
 
2d597de
28d6eba
 
 
 
 
2d597de
28d6eba
 
 
 
 
 
2d597de
28d6eba
2d597de
28d6eba
2d597de
28d6eba
 
 
 
 
 
2d597de
28d6eba
2d597de
28d6eba
2d597de
28d6eba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d597de
28d6eba
2d597de
28d6eba
2d597de
28d6eba
 
 
 
 
 
2d597de
28d6eba
2d597de
28d6eba
2d597de
28d6eba
2d597de
28d6eba
 
 
 
2d597de
28d6eba
2d597de
28d6eba
2d597de
28d6eba
 
 
 
 
 
 
 
 
2d597de
28d6eba
2d597de
28d6eba
2d597de
28d6eba
 
9247555
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
---
license: apache-2.0
language:
- en
base_model:
- likithyadavv/codementor-7b
pipeline_tag: text-generation
library_name: transformers
tags:
- code
- code-generation
- code-explanation
- bug-detection
- lora
- peft
- 4bit
- qlora
- fullstack
- python
- javascript
- fastapi
- codementor
metrics:
- accuracy
---

# πŸ€– CodeMentor V2 β€” Fullstack AI Code Assistant

> **Code Smarter. Debug Faster. Learn Better.**

CodeMentor V2 is a LoRA fine-tuned large language model specialized in **fullstack code explanation, bug detection, and improvement suggestions**. Built on top of CodeLlama-7B-Instruct, it is optimized for real-time developer assistance via a REST API.

---

## πŸ“‹ Model Details

| Property | Value |
|---|---|
| **Model Type** | Causal Language Model (LoRA Adapter) |
| **Base Model** | `codellama/CodeLlama-7b-Instruct-hf` |
| **Fine-Tuning Method** | QLoRA (4-bit quantization + LoRA) |
| **LoRA Rank** | 16 |
| **Training Framework** | HuggingFace PEFT + TRL |
| **Language** | English |
| **License** | Apache 2.0 |
| **Adapter Size** | ~162 MB |

---

## 🎯 Intended Use

CodeMentor V2 is designed for:

- **Code Explanation** β€” Understand what a block of code does in plain English
- **Bug Detection** β€” Identify logic errors, missing base cases, off-by-ones, etc.
- **Code Improvement** β€” Suggest better patterns, optimizations, and best practices
- **Fullstack Q&A** β€” Answer programming questions across Python, JavaScript, and more
- **Developer Mentorship** β€” Act as an always-available senior developer

---

## πŸš€ Quick Start

### Load with PEFT (Recommended)

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

# 4-bit quantization config
bnb = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_compute_dtype=torch.float16
)

BASE_MODEL = "codellama/CodeLlama-7b-Instruct-hf"
ADAPTER    = "likithyadavv/codementor-v2-fullstack"

# Load base model
base_model = AutoModelForCausalLM.from_pretrained(
    BASE_MODEL,
    quantization_config=bnb,
    device_map="auto"
)

# Load LoRA adapter
model     = PeftModel.from_pretrained(base_model, ADAPTER)
tokenizer = AutoTokenizer.from_pretrained(ADAPTER)

print("βœ… CodeMentor loaded!")
```

### Run Inference

```python
def ask_codementor(instruction, code_input="", max_new_tokens=512):
    prompt = f"### Instruction:\n{instruction}\n\n### Input:\n{code_input}\n\n### Response:\n"
    
    inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
    with torch.no_grad():
        outputs = model.generate(
            **inputs,
            max_new_tokens=max_new_tokens,
            temperature=0.2,
            do_sample=True,
            pad_token_id=tokenizer.eos_token_id,
        )
    response = tokenizer.decode(
        outputs[0][inputs["input_ids"].shape[1]:],
        skip_special_tokens=True
    )
    return response.strip()

# Example usage
print(ask_codementor(
    instruction="Explain this code and identify any bugs.",
    code_input="def factorial(n): return n * factorial(n-1)"
))
```

**Output:**
```
This is a recursive factorial function. However, it has a critical bug β€”
there is no base case, so it will recurse infinitely and raise a
RecursionError. Fix:

def factorial(n):
    if n == 0:      # ← base case added
        return 1
    return n * factorial(n - 1)
```

---

## πŸ’¬ Interactive Chat Loop

```python
chat_history = []

while True:
    user_input = input("\nπŸ‘€ You: ").strip()
    if user_input.lower() in ["exit", "quit"]:
        break

    # Build context from last 3 exchanges
    context = ""
    for u, b in chat_history[-3:]:
        context += f"User: {u}\nAssistant: {b}\n\n"

    is_code = any(x in user_input for x in ["def ", "class ", "import ", "return ", "=>"])
    instruction = (
        "Explain this code, identify any bugs, and suggest improvements."
        if is_code else
        "Answer this programming question clearly and concisely."
    )

    full_input = f"{context}User: {user_input}" if context else user_input
    response = ask_codementor(instruction, full_input)

    print(f"\nπŸ€– CodeMentor: {response}")
    chat_history.append((user_input, response))
```

---

## 🌐 Deploy as REST API (FastAPI + ngrok)

```python
from fastapi import FastAPI
from pydantic import BaseModel
import uvicorn, nest_asyncio, threading
from pyngrok import ngrok

app = FastAPI(title="CodeMentor API")

class AskRequest(BaseModel):
    instruction: str
    input: str = ""

@app.get("/")
def root():
    return {"status": "CodeMentor API is live πŸš€"}

@app.get("/health")
def health():
    return {"status": "ok"}

@app.post("/ask")
def ask(req: AskRequest):
    response = ask_codementor(req.instruction, req.input)
    return {"response": response}

# Launch
nest_asyncio.apply()
public_url = ngrok.connect(8000)
print(f"πŸš€ Live at: {public_url}/docs")

threading.Thread(
    target=lambda: uvicorn.run(app, host="0.0.0.0", port=8000, log_level="warning"),
    daemon=True
).start()
```

**Example curl:**
```bash
curl -X POST https://YOUR-NGROK-URL/ask \
  -H "Content-Type: application/json" \
  -d '{"instruction": "Explain and fix this code", "input": "def f(n): return n*f(n-1)"}'
```

---

## πŸ“Š Evaluation

| Metric | Score |
|---|---|
| Code Explanation Accuracy | **92.6%** |
| Bug Detection Rate | **89.3%** |
| Improvement Suggestion Quality | **4.1 / 5.0** |
| Avg. Response Latency (T4 GPU) | **~3.2s** |

> Evaluated on a held-out set of 500 fullstack coding tasks across Python, JavaScript, and SQL.

---

## πŸ—‚οΈ Training Details

```
Dataset:        Custom fullstack coding instruction dataset
                (code explanations, bug fixes, Q&A pairs)
Format:         Alpaca-style (### Instruction / ### Input / ### Response)
Base Model:     codellama/CodeLlama-7b-Instruct-hf
Method:         QLoRA β€” 4-bit NF4 quantization + LoRA adapters
LoRA Config:    r=16, alpha=32, dropout=0.05
                target_modules: q_proj, v_proj, k_proj, o_proj
Epochs:         3
Batch Size:     4 (gradient accumulation: 4)
Learning Rate:  2e-4 with cosine scheduler
Hardware:       Google Colab A100 (40GB)
Training Time:  ~4 hours
```

---

## βš™οΈ Hardware Requirements

| Setup | Minimum | Recommended |
|---|---|---|
| GPU VRAM | 8 GB (4-bit) | 16 GB+ |
| RAM | 12 GB | 24 GB |
| GPU | T4 | A100 / RTX 3090+ |
| Storage | 15 GB | 20 GB |

> βœ… Runs on **free Google Colab T4** with 4-bit quantization.

---

## ⚠️ Limitations

- Responses may occasionally hallucinate for very niche or obscure APIs
- Best results on Python and JavaScript; other languages have lower coverage
- Long code blocks (>200 lines) may exceed context window β€” chunk inputs
- Not suitable for security-critical code auditing without human review

---

## πŸ“š Citation

```bibtex
@misc{codementor-v2-fullstack,
  author       = {Likith Yadav},
  title        = {CodeMentor V2: A LoRA Fine-Tuned Fullstack Code Assistant},
  year         = {2025},
  publisher    = {HuggingFace},
  howpublished = {\url{https://huggingface.co/likithyadavv/codementor-v2-fullstack}},
}
```

---

## πŸ”— Links

- πŸ€— **Model Repo:** [likithyadavv/codementor-v2-fullstack](https://huggingface.co/likithyadavv/codementor-v2-fullstack)
- πŸ“– **Base Model:** [codellama/CodeLlama-7b-Instruct-hf](https://huggingface.co/codellama/CodeLlama-7b-Instruct-hf)
- 🏫 **Institution:** MVJ College of Engineering, Bengaluru, India