Views
No views yet
GSAI-ML/LLaDA-8B-Instruct base model. Unlike traditional Autoregressive (AR) models that generate tokens left-to-right, this model uses Masked Iterative Generation (Diffusion).model.generate() function because it requires a custom diffusion sampling loop. Use the code below to generate SQL queries.1import torch
2from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
3from peft import PeftModel, PeftConfig
4
5# Device setup
6device = "cuda" if torch.cuda.is_available() else "cpu"
7
8# 1. Load Base Model (4-bit)
9base_model_id = "GSAI-ML/LLaDA-8B-Instruct"
10bnb_config = BitsAndBytesConfig(
11 load_in_4bit=True,
12 bnb_4bit_compute_dtype=torch.float16,
13 bnb_4bit_quant_type="nf4",
14)
15
16model = AutoModelForCausalLM.from_pretrained(
17 base_model_id,
18 quantization_config=bnb_config,
19 device_map="auto",
20 trust_remote_code=True,
21 use_cache=False
22)
23tokenizer = AutoTokenizer.from_pretrained(base_model_id, trust_remote_code=True)
24
25# 2. Load LoRA Adapter (This Repo)
26adapter_model_id = "YOUR_USERNAME/llada-text-to-sql-lora" # Replace with your repo name
27model = PeftModel.from_pretrained(model, adapter_model_id)
28model.eval()
291@torch.no_grad()
2def generate_block_diffusion(model, tokenizer, prompt_text, steps=32, gen_len=64):
3 """
4 Generates text using LLaDA's block diffusion strategy.
5 """
6 # Tokenize Prompt
7 prompt_ids = tokenizer.encode(prompt_text, return_tensors='pt').to(model.device)
8 prompt_len = prompt_ids.shape[1]
9
10 # Initialize Response with [MASK] tokens
11 mask_ids = torch.full((1, gen_len), tokenizer.mask_token_id, device=model.device)
12 input_ids = torch.cat([prompt_ids, mask_ids], dim=1)
13
14 # Track unknown indices (initially all response tokens)
15 unknown_indices = set(range(prompt_len, input_ids.shape[1]))
16 tokens_to_lock_per_step = gen_len // steps
17
18 for step in range(steps):
19 # Forward pass
20 outputs = model(input_ids)
21 probs = torch.softmax(outputs.logits, dim=-1)
22
23 # Get most confident predictions
24 confidences, predicted_ids = torch.max(probs, dim=-1)
25
26 # Identify which tokens to "lock in" this step
27 candidates = []
28 current_unknowns = list(unknown_indices)
29 if not current_unknowns: break
30
31 for idx in current_unknowns:
32 score = confidences[0, idx].item()
33 token = predicted_ids[0, idx].item()
34 candidates.append((score, idx, token))
35
36 # Sort by confidence and pick top k
37 candidates.sort(key=lambda x: x[0], reverse=True)
38 top_k = candidates[:tokens_to_lock_per_step]
39
40 # Update input_ids
41 for _, idx, token in top_k:
42 input_ids[0, idx] = token
43 unknown_indices.remove(idx)
44
45 # Decode only the generated part
46 return tokenizer.decode(input_ids[0, prompt_len:], skip_special_tokens=True)
471schema = "CREATE TABLE users (id INTEGER, name TEXT, age INTEGER);"
2question = "Show me the names of users older than 25."
3
4prompt = f"""
5<|im_start|>system
6You are a Text-to-SQL assistant. Output ONLY the SQL query. Do not add explanations.<|im_end|>
7<|im_start|>user
8Schema:
9{schema}
10
11Question:
12{question}<|im_end|>
13<|im_start|>assistant
14"""
15
16output = generate_block_diffusion(model, tokenizer, prompt, steps=32, gen_len=64)
17print("Generated SQL:", output)
18[MASK] based on a uniform time step . Loss was calculated only on masked tokens and reweighted by .q_proj, v_projgretelai/synthetic_text_to_sql test set (200 samples) using Block Diffusion sampling.| Metric | Score |
|---|---|
| Exact Match (EM) | ~30% |
| Normalized EM | ~35-40%* |
SELECT ... ;) is recommended.1@article{nie2024llada,
2 title={LLaDA: Large Language Diffusion with Autoregression},
3 author={Nie, Shen and others},
4 journal={arXiv preprint arXiv:2402.XXXXX},
5 year={2024}
6}
7