Fine-Tuning DeepSeek-Coder for Enterprise APIs with QLoRA
General-purpose code LLMs write solid boilerplate for public libraries, yet they routinely hallucinate endpoints, invent deprecated query parameters, or miss strict authentication and idempotency conventions when generating code against internal enterprise APIs. Relying solely on long system prompts with OpenAPI specs burns context tokens on every request and still drifts under multi-step workflows.
Parameter-Efficient Fine-Tuning (PEFT) with QLoRA solves this cleanly. By quantizing the base DeepSeek-Coder weights to 4-bit NormalFloat (NF4) and training lightweight low-rank adapter matrices on curated internal API examples, you teach the model your exact SDK signatures, error-handling wrappers, and compliance rules on a single workstation or cloud GPU.
Why QLoRA Works Well for Enterprise Code Generation
Full-parameter fine-tuning of a 6.7B–16B code model requires multi-GPU clusters and risks catastrophic forgetting of general programming syntax. QLoRA freezes the quantized base model and updates less than 2% of total parameters:
| Training Strategy | VRAM Footprint (7B–16B Class) | Preserves Base Coding Ability | Adapter Artifact Size | Best Use Case |
|---|---|---|---|---|
| Prompt Engineering / RAG Only | Inference only | Yes | None | Frequently changing docs with simple endpoints |
| Full Fine-Tuning | 80 GB – 320 GB+ | Risk of syntax drift | 14 GB – 32 GB | Massive multi-language pretraining corpora |
| QLoRA (4-bit NF4 + LoRA) | 12 GB – 24 GB | High | 40 MB – 180 MB | Internal SDKs, proprietary APIs, strict payload schemas |
Preparing the Enterprise API Training Dataset
High-signal fine-tuning data beats raw log volume. Curate 500 to 3,000 verified (instruction, context, code_solution) examples covering:
- Authentication & Retry Wrappers: Token refresh,
X-Idempotency-Keyheaders, and exponential backoff on HTTP429/503. - Typed Request/Response Payloads: Pydantic models or TypeScript interfaces matching internal microservices.
- Negative / Edge Cases: Proper handling of pagination cursors, partial batch failures, and audit-trail headers.
Store examples in JSONL format (data/enterprise_api_sft.jsonl) using a structured chat template:
{
"messages": [
{
"role": "system",
"content": "You are an internal platform engineer. Generate production Python code using the AcmePay v3 SDK with strict idempotency and typed error handling."
},
{
"role": "user",
"content": "Create a refund endpoint call for settlement_id 'stl_9821' with reason 'duplicate_charge' and retry transient 503 errors."
},
{
"role": "assistant",
"content": "import uuid\nfrom acmepay.v3 import AcmePayClient, RefundRequest\nfrom acmepay.v3.exceptions import TransientGatewayError\nfrom tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential\n\nclient = AcmePayClient.from_env()\n\n@retry(\n retry=retry_if_exception_type(TransientGatewayError),\n stop=stop_after_attempt(3),\n wait=wait_exponential(multiplier=0.5, min=0.5, max=4.0),\n)\ndef issue_settlement_refund(settlement_id: str, reason: str) -> dict:\n payload = RefundRequest(settlement_id=settlement_id, reason=reason)\n response = client.refunds.create(\n payload=payload,\n idempotency_key=f'refund-{settlement_id}-{uuid.uuid4().hex[:8]}',\n )\n return response.model_dump()\n"
}
]
}
Installing Dependencies
Install PyTorch alongside Hugging Face transformers, peft, bitsandbytes, datasets, and trl:
pip install torch transformers peft bitsandbytes datasets trl accelerate
Fine-Tuning DeepSeek-Coder with QLoRA (train_qlora.py)
The script below loads a DeepSeek-Coder checkpoint in 4-bit precision, targets both attention and MLP projection layers (q_proj, k_proj, v_proj, o_proj, gate_proj, up_proj, down_proj), and trains with SFTTrainer using cosine learning-rate decay.
import torch
from datasets import load_dataset
from peft import LoraConfig, prepare_model_for_kbit_training
from transformers import (
AutoModelForCausalLM,
AutoTokenizer,
BitsAndBytesConfig,
)
from trl import SFTConfig, SFTTrainer
MODEL_ID = "deepseek-ai/deepseek-coder-6.7b-instruct"
DATASET_PATH = "data/enterprise_api_sft.jsonl"
OUTPUT_DIR = "artifacts/deepseek-coder-enterprise-api-lora"
def build_bnb_config() -> BitsAndBytesConfig:
"""Configure 4-bit NF4 quantization with bfloat16 compute."""
return BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_use_double_quant=True,
bnb_4bit_compute_dtype=torch.bfloat16,
)
def build_lora_config() -> LoraConfig:
"""Configure LoRA adapters across attention and feed-forward linear layers."""
return LoraConfig(
r=16,
lora_alpha=32,
lora_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",
],
)
def train() -> None:
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True)
if tokenizer.pad_token is None:
tokenizer.pad_token = tokenizer.eos_token
tokenizer.padding_side = "right"
model = AutoModelForCausalLM.from_pretrained(
MODEL_ID,
quantization_config=build_bnb_config(),
device_map="auto",
trust_remote_code=True,
)
model.config.use_cache = False
model = prepare_model_for_kbit_training(model)
dataset = load_dataset("json", data_files=DATASET_PATH, split="train")
splits = dataset.train_test_split(test_size=0.1, seed=42)
sft_config = SFTConfig(
output_dir=OUTPUT_DIR,
num_train_epochs=3,
per_device_train_batch_size=2,
per_device_eval_batch_size=2,
gradient_accumulation_steps=8,
learning_rate=2e-4,
lr_scheduler_type="cosine",
warmup_ratio=0.05,
weight_decay=0.01,
max_seq_length=2048,
logging_steps=10,
eval_strategy="steps",
eval_steps=50,
save_strategy="steps",
save_steps=50,
save_total_limit=2,
bf16=True,
gradient_checkpointing=True,
optim="paged_adamw_8bit",
report_to="none",
)
trainer = SFTTrainer(
model=model,
args=sft_config,
train_dataset=splits["train"],
eval_dataset=splits["test"],
processing_class=tokenizer,
peft_config=build_lora_config(),
)
trainer.model.print_trainable_parameters()
trainer.train()
trainer.save_model(OUTPUT_DIR)
tokenizer.save_pretrained(OUTPUT_DIR)
print(f"Saved QLoRA adapter and tokenizer to {OUTPUT_DIR}")
if __name__ == "__main__":
train()
Merging Adapters & Running Enterprise Inference (infer_api.py)
Once training finishes, you can either load the lightweight LoRA adapter dynamically on top of the base model or merge the adapter weights into a standalone checkpoint for vLLM / TGI deployment:
import torch
from peft import PeftModel
from transformers import AutoModelForCausalLM, AutoTokenizer
BASE_MODEL = "deepseek-ai/deepseek-coder-6.7b-instruct"
ADAPTER_DIR = "artifacts/deepseek-coder-enterprise-api-lora"
def load_enterprise_coder():
tokenizer = AutoTokenizer.from_pretrained(ADAPTER_DIR, trust_remote_code=True)
base_model = AutoModelForCausalLM.from_pretrained(
BASE_MODEL,
torch_dtype=torch.bfloat16,
device_map="auto",
trust_remote_code=True,
)
model = PeftModel.from_pretrained(base_model, ADAPTER_DIR)
model.eval()
return model, tokenizer
def generate_api_code(prompt: str) -> str:
model, tokenizer = load_enterprise_coder()
messages = [
{
"role": "system",
"content": "You are an internal platform engineer. Generate production Python code using the AcmePay v3 SDK with strict idempotency and typed error handling.",
},
{"role": "user", "content": prompt},
]
input_ids = tokenizer.apply_chat_template(
messages,
add_generation_prompt=True,
return_tensors="pt",
).to(model.device)
with torch.no_grad():
outputs = model.generate(
input_ids,
max_new_tokens=512,
do_sample=False,
eos_token_id=tokenizer.eos_token_id,
)
generated_tokens = outputs[0][input_ids.shape[-1] :]
return tokenizer.decode(generated_tokens, skip_special_tokens=True)
if __name__ == "__main__":
code = generate_api_code(
"Fetch paginated ledger entries for merchant 'mch_404' and handle rate-limit retries."
)
print(code)
Validating Fine-Tuned Output Against OpenAPI Schemas
Never measure an enterprise code model on perplexity alone. Before promoting an adapter to staging, evaluate generated snippets against automated contract checks:
- AST & Syntax Parsing: Verify every completion compiles cleanly (
ast.parsefor Python ortsc --noEmitfor TypeScript). - SDK Symbol & Endpoint Allowlist: Parse imports and method calls to confirm zero hallucinated endpoints, removed methods, or unauthorized external packages.
- Mock Server Execution: Run generated functions against a Prism or WireMock OpenAPI stub and assert that required headers (
Authorization,X-Idempotency-Key,X-Correlation-ID) and JSON schema fields pass validation.
Best Practices for Enterprise API Fine-Tuning
- Scrub secrets and PII before dataset creation: Run automated regex and entropy scanners over internal git commits and integration tests so API keys, tenant IDs, and internal hostnames never enter training weights.
- Target both attention and MLP modules: Including
gate_proj,up_proj, anddown_projalongsideq/k/v/o_projsignificantly improves recall of exact parameter names and structured schemas compared to attention-only LoRA. - Use deterministic decoding (
do_sample=False): For SDK and API payload synthesis, greedy decoding or low temperature (0.0–0.1) prevents creative parameter drift. - Version adapters alongside OpenAPI specs: Tag each LoRA release with the exact internal API schema version (e.g.,
acmepay-v3.14-lora) so teams can roll back cleanly when breaking changes ship.
Common Mistakes
- Training on unverified developer snippets: Scraping raw internal repositories without filtering out deprecated v1/v2 calls teaches the model conflicting API versions.
- Setting
max_seq_lengthtoo short: Truncating multi-file SDK examples mid-function trains the model to emit incomplete try/except blocks or missing return statements. - Omitting negative and error-handling examples: If every training sample shows a
200 OKhappy path, the fine-tuned model will drop retry decorators, pagination loops, and exception handling.
Summary
Fine-tuning DeepSeek-Coder with QLoRA bridges the gap between generic code generation and strict enterprise API compliance. By curating schema-verified JSONL examples, training 4-bit adapters with SFTTrainer, and gating releases with AST and mock-server contract tests, engineering teams can deploy reliable internal coding assistants on modest GPU hardware.