惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
Visual Studio Blog
爱范儿
爱范儿
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
雷峰网
雷峰网
V
V2EX
博客园_首页
Engineering at Meta
Engineering at Meta
博客园 - 聂微东
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Apple Machine Learning Research
Apple Machine Learning Research
GbyAI
GbyAI
H
Help Net Security
A
About on SuperTechFans
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Blog — PlanetScale
Blog — PlanetScale
W
WeLiveSecurity
云风的 BLOG
云风的 BLOG
D
Docker
Security Archives - TechRepublic
Security Archives - TechRepublic
Help Net Security
Help Net Security
N
News and Events Feed by Topic
Simon Willison's Weblog
Simon Willison's Weblog
G
Google Developers Blog
A
Arctic Wolf
T
The Blog of Author Tim Ferriss
博客园 - 叶小钗
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Google DeepMind News
Google DeepMind News
博客园 - 三生石上(FineUI控件)
aimingoo的专栏
aimingoo的专栏
Hacker News: Ask HN
Hacker News: Ask HN
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园 - 司徒正美
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
P
Privacy International News Feed
T
Troy Hunt's Blog
T
Tenable Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Recorded Future
Recorded Future
F
Fortinet All Blogs
D
DataBreaches.Net
B
Blog
T
Threat Research - Cisco Blogs
MyScale Blog
MyScale Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
The GitHub Blog
The GitHub Blog
Security Latest
Security Latest
M
MIT News - Artificial intelligence

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Fine Tune Llama 3 For Sql Query Generation Tutorial
Sam Chen · 2026-06-15 · via DEV Community

Fine‑Tuning Llama 3 for Production‑Ready SQL Generation (Under $50) Hey, it’s Nick Creighton from Build Log. In the latest episode of Signal Notes I walked through how I took a fresh Llama 3 checkpoint, threw a few hundred annotated queries at it, and ended up with a model that reliably writes SELECT statements for our internal analytics dashboard—all for less than the price of a lunch. If you’ve ever tried to get a generic chatbot to spit out SQL and ended up chasing phantom columns or a 40 % data‑drift nightmare, you’ll know why you need a custom model. Below is the step‑by‑step companion guide that turns the audio discussion into a hands‑on playbook. ### Why a Generic Text‑to‑SQL Model Is a Liability Let’s recap the hook from the episode: - Generic LLMs hallucinate schema elements (e.g., fiscal_quarter that doesn’t exist). - They expose sensitive table or column names in prompts, a compliance red flag. - Business‑specific jargon (“top line”) never makes it into a pre‑trained model. - OpenAI‑style API pricing can balloon when you start running hundreds of queries a day. Bottom line: you own the data, you own the model, you own the risk. ### What You’ll Need Before You Start - Hardware: A single RTX 4090 (or any 24 GB+ GPU) will do. If you don’t have one, look into Paperspace or Google Vertex AI spot instances – they run under $0.30/hr. - Software: python>=3.10, torch (CUDA‑enabled), transformers (v4.40+), datasets, and peft for parameter‑efficient fine‑tuning. - Data: A curated set of SQL‑in‑context examples from your own warehouses – ideally 200–500 pairs of natural‑language prompt → SQL query. - Budget Tracker: Keep a simple budget.txt file; we’ll update it after each cloud‑run to stay under $50. ### Step 1: Pull a Clean Llama 3 Checkpoint The Meta‑Llama‑3‑8B checkpoint is free for commercial use (as of the 2024 license). Grab the gguf version if you want to run inference on CPU later. git lfs install git clone https://huggingface.co/meta-llama/Meta-Llama-3-8B cd Meta-Llama-3-8B Verify the download size (~15 GB) and checksum – you don’t want a corrupted model messing with your fine‑tuning loss. ### Step 2: Assemble a Domain‑Specific SQL Corpus Here’s the practical part. Your model will only be as good as the examples you feed it. - Export Schema: Run pg_dump -s -U your_user your_db > schema.sql (PostgreSQL) or the equivalent for Snowflake/Redshift. - Harvest Queries: Pull the last 30 days of production queries from your query‑audit table, anonymize any PII, and store them in queries_raw.sql. - Pair With NL: For each query, write a concise natural‑language description (30‑80 words). If you have a product manager, ask them to phrase the question as a business user would. - Normalize: Ensure every pair follows the same JSON schema: { "instruction": "Show me quarterly gross revenue for the US region.", "input": null, "output": "SELECT fiscal_year, SUM(gross_revenue) FROM sales WHERE region = 'US' GROUP BY fiscal_year;" } - Validate: Run each output against a test database. Keep only the queries that return without errors. This step eliminates “syntactically correct but semantically wrong” examples. Goal: 300 high‑quality pairs. If you’re short, generate synthetic variations with ChatGPT (but treat them as “augmented” – still validate). ### Step 3: Create a Hugging Face datasets Object from datasets import Dataset import json, pathlib data_path = pathlib.Path("sql_corpus.jsonl") records = [json.loads(line) for line in data_path.open()] dataset = Dataset.from_dict({ "instruction": [r["instruction"] for r in records], "output": [r["output"] for r in records], }) dataset = dataset.train_test_split(test_size=0.1, seed=42) Splitting 90/10 gives you a quick validation set to watch over‑fitting. ### Step 4: Prompt Engineering – The “Instruction‑Tuning” Wrapper Llama 3 expects a chat‑style conversation. Wrap each example in a system‑prompt that tells the model it’s a “SQL‑assistant”. system_prompt = ( "You are an expert SQL assistant for the Acme Analytics team. " "Answer only with a valid PostgreSQL query. Do not add explanations unless asked." ) def format_example(instruction, output): return [ {"role": "system", "content": system_prompt}, {"role": "user", "content": instruction}, {"role": "assistant", "content": output} ] This consistent wrapper dramatically improves downstream performance. ### Step 5: Parameter‑Efficient Fine‑Tuning (PEFT) with LoRA Full fine‑tuning of 8 B parameters would be a waste of GPU memory. LoRA (Low‑Rank Adaptation) lets us train only a few thousand extra weights, keeping VRAM usage under 20 GB. pip install peft accelerate from transformers import AutoModelForCausalLM, AutoTokenizer from peft import LoraConfig, get_peft_model model = AutoModelForCausalLM.from_pretrained( "Meta-Llama-3-8B", device_map="auto", torch_dtype="auto" ) tokenizer = AutoTokenizer.from_pretrained("Meta-Llama-3-8B") tokenizer.pad_token = tokenizer.eos_token lora_cfg = LoraConfig( r=16, lora_alpha=32, target_modules=["q_proj", "k_proj", "v_proj", "o_proj"], lora_dropout=0.05, bias="none", task_type="CAUSAL_LM" ) model = get_peft_model(model, lora_cfg) model.print_trainable_parameters() The output will show ~0.2 % of parameters are trainable – perfect for a $0.30/hr spot instance. ### Step 6: Training Loop – Keep an Eye on Cost We’ll use accelerate to handle distributed training automatically. Set gradient_accumulation_steps so the effective batch size stays around 32, which balances speed and GPU memory. from accelerate import Accelerator from transformers import Trainer, TrainingArguments accelerator = Accelerator() training_args = TrainingArguments( output_dir="llama3-sql", per_device_train_batch_size=4, per_device_eval_batch_size=4, gradient_accumulation_steps=8, learning_rate=2e-5, num_train_epochs=3, fp16=True, logging_steps=20, evaluation_strategy="steps", eval_steps=100, save_steps=200, save_total_limit=2, report_to="none" ) def data_collator(features): batch = tokenizer.pad( {"input_ids": [f["input_ids"] for f in features], "labels": [f["labels"] for f in features]}, padding=True, return_tensors="pt" ) batch["labels"][batch["labels"] == tokenizer.pad_token_id] = -100 return batch trainer = Trainer( model=model, args=training_args, train_dataset=dataset["train"], eval_dataset=dataset["test"], tokenizer=tokenizer, data_collator=data_collator, ) trainer.train() Cost‑tracking tip: After each training run, run accelerate status and record the total GPU‑hours in budget.txt. With a 3‑epoch run on a single RTX 4090, you should stay under $12. ### Step 7: Quick Evaluation – The “Real‑World” Test Suite Training loss is nice, but we need to know if the model actually respects your schema. - Static Tests: Feed 20 held‑out natural‑language prompts and compare the generated SQL string to the ground truth using difflib.SequenceMatcher. Aim for > 85 % exact match. - Execution Tests: Run each generated query against a sandbox copy of your DB. Capture rowcount and error_message. Flag any “column not found” or “syntax error” failures. - Security Scan: Verify that no table or column names appear in the prompt side‑channel (e.g., user‑provided text). If they do, strip them out before sending to the model. Below is a tiny helper you can drop into a notebook: def eval_sql(prompt): messages = format_example(prompt, "") input_ids = tokenizer.apply_chat_template(messages, return_tensors="pt") output = model.generate( input_ids.to(model.device), max_new_tokens=200, temperature=0.0, do_sample=False ) sql = tokenizer.decode(output[0], skip_special_tokens=True) return sql.strip() ### Step 8: Deploying the Model – From Notebook to Production API We’ll spin up a FastAPI wrapper and serve it via ngrok for internal testing. When you’re ready, push the container to ECR and run it on AWS Fargate (or GCP Cloud Run). All of this can be done for under $20/month. # fastapi_app.py from fastapi import FastAPI, HTTPException from pydantic import BaseModel app = FastAPI() class QueryRequest(BaseModel): question: str @app.post("/generate-sql") def generate_sql(req: QueryRequest): try: sql = eval_sql(req.question) return {"sql": sql} except Exception as e: raise HTTPException(status_code=500, detail=str(e)) Build a Dockerfile that copies the model weights, installs torch and transformers, and runs uvicorn fastapi_app:app --host 0.0.0.0 --port 8080. Keep the container size lean (use python:3.11-slim as base). ### Step 9: Monitoring & Continuous Improvement - Telemetry: Log every incoming question, the generated SQL, and a boolean execution_success flag from your sandbox runner. - Feedback Loop: If a query fails, automatically add the (question, corrected‑SQL) pair to a retrain_queue.jsonl file. Schedule a nightly trainer.train() run to ingest the new data. - Cost Guardrails: Set a CloudWatch alarm (or GCP Monitoring) that triggers when GPU usage exceeds $5 in any 24‑hour window. The alarm can spin down the spot instance automatically. Iterating in this fashion turns a one‑off fine‑tune into a living, self‑healing service. ### Step 10: Security & Compliance Checklist - Encrypt model checkpoints at rest (use AWS KMS or GCP CMEK). - Never log raw user prompts that contain PII; hash them instead. - Restrict API access to internal IP ranges or via a VPN. - Run a quarterly “model‑drift” audit: compare the model’s schema coverage against the latest information_schema dump. ### Real‑World Results – What I Saw After Deploying Within the first week, my team ran 1,240 generated queries. The success rate (queries that executed without error) was 93 %. The remaining 7 % were edge‑cases where the model needed a tiny business rule tweak (e.g., “exclude test accounts”). Adding those 15 new examples to the training set bumped the success rate to 96 % after a quick 30‑minute re‑train. Cost breakdown: - Initial fine‑tune on a spot GPU: $11.20 - Docker host on Fargate (2 vCPU, 4 GB RAM): $17.60/month - Data‑warehouse sandbox for validation: $5.20/month - Total first‑month spend: $33.80 That’s well under the “under $50” promise and dramatically cheaper than a commercial Text‑to‑SQL SaaS that charges per‑query. ### Actionable Checklist (Copy‑Paste into Your Project Management Tool) - [ ] Spin up a 24 GB GPU (RTX 4090 or Spot Instance) - [ ] Clone Llama 3 checkpoint - [ ] Export schema & harvest last‑30‑day queries - [ ] Write NL descriptions for each query (300 pairs minimum) - [ ] Validate each query against a sandbox DB


This article continues on our podcast...