Views
No views yet
mistralai/Mistral-7B-Instruct-v0.1 for generating SPARQL queries from German natural language questions, specifically targeting the Wikidata knowledge graph.mistralai/Mistral-7B-Instruct-v0.11import torch
2from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
3import re
4
5model_id = "julioc-p/mistral_de_txt_sparql_4bit"
6base_model_for_tokenizer = "mistralai/Mistral-7B-Instruct-v0.1"
7
8# Configuration for 4-bit quantization
9bnb_config = BitsAndBytesConfig(
10 load_in_4bit=True,
11 bnb_4bit_quant_type="nf4",
12 bnb_4bit_compute_dtype=torch.float16,
13 bnb_4bit_use_double_quant=False,
14)
15
16model = AutoModelForCausalLM.from_pretrained(
17 model_id,
18 quantization_config=bnb_config,
19 device_map="auto" # "cuda" in your script, "auto" is generally more flexible
20)
21tokenizer = AutoTokenizer.from_pretrained(base_model_for_tokenizer)
22
23if tokenizer.pad_token is None:
24 tokenizer.pad_token = tokenizer.eos_token
25model.config.pad_token_id = tokenizer.pad_token_id
26
27
28sparql_pattern_strict = re.compile(
29 r"""
30 (SELECT|ASK|CONSTRUCT|DESCRIBE) # Match SPARQL query type
31 .*? # Match any characters (non-greedy)
32 \} # Match the first closing curly brace
33 ( # Start of optional block for trailing clauses
34 (?: # Non-capturing group for one or more trailing clauses
35 \s* # Match any whitespace
36 (?: # Non-capturing group for specific clauses
37 (?:(?:GROUP|ORDER)\s+BY|HAVING)\s+.+?\s*(?=\s*(?:(?:GROUP|ORDER)\s+BY|HAVING|LIMIT|OFFSET|VALUES|$)) | # GROUP BY, ORDER BY, HAVING
38 LIMIT\s+\d+ | # LIMIT clause
39 OFFSET\s+\d+ | # OFFSET clause
40 VALUES\s*(?:\{.*?\}|\w+|\(.*?\)) # VALUES clause
41 )
42 )* # Match zero or more trailing clauses
43 )
44 """,
45 re.DOTALL | re.IGNORECASE | re.VERBOSE,
46)
47
48def extract_sparql(text):
49 code_block_match = re.search(
50 r"```(?:sparql)?\s*(.*?)\s*```", text, re.DOTALL | re.IGNORECASE
51 )
52 if code_block_match:
53 text_to_search = code_block_match.group(1)
54 else:
55 text_to_search = text
56
57 match = sparql_pattern_strict.search(text_to_search)
58 if match:
59 return match.group(0).strip()
60 else:
61 # Fallback to simpler regex if strict pattern doesn't match
62 fallback_match = re.search(
63 r"(SELECT|ASK|CONSTRUCT|DESCRIBE).*?\}",
64 text_to_search,
65 re.DOTALL | re.IGNORECASE,
66 )
67 if fallback_match:
68 return fallback_match.group(0).strip()
69 return ""
70
71# --- Example usage ---
72question = "Was ist der Siedepunkt von Wasser?"
73knowledge_graph_target = "Wikidata"
74
75prompt_content = f"Write a SparQL query that answers this request: '{question}' from the knowledge graph {knowledge_graph_target}."
76
77chat_template = [
78 {"role": "user", "content": prompt_content},
79]
80
81inputs = tokenizer.apply_chat_template(
82 chat_template,
83 tokenize=True,
84 add_generation_prompt=True,
85 return_tensors="pt"
86).to(model.device)
87
88# Generate the output
89with torch.no_grad():
90 outputs = model.generate(
91 input_ids=inputs,
92 max_new_tokens=512,
93 do_sample=True,
94 pad_token_id=tokenizer.pad_token_id
95 )
96
97generated_text_assistant_part = tokenizer.decode(outputs[0][inputs.shape[1]:], skip_special_tokens=True)
98cleaned_sparql = extract_sparql(generated_text_assistant_part)
99
100print(f"Frage: {question}")
101print(f"Generierte SPARQL: {cleaned_sparql}")
102print(f"Rohe generierte Textausgabe (Assistent): {generated_text_assistant_part}")julioc-p/Question-Sparql dataset. Specifically, for the v1.1 Mistral German model, a 35,000-sample German subset was used.r (LoRA rank): 16 (Adjusted from 64 for Mistral due to stability, as per thesis)lora_alpha: 16 (Maintained from initial v1 setup, or potentially adjusted with r)lora_dropout: 0.1bias: "none"task_type: "CAUSAL_LM"target_modules: "q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj" (Note: lm_head was removed for Mistral v1.1, as per thesis page 39)num_train_epochs: 5per_device_train_batch_size: 1gradient_accumulation_steps: 8gradient_checkpointing: Trueoptim: "paged_adamw_32bit"learning_rate: 1e-5weight_decay: 0.05bf16: Falsefp16: Truemax_grad_norm: 1.0warmup_ratio: 0.01lr_scheduler_type: "cosine"group_by_length: Truepacking: Falseload_in_4bit: Truebnb_4bit_quant_type: "nf4"bnb_4bit_compute_dtype: torch.float16bnb_4bit_use_double_quant: Falsejulioc-p/Question-Sparql dataset (Wikidata-focused).transformers, peft (0.13.2), bitsandbytes, trl, PyTorch.4.39.3)0.43.0)0.8.6)torch==2.1.0)