Views
No views yet
meta-llama/Llama-3.2-1B-Instructpavan-naik/Llama-3.2-1B-Instruct-Text-to-SQLpip install peft transformers bitsandbytes1from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
2from peft import PeftModel
3import torch1bnb_config = BitsAndBytesConfig(
2 load_in_4bit=True,
3 bnb_4bit_use_double_quant=True,
4 bnb_4bit_quant_type="nf4",
5 bnb_4bit_compute_dtype=torch.float16
6)1# Load base model
2base_model = AutoModelForCausalLM.from_pretrained(
3 "meta-llama/Llama-3.2-1B-Instruct",
4 #quantization_config=bnb_config, #uncomment if you want to use quatized version.
5 device_map="auto"
6)
7
8# Load tokenizer
9tokenizer = AutoTokenizer.from_pretrained(
10 "pavan-naik/Llama-3.2-1B-Instruct-Text-to-SQL",
11 trust_remote_code=True
12)
13tokenizer.pad_token = tokenizer.eos_tokenmodel = PeftModel.from_pretrained(base_model, "pavan-naik/Llama-3.2-1B-Instruct-Text-to-SQL")1sql_prompt_template = """You are a database management system expert, proficient in Structured Query Language (SQL).
2Your job is to write an SQL query that answers the following question, based on the given database schema and any additional information provided. Use SQLite syntax.
3Please output only SQL (without any explanations).
4### Question: {question}
5### Schema: {context}
6### Completion: """1def generate_sql(question, context, model, tokenizer, max_length=128):
2 prompt = sql_prompt_template.format(question=question, context=context)
3 inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=max_length)
4 inputs = {k: v.to(model.device) for k, v in inputs.items()}
5
6 prompt_length = len(inputs["input_ids"][0])
7 outputs = model.generate(
8 **inputs,
9 max_length=prompt_length + max_length,
10 num_return_sequences=1,
11 temperature=0.7,
12 do_sample=True,
13 )
14
15 sql_answer = tokenizer.decode(outputs[0][prompt_length:], skip_special_tokens=True).strip()
16 return sql_answer1# Define your question and database schema
2question = "For each continent, show the city with the highest population and what percentage of its country's total population it represents"
3context = """
4CREATE TABLE city (city_id INTEGER, name VARCHAR, population INTEGER, country_id INTEGER);
5CREATE TABLE country (country_id INTEGER, name VARCHAR, continent VARCHAR)
6"""
7
8# Generate SQL query
9sql_query = generate_sql(question, context, model, tokenizer)
10print(sql_query)max_length parameter based on your query complexity