Downloads · 30 days
24
10% of all-time downloads
julioc-p/mistral_txt_sparql_en_v2
mistral_txt_sparql_en_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 English natural language questions, specifically targeting the Wikidata knowledge graph.
Downloads · 30 days
24
10% of all-time downloads
All-time downloads
245
Public
Repo size
20 GB
Likes
0
Public
Click a slice to open those files.
.safetensors1.4 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 English natural language questions, specifically targeting the Wikidata knowledge graph.
It was fine-tuned using QLoRA with 4-bit quantization. It takes an English 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
import re
import json
# Model ID for the Mistral English v2 model
model_id = "julioc-p/mistral_txt_sparql_en_v2"
# Configuration for 4-bit quantization
bnb_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.float16,
bnb_4bit_use_double_quant=True,
)
model = AutoPeftModelForCausalLM.from_pretrained(
model_id,
quantization_config=bnb_config,
device_map="auto"
)
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 extraction function
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:
# v2 models wrap output in ```sparql ... ``` so this is the main path
text_to_search = text
match = re.search(r"(SELECT|ASK|CONSTRUCT|DESCRIBE).*?\}", text_to_search, re.DOTALL | re.IGNORECASE)
if match:
return match.group(0).strip()
return ""
question = "Who was Barnard College's American female employee?"
example_context_json_str = '''
{
"entities": {
"Barnard College": "Q167733",
"American": "Q30",
"female": "Q6581072",
"employee": "Q5"
},
"relationships": {
"instance of": "P31",
"employer": "P108",
"gender": "P21",
"country of citizenship": "P27"
}
}
'''
system_message_template = """You are an expert text to SparQL query translator. Users will ask you questions in English and you will generate a SparQL query based on the provided context encloses in ```sparql <respose_query>```.
CONTEXT:
{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,
do_sample=True,
temperature=0.7,
top_p=0.9,
pad_token_id=tokenizer.pad_token_id
)
# Decode only the generated part
generated_text_full = tokenizer.decode(outputs[0], skip_special_tokens=True)
assistant_response_part = generated_text_full.split("<|im_start|>assistant")[-1].split("<|im_end|>")[0].strip()
cleaned_sparql = extract_sparql(assistant_response_part)
print(f"Question: {question}")
print(f"Context: {example_context_json_str}")
print(f"Generated SPARQL: {cleaned_sparql}")
print(f"Assistant's Raw Response: {assistant_response_part}")
The model was fine-tuned on a subset of the julioc-p/Question-Sparql dataset. 80,000 English examples for training, which included a context field containing Wikidata entity and relationship ID mappings.
The following hyperparameters were used for fine-tuning:
r (LoRA rank): 256lora_alpha: 128lora_dropout: 0.05target_modules: "all-linear"num_train_epochs: 3optim: "adamw_torch_fused"learning_rate: 2e-4fp16: 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 result in P, R, F1 = 0.
On QALD-10 (English, N=394):
On v2 Test Set (English, N=10000):
transformers, peft (0.13.2), bitsandbytes, trl, PyTorch.4.39.3)0.43.0)0.8.6)torch==2.1.0)