Downloads · 30 days
5
5% of all-time downloads
julioc-p/mistral_txt_sparql_de_v2
mistral_txt_sparql_de_v2 is a machine learning model from julioc-p. Use it for the machine learning task on the model card, and read the license before you ship it in a product. It is set up for peft. The card lists the license as mit.
This model is a fine-tuned version of mistralai/Mistral-7B-v0.1 for generating SPARQL queries from German natural language questions, specifically targeting the Wikidata knowledge graph.
Downloads · 30 days
5
5% of all-time downloads
All-time downloads
111
Public
Repo size
21.9 GB
Likes
0
Public
Click a slice to open those files.
.safetensors3.7 GB · 100%
From the Hugging Face model README
This model is a fine-tuned version of mistralai/Mistral-7B-v0.1 for generating SPARQL queries from German natural language questions, specifically targeting the Wikidata knowledge graph.
It was fine-tuned using QLoRA with 4-bit quantization. It takes a German natural language question and corresponding entity/relationship context as input and aims to produce a SPARQL query for Wikidata. This model is part of experiments investigating continual multilingual pre-training.
mistralai/Mistral-7B-v0.1```sparql ... ``` delimiters).The following Python script provides an example of how to load the model and tokenizer to generate a SPARQL query.
import torch
from transformers import AutoTokenizer, BitsAndBytesConfig
from peft import AutoPeftModelForCausalLM # Use AutoPeftModelForCausalLM for v2 models
import re
import json
# Model ID for the Mistral German v2 model
model_id = "julioc-p/mistral_txt_sparql_de_v2"
# Configuration for 4-bit quantization (as per v2 setup in thesis/script)
bnb_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.float16,
bnb_4bit_use_double_quant=True,
)
# Load the model and tokenizer
print(f"Loading model: {model_id}")
model = AutoPeftModelForCausalLM.from_pretrained(
model_id,
quantization_config=bnb_config,
device_map="auto"
)
print(f"Loading tokenizer for: {model_id}")
tokenizer = AutoTokenizer.from_pretrained(model_id)
if tokenizer.pad_token is None:
tokenizer.pad_token = tokenizer.eos_token
model.config.pad_token_id = tokenizer.pad_token_id
sparql_pattern_strict = re.compile(
r"""
(SELECT|ASK|CONSTRUCT|DESCRIBE) # Match the starting keyword
.*? # Match any characters non-greedily
\} # Match the closing brace of the main block
( # Start of optional block for trailing clauses
(?: # Non-capturing group for one or more trailing clauses
\s*
(?: # Clause alternatives
(?:(?:GROUP|ORDER)\s+BY|HAVING)\s+.+?\s*(?=\s*(?:(?:GROUP|ORDER)\s+BY|HAVING|LIMIT|OFFSET|VALUES|$)) |
LIMIT\s+\d+ |
OFFSET\s+\d+ |
VALUES\s*(?:\{.*?\}|\w+|\(.*?\))
)
)* # Match zero or more clauses
)
""",
re.DOTALL | re.IGNORECASE | re.VERBOSE
)
def extract_sparql(text):
code_block_match = re.search(r"```(?:sparql)?\s*(.*?)\s*```", text, re.DOTALL | re.IGNORECASE)
if code_block_match:
text_to_search = code_block_match.group(1)
else:
text_to_search = text # Search directly if no markdown code block
match = sparql_pattern_strict.search(text_to_search)
if match:
return match.group(0).strip()
else:
fallback_match = re.search(r"(SELECT|ASK|CONSTRUCT|DESCRIBE).*?\}", text_to_search, re.DOTALL | re.IGNORECASE)
if fallback_match:
return fallback_match.group(0).strip()
return ""
# --- Example usage ---
question = "Wer war der amerikanische weibliche Angestellte des Barnard College?"
example_context_json_str = '''
{
"entitäten": {
"Barnard College": "Q167733",
"amerikanisch": "Q30",
"weiblich": "Q6581072",
"Angestellte": "Q5"
},
"beziehungen": {
"Instanz von": "P31",
"Arbeitgeber": "P108",
"Geschlecht": "P21",
"Land der Staatsbürgerschaft": "P27"
}
}
'''
# System prompt template for v2 models (German)
system_message_template = """Sie sind ein Experte für die Übersetzung von Text in SPARQL-Anfragen. Benutzer werden Ihnen Fragen auf Deutsch stellen, und Sie werden eine SPARQL-Anfrage basierend auf dem bereitgestellten Kontext generieren, der in ```sparql <Antwortanfrage>``` eingeschlossen ist.
KONTEXT:
{context}"""
# Format the system message with the actual context
formatted_system_message = system_message_template.format(context=example_context_json_str)
chat_template = [
{"role": "system", "content": formatted_system_message},
{"role": "user", "content": question},
]
inputs = tokenizer.apply_chat_template(
chat_template,
tokenize=True,
add_generation_prompt=True,
return_tensors="pt"
).to(model.device)
# Generate the output
with torch.no_grad():
outputs = model.generate(
input_ids=inputs.input_ids,
attention_mask=inputs.attention_mask,
max_new_tokens=512, # From your v2 generation script
do_sample=True, # From your v2 generation script
temperature=0.7, # Common for sampling
top_p=0.9, # Common for sampling
pad_token_id=tokenizer.pad_token_id
)
# Decode only the generated part
generated_text_full = tokenizer.decode(outputs[0], skip_special_tokens=True)
# Extract only assistant's response (ChatML format specific extraction)
assistant_response_part = ""
if "<|im_start|>assistant" in generated_text_full: # Specific to ChatML after template application
assistant_response_part = generated_text_full.split("<|im_start|>assistant")[-1].split("<|im_end|>")[0].strip()
elif "assistant\n" in generated_text_full: # More generic if template output varies
assistant_response_part = generated_text_full.split("assistant\n")[-1].strip()
else:
input_length = inputs.input_ids.shape[1]
assistant_response_part = tokenizer.decode(outputs[0][input_length:], skip_special_tokens=True).strip()
cleaned_sparql = extract_sparql(assistant_response_part)
print(f"Frage: {question}")
print(f"Kontext: {example_context_json_str}")
print(f"Generierte SPARQL: {cleaned_sparql}")
print(f"Textausgabe (Assistent): {assistant_response_part}")
The model was fine-tuned on a subset of the julioc-p/Question-Sparql dataset. 80,000 German examples
The following hyperparameters were used:
r (LoRA rank): 256lora_alpha: 128lora_dropout: 0.05target_modules: "all-linear"task_type: "CAUSAL_LM"num_train_epochs: 3optim: "adamw_torch_fused"learning_rate: 2e-4weight_decay: 0.05fp16: Truemax_grad_norm: 0.3warmup_ratio: 0.03lr_scheduler_type: "constant"packing: Truenoise_alpha: 5load_in_4bit: Truebnb_4bit_quant_type: "nf4"bnb_4bit_compute_dtype: torch.float16bnb_4bit_use_double_quant: Truejulioc-p/Question-Sparql dataset, including context.QALD standard macro-averaged F1-score, Precision, and Recall. Non-executable queries: P, R, F1 = 0. Executable Queries % tracked.
On QALD-10 (German, N=394):
On v2 Test Set (German, N=10000):
transformers, peft (0.13.2), bitsandbytes, trl, PyTorch.4.39.3)0.43.0)0.8.6)torch==2.1.0)