Views
No views yet
1# LoRA Configuration
2r = 16 # Rank: 16 is a good balance for 2B models
3target_modules = ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]
4lora_alpha = 16
5lora_dropout = 0
6bias = "none"
7use_gradient_checkpointing = "unsloth"
8
9# Training Parameters
10max_seq_length = 2048
11per_device_train_batch_size = 2
12gradient_accumulation_steps = 4 # Effective batch size = 8
13warmup_steps = 5
14max_steps = 100 # Demo configuration - increase to 300+ for production
15learning_rate = 2e-4
16optim = "adamw_8bit" # 8-bit optimizer for memory efficiency
17weight_decay = 0.01
18lr_scheduler_type = "linear"pip install unsloth transformers torch trl datasets1from unsloth import FastLanguageModel
2import torch
3
4max_seq_length = 2048
5dtype = None
6load_in_4bit = True
7
8model, tokenizer = FastLanguageModel.from_pretrained(
9 model_name = "rajaykumar12959/gemma-2-2b-text-to-sql-qlora",
10 max_seq_length = max_seq_length,
11 dtype = dtype,
12 load_in_4bit = load_in_4bit,
13)
14
15FastLanguageModel.for_inference(model) # Enable faster inference1def inference_text_to_sql(model, tokenizer, schema, question, max_new_tokens=300):
2 """
3 Perform inference to generate SQL from natural language question and database schema.
4
5 Args:
6 model: Fine-tuned Gemma model
7 tokenizer: Model tokenizer
8 schema: Database schema as string
9 question: Natural language question
10 max_new_tokens: Maximum tokens to generate
11
12 Returns:
13 Generated SQL query as string
14 """
15 # Format the input prompt
16 input_prompt = f"""<start_of_turn>user
17You are a powerful text-to-SQL model. Your job is to answer questions about a database. You are given a question and context regarding one or more tables.
18
19### Schema:
20{schema}
21
22### Question:
23{question}<end_of_turn>
24<start_of_turn>model
25"""
26
27 # Tokenize input
28 inputs = tokenizer([input_prompt], return_tensors="pt").to("cuda")
29
30 # Generate output
31 with torch.no_grad():
32 outputs = model.generate(
33 **inputs,
34 max_new_tokens=max_new_tokens,
35 use_cache=True,
36 do_sample=True,
37 temperature=0.1, # Low temperature for more deterministic output
38 top_p=0.9,
39 pad_token_id=tokenizer.eos_token_id
40 )
41
42 # Decode and clean the result
43 result = tokenizer.batch_decode(outputs)[0]
44 sql_query = result.split("<start_of_turn>model")[-1].replace("<end_of_turn>", "").strip()
45
46 return sql_query1# Simple employee database
2simple_schema = """
3CREATE TABLE employees (
4 employee_id INT PRIMARY KEY,
5 name TEXT,
6 department TEXT,
7 salary DECIMAL,
8 hire_date DATE
9);
10"""
11
12simple_question = "Find all employees in the 'Engineering' department with salary greater than 75000"
13
14sql_result = inference_text_to_sql(model, tokenizer, simple_schema, simple_question)
15print(f"Generated SQL:\n{sql_result}")1SELECT * FROM employees
2WHERE department = 'Engineering'
3AND salary > 75000;sql_context: Database schemasql_prompt: Natural language questionsql: Target SQL query1def formatting_prompts_func(examples):
2 schemas = examples["sql_context"]
3 questions = examples["sql_prompt"]
4 outputs = examples["sql"]
5
6 texts = []
7 for schema, question, output in zip(schemas, questions, outputs):
8 text = gemma_prompt.format(schema, question, output) + EOS_TOKEN
9 texts.append(text)
10 return { "text" : texts, }max_steps to 300+Fine_tune_qlora.ipynbpip install unsloth transformers torch trl datasetsmax_steps in TrainingArguments for longer training1# For production use, update these parameters:
2max_steps = 300, # Increase from 100
3warmup_steps = 10, # Increase warmup
4per_device_train_batch_size = 4, # If you have more GPU memory| Parameter | Value |
|---|---|
| Base Model | Gemma-2-2B (4-bit quantized) |
| Fine-tuning Method | QLoRA |
| LoRA Rank | 16 |
| Training Steps | 100 (demo) |
| Learning Rate | 2e-4 |
| Batch Size | 8 (effective) |
| Max Sequence Length | 2048 |
| Dataset Size | 100k examples |
1@misc{gemma-2-2b-text-to-sql-qlora,
2 author = {rajaykumar12959},
3 title = {Gemma-2-2B Text-to-SQL QLoRA Fine-tuned Model},
4 year = {2024},
5 publisher = {Hugging Face},
6 howpublished = {\url{https://huggingface.co/rajaykumar12959/gemma-2-2b-text-to-sql-qlora}},
7}