Given a LeetCode-style problem statement, its sample input/output, and an algorithm tag, generates a working Python solution.
PROBLEM: Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
ALGORITHM: Hash Map
OUTPUT (Python):
def twoSum(nums, target):
seen = {}
for i, n in enumerate(nums):
if target - n in seen:
return [seen[target - n], i]
seen[n] = i
DoRA splits each adapted weight into magnitude + direction and trains both, which follows full fine-tuning's behavior more closely than plain LoRA — important for code where small precision errors break correctness outright. 4-bit NF4 quantization of the frozen base keeps this affordable on a single 48GB GPU.
Concretely, versus the plain-QLoRA v1 release of this suite: DoRA adds a per-column
trainable magnitude vector on top of the usual low-rank direction update, so the
adapter can rescale a feature's importance instead of only rotating it. On a code
task where a single wrong operator or dropped edge case fails the whole solution,
that closer match to full fine-tuning's update pattern showed up as fewer
near-miss failures during our own qualitative review, at the same LoRA rank and
VRAM budget.
python
1# training-side PEFT config (see build_language_datasets.py / trainer script for full pipeline)2from peft import LoraConfig
34peft_config = LoraConfig(5 r=16,6 lora_alpha=32,7 lora_dropout=0.0,8 target_modules=["q_proj","k_proj","v_proj","o_proj","gate_proj","up_proj","down_proj"],9 use_dora=True,# <- this is what makes it QDoRA, not QLoRA10 task_type="CAUSAL_LM",11)
Benchmarks (free, reproducible)
Run benchmark_suite.py from the deployment kit to reproduce. All numbers are pass@1 unless noted.
from leetcode-codegen-python test split, exact I/O match
Tokens/sec (fp16, GPU)
Python
—
—
latency benchmark
Tokens/sec (GGUF q4_k_m)
Python
—
—
latency benchmark
Numbers are intentionally left blank in this template — benchmark_suite.py fills a results/leetcode-python-qwen25-coder-7b.json file and this table should be regenerated from it.
Intended use
Drop-in solution generator for Python coding-practice tools, interview-prep apps, and automated code-review sandboxes for algorithmic problems.
Direct use
Give a problem statement (+ optional algorithm hint), get back a Python function/class implementing it.
Downstream use
Feed output into an automated grader (run against test cases), a code-review bot, or a practice-app "show solution" feature.
Out of scope
Production system design or non-algorithmic code (this model specializes narrowly on LeetCode-style problems)
Security-critical code without human review
Guaranteed-optimal complexity — treat output as a strong first draft, not a proof
Quickstart
Option A — Transformers + PEFT
python
1from transformers import AutoModelForCausalLM, AutoTokenizer
2from peft import PeftModel
3import torch
45base_model ="unsloth/Qwen2.5-Coder-7B-Instruct"6adapter ="AmareshHebbar/leetcode-python-qwen25-coder-7b"78tokenizer = AutoTokenizer.from_pretrained("AmareshHebbar/leetcode-python-qwen25-coder-7b")9model = AutoModelForCausalLM.from_pretrained(10 base_model,11 torch_dtype=torch.bfloat16,12 device_map="auto",13)14model = PeftModel.from_pretrained(model, adapter)1516messages =[17{"role":"system","content":"You are an expert Python competitive programmer. Given a LeetCode-style problem statement and an algorithm tag, write a correct, efficient Python solution."},18{"role":"user","content":"Problem: Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.\nAlgorithm: Hash Map"},19]20inputs = tokenizer.apply_chat_template(messages, return_tensors="pt", add_generation_prompt=True).to(model.device)21outputs = model.generate(inputs, max_new_tokens=512, temperature=0.2, do_sample=True)22print(tokenizer.decode(outputs[0][inputs.shape[1]:], skip_special_tokens=True))
Batch inference (many problems at once)
python
1problems =[2"Problem: Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.\nAlgorithm: Hash Map",3"Problem: Given a string s, find the length of the longest substring without repeating characters.\nAlgorithm: two pointers / sliding window",4"Problem: Merge two sorted linked lists into one sorted list.\nAlgorithm: linked list, dummy head",5]67prompts =[8 tokenizer.apply_chat_template(9[{"role":"system","content":"You are an expert Python competitive programmer. Given a LeetCode-style problem statement and an algorithm tag, write a correct, efficient Python solution."},{"role":"user","content": p}],10 tokenize=False, add_generation_prompt=True,11)12for p in problems
13]14tokenizer.padding_side ="left"15batch = tokenizer(prompts, return_tensors="pt", padding=True).to(model.device)16outputs = model.generate(**batch, max_new_tokens=512, temperature=0.2, do_sample=True)17for i, o inenumerate(outputs):18print(f"--- solution {i} ---")19print(tokenizer.decode(o[batch['input_ids'].shape[1]:], skip_special_tokens=True))
1json_system_prompt =(2"You are an expert Python competitive programmer. Given a LeetCode-style problem statement and an algorithm tag, write a correct, efficient Python solution. "3'Respond ONLY with JSON: {"code": "...", "time_complexity": "...", '4'"space_complexity": "...", "explanation": "..."}'5)6messages =[7{"role":"system","content": json_system_prompt},8{"role":"user","content":"Problem: Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.\nAlgorithm: Hash Map"},9]10inputs = tokenizer.apply_chat_template(messages, return_tensors="pt", add_generation_prompt=True).to(model.device)11outputs = model.generate(inputs, max_new_tokens=512, temperature=0.1, do_sample=True)12raw = tokenizer.decode(outputs[0][inputs.shape[1]:], skip_special_tokens=True)1314import json
15result = json.loads(raw.strip().removeprefix("```json").removesuffix("```").strip())16print(result["code"])17print(result["time_complexity"], result["space_complexity"])
Option B — Unsloth (2x faster load + inference)
python
1from unsloth import FastLanguageModel
23model, tokenizer = FastLanguageModel.from_pretrained(4 model_name="AmareshHebbar/leetcode-python-qwen25-coder-7b",5 max_seq_length=2048,6 load_in_4bit=True,7)8FastLanguageModel.for_inference(model)910messages =[11{"role":"system","content":"You are an expert Python competitive programmer. Given a LeetCode-style problem statement and an algorithm tag, write a correct, efficient Python solution."},12{"role":"user","content":"Problem: Given a string s, find the length of the longest substring without repeating characters.\nAlgorithm: two pointers / sliding window"},13]14prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)15inputs = tokenizer(prompt, return_tensors="pt").to("cuda")16outputs = model.generate(**inputs, max_new_tokens=512, temperature=0.2, do_sample=True)17print(tokenizer.decode(outputs[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True))
Option C — vLLM (production serving, OpenAI-compatible) {#vllm}
1from openai import OpenAI
23client = OpenAI(base_url="http://localhost:8000/v1", api_key="not-needed")4response = client.chat.completions.create(5 model="leetcode-python-qwen25-coder-7b",6 messages=[7{"role":"system","content":"You are an expert Python competitive programmer. Given a LeetCode-style problem statement and an algorithm tag, write a correct, efficient Python solution."},8{"role":"user","content":"Problem: Merge two sorted linked lists into one sorted list.\nAlgorithm: linked list, dummy head"},9],10 temperature=0.2,11)12print(response.choices[0].message.content)
Streaming with vLLM's OpenAI-compatible endpoint:
python
1stream = client.chat.completions.create(2 model="leetcode-python-qwen25-coder-7b",3 messages=[{"role":"user","content":"Problem: Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.\nAlgorithm: Hash Map"}],4 stream=True,5)6for chunk in stream:7if chunk.choices[0].delta.content:8print(chunk.choices[0].delta.content, end="", flush=True)
Option D — TGI (Text Generation Inference) {#tgi}
bash
1docker run --gpus all --shm-size 1g -p 8080:80 \2 -v $PWD/data:/data ghcr.io/huggingface/text-generation-inference:latest \3 --model-id unsloth/Qwen2.5-Coder-7B-Instruct \4 --lora-adapters leetcode-python-qwen25-coder-7b=AmareshHebbar/leetcode-python-qwen25-coder-7b
bash
1curl127.0.0.1:8080/generate_stream \2 -X POST \3 -d '{"inputs":"<|im_start|>system\nYou are an expert Python competitive programmer. Given a LeetCode-style problem statement and an algorithm tag, write a correct, efficient Python solution.<|im_end|>\n<|im_start|>user\nProblem: Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.\nAlgorithm: Hash Map<|im_end|>\n<|im_start|>assistant\n","parameters":{"max_new_tokens":512}}'\4 -H 'Content-Type: application/json'
Option E — Ollama (local, mobile/edge-friendly) {#ollama}
bash
1# 1. Pull the GGUF build2huggingface-cli download AmareshHebbar/leetcode-python-qwen25-coder-7b-GGUF leetcode-python-qwen25-coder-7b.q4_k_m.gguf --local-dir .34# 2. Create the model from the Modelfile shipped in the deployment kit (see deploy_ollama.py)5ollama create leetcode-python-qwen25-coder-7b -f Modelfile.python
67# 3. Run it8ollama run leetcode-python-qwen25-coder-7b "Problem: Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.\nAlgorithm: Hash Map"
Python client against a local Ollama server:
python
1import requests
2r = requests.post("http://localhost:11434/api/generate", json={3"model":"leetcode-python-qwen25-coder-7b",4"prompt":"Problem: Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.\nAlgorithm: Hash Map",5"stream":False,6})7print(r.json()["response"])
Option F — GGUF / llama.cpp direct (mobile/edge inference)
bash
1./llama-cli -m leetcode-python-qwen25-coder-7b.q4_k_m.gguf \2 -p "<|im_start|>system\nYou are an expert Python competitive programmer. Given a LeetCode-style problem statement and an algorithm tag, write a correct, efficient Python solution.<|im_end|>\n<|im_start|>user\nProblem: Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.<|im_end|>\n<|im_start|>assistant\n"\3 -n 512 --temp 0.2
See export_gguf.py in the deployment kit for building q4_k_m / q5_k_m / q8_0 variants, and the mobile integration notes there for Android (llama.cpp JNI) and iOS (llama.cpp via Swift bindings).
Training details
Why this base model
Qwen2.5-Coder-7B-Instruct was chosen over a general instruct model because its
pretraining already concentrates capacity on code — the QDoRA adapter only has to
specialize output format and LeetCode-specific conventions (function signatures,
in-place vs. new-array conventions, Python idioms) rather than teach the model
to code from scratch. 7B was picked as the size that still fits comfortably in a
single-GPU QDoRA run while keeping enough headroom that the base model's code
reasoning survives adaptation.
Data pipeline
Source: doocs/leetcode, 3,977 problems with
English documentation. Each problem can have multiple solutions spanning different
algorithm tags (greedy, DP, two pointers, etc.) — the pipeline treats this as a
one-to-many problem-to-solution structure rather than picking a single "canonical" answer.
Stage
What it does
extract_doocs.py
pulls problem statement + I/O examples + per-solution algorithm tag from doocs/leetcode
verify.py
executes each extracted solution against its sample I/O, drops anything that fails
normalize.py
standardizes formatting/whitespace and problem/solution schema across all 4 languages
build_language_datasets.py
splits into per-language configs and writes the final train/val/test SFT rows
~70% of extracted solutions verified (execution-checked against sample I/O). Full extraction/verification/build code lives alongside the
leetcode-codegen-python dataset card.
self-reported, not measured with a carbon tracker — treat as approximate
Fine-tuned with Unsloth + TRL's SFTTrainer,
DoRA enabled via PEFT.
Bias, risks & limitations
Narrow specialization. This model is tuned tightly on LeetCode-style algorithmic problems — general software-engineering code (frameworks, infra, business logic) is out of distribution.
Verify before trusting. Like any LLM, generated solutions can look plausible and still fail an edge case (empty input, integer overflow, off-by-one). Always run against test cases before use.
Not exhaustive on complexity. The model doesn't guarantee asymptotically optimal solutions — check the complexity claims yourself for performance-sensitive use.
Data recency. Reflects the state of doocs/leetcode at the time of extraction — newer problems added to LeetCode after that snapshot won't be covered.
FAQ
Q: Can I merge the adapter into the base model?
Yes — model.merge_and_unload() after loading with PEFT, or Unsloth's save_pretrained_merged(). DoRA adapters merge the same way LoRA adapters do.
Q: Why QDoRA instead of plain QLoRA?
See Why QDoRA above — short version: DoRA's magnitude/direction split tracks full fine-tuning more closely, which matters for code correctness.
Q: Why QDoRA instead of full fine-tuning?
Qwen2.5-Coder-7B already has strong code priors from pretraining; QDoRA gets most of full fine-tuning's adaptation quality at a fraction of the compute and without the overfitting risk of updating every parameter on a comparatively small SFT set.
Q: Which quantization should I use on mobile?
q4_k_m is the best size/quality tradeoff for phones; q5_k_m if you have RAM headroom; avoid q2/q3 for code generation — correctness drops sharply below 4-bit.
Q: Does this model store or transmit my input?
No — inference runs entirely on whatever infrastructure you deploy it to.