Views
No views yet
1# Cài đặt thư viện cốt lõi để chạy mô hình AI
2%pip install "transformers>=4.51.3" "torchao>=0.16.0" accelerate
3
4import torch
5from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
6from peft import PeftModel
7
8print("Bước 1: Đang tải bộ tách từ (Tokenizer)...")
9tokenizer = AutoTokenizer.from_pretrained("hduc01/gemma-3-text-to-sql-fast")
10
11print("Bước 2: Tải mô hình nền tảng gốc của Google...")
12base_model = AutoModelForCausalLM.from_pretrained(
13 "google/gemma-3-1b-it",
14 torch_dtype=torch.float16,
15 low_cpu_mem_usage=True,
16 device_map="auto"
17)
18
19print("Bước 3: Bọc mảnh Adapter của bạn lên trên mô hình gốc...")
20# Lấy file 1.27 GB trên Hub của bạn về để ráp vào mô hình gốc
21model = PeftModel.from_pretrained(base_model, "hduc01/gemma-3-text-to-sql-fast")
22
23print("Bước 4: Vá lỗi toán học cấu hình tầng sâu (Sửa lỗi Issue #2777)...")
24# Ép bộ não sau khi đã bọc Adapter phải tắt tính năng liên kết trọng số từ vựng
25model.config.tie_word_embeddings = False
26
27print("Bước 5: Khởi tạo dây chuyền Pipeline suy luận...")
28generator = pipeline(
29 "text-generation",
30 model=model,
31 tokenizer=tokenizer
32)
33
34# 1. Định nghĩa SCHEMA và Câu hỏi chuẩn chuyên môn Text-to-SQL
35test_schema = """CREATE TABLE orders (
36 order_id INT,
37 customer_id INT,
38 order_date DATE,
39 total_amount DECIMAL(10,2),
40 status VARCHAR(20)
41);"""
42
43test_question = "Find the total amount spent on all orders that have a status of 'Completed' after January 1st, 2020."
44
45formatted_prompt = f"""Given the <SCHEMA> and the <USER_QUERY>, generate the corresponding SQL command to retrieve the desired data, considering the query's syntax, semantics, and schema constraints.
46<SCHEMA>
47{test_schema}
48</SCHEMA>
49<USER_QUERY>
50{test_question}
51</USER_QUERY>"""
52
53messages = [
54 {"role": "system", "content": "You are a text to SQL query translator. Users will ask you questions in English and you will generate a SQL query based on the provided SCHEMA."},
55 {"role": "user", "content": formatted_prompt}
56]
57
58print("AI đang đọc SCHEMA và tiến hành dịch sang câu lệnh SQL...")
59output = generator(
60 messages,
61 max_new_tokens=100,
62 temperature=0.1, # Khóa độ sáng tạo ở mức thấp nhất
63 do_sample=False,
64 return_full_text=False
65)
66
67print("\nCÂU LỆNH SQL:")
68print(output[0]["generated_text"])
691@software{vonwerra2020trl,
2 title = {{TRL: Transformers Reinforcement Learning}},
3 author = {von Werra, Leandro and Belkada, Younes and Tunstall, Lewis and Beeching, Edward and Thrush, Tristan and Lambert, Nathan and Huang, Shengyi and Rasul, Kashif and Gallouédec, Quentin},
4 license = {Apache-2.0},
5 url = {https://github.com/huggingface/trl},
6 year = {2020}
7}