Views
No views yet
occiglot/occiglot-7b-eu5 for generating SPARQL queries from German natural language questions, specifically targeting the Wikidata knowledge graph.occiglot/occiglot-7b-eu5```sparql ... ``` delimiters).1import torch
2from transformers import AutoTokenizer, BitsAndBytesConfig
3from peft import AutoPeftModelForCausalLM
4import re
5import json
6
7# Model ID for the Occiglot German v2 model
8model_id = "julioc-p/occiglot_txt_sparql_de_v2"
9
10# Configuration for 4-bit quantization
11bnb_config = BitsAndBytesConfig(
12 load_in_4bit=True,
13 bnb_4bit_quant_type="nf4",
14 bnb_4bit_compute_dtype=torch.float16,
15 bnb_4bit_use_double_quant=True,
16)
17
18# Load the model and tokenizer from the PEFT-saved directory
19model = AutoPeftModelForCausalLM.from_pretrained(
20 model_id,
21 quantization_config=bnb_config,
22 device_map="auto"
23)
24tokenizer = AutoTokenizer.from_pretrained(model_id)
25
26if tokenizer.pad_token is None:
27 tokenizer.pad_token = tokenizer.eos_token
28 model.config.pad_token_id = tokenizer.pad_token_id
29
30# SPARQL extraction function
31def extract_sparql(text):
32 code_block_match = re.search(r"```(?:sparql)?\s*(.*?)\s*```", text, re.DOTALL | re.IGNORECASE)
33 if code_block_match:
34 text_to_search = code_block_match.group(1)
35 else:
36 text_to_search = text
37
38 match = re.search(r"(SELECT|ASK|CONSTRUCT|DESCRIBE).*?\}", text_to_search, re.DOTALL | re.IGNORECASE)
39 if match:
40 return match.group(0).strip()
41 return ""
42
43question = "Wer war der amerikanische weibliche Angestellte des Barnard College?"
44example_context_json_str = '''
45{
46 "entitäten": {
47 "Barnard College": "Q167733",
48 "amerikanisch": "Q30",
49 "weiblich": "Q6581072",
50 "Angestellte": "Q5"
51 },
52 "beziehungen": {
53 "Instanz von": "P31",
54 "Arbeitgeber": "P108",
55 "Geschlecht": "P21",
56 "Land der Staatsbürgerschaft": "P27"
57 }
58}
59'''
60# System prompt template
61system_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.
62KONTEXT:
63{context}"""
64
65# Format the system message with the actual context
66formatted_system_message = system_message_template.format(context=example_context_json_str)
67
68chat_template = [
69 {"role": "system", "content": formatted_system_message},
70 {"role": "user", "content": question},
71]
72
73inputs = tokenizer.apply_chat_template(
74 chat_template,
75 tokenize=True,
76 add_generation_prompt=True,
77 return_tensors="pt"
78).to(model.device)
79
80# Generate the output
81with torch.no_grad():
82 outputs = model.generate(
83 input_ids=inputs.input_ids,
84 attention_mask=inputs.attention_mask,
85 max_new_tokens=512,
86 do_sample=True,
87 temperature=0.7,
88 top_p=0.9,
89 pad_token_id=tokenizer.pad_token_id
90 )
91
92# Decode and extract the assistant's response
93generated_text_full = tokenizer.decode(outputs[0], skip_special_tokens=True)
94assistant_response_part = generated_text_full.split("<|im_start|>assistant")[-1].split("<|im_end|>")[0].strip()
95
96cleaned_sparql = extract_sparql(assistant_response_part)
97
98print(f"Frage: {question}")
99print(f"Kontext: {example_context_json_str}")
100print(f"Generierte SPARQL: {cleaned_sparql}")
101print(f"Textausgabe (Assistent): {assistant_response_part}")julioc-p/Question-Sparql dataset. 80,000 German examples for training, which included a context field containing Wikidata entity and relationship ID mappings.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.transformers, peft (0.13.2), bitsandbytes, trl, PyTorch.4.39.3)0.43.0)0.8.6)torch==2.1.0)