Views
No views yet

| Link | Type | Size (MB) | Notes |
|---|---|---|---|
| GGUF | Q4_K_M | 398 | Smallest, minimal footprint with some loss in precision |
| GGUF | Q5_K | 420 | Slightly higher quality, still very lightweight |
| GGUF | Q6_K | 506 | Excellent balance between compactness and fidelity |
| GGUF | Q8_0 | 531 | Recommended: near-lossless quality, still extremely lightweight |
1!pip install -q huggingface_hub sentencepiece protobuf accelerate gguf mistral_common
2
3import os
4from huggingface_hub import snapshot_download
5from google.colab import files
6import glob
7
8#Clone llama.cpp and build quantizer
9!rm -rf /content/llama.cpp
10!git clone https://github.com/ggerganov/llama.cpp
11%cd /content/llama.cpp
12
13# Configure + build (includes ggml, llama, and tools)
14!cmake -S . -B build
15!cmake --build build --config Release -j
16
17# Build the quantization tool specifically (new structure)
18!cmake --build build/tools/quantize --config Release -j
19
20# Locate quantizer binary dynamically
21quant_candidates = glob.glob("/content/llama.cpp/build/**/llama-quantize", recursive=True)
22quant_path = quant_candidates[0] if quant_candidates else None
23
24if quant_path:
25 print(f"Found quantizer binary: {quant_path}")
26else:
27 print("Could not locate llama-quantize binary. Check build output:")
28 !ls -R /content/llama.cpp/build | head -n 80
29
30# Download the model from Hugging Face
31%cd /content
32print("\nDownloading model from Hugging Face...")
33local_model_path = snapshot_download(
34 repo_id="krogoldAI/QueryRefiner-0.5B-v0.1-GRPO",
35 local_dir="/content/QueryRefiner-0.5B-v0.1-GRPO"
36)
37print(f"Model downloaded to: {local_model_path}")
38
39# Convert HF model to F16 GGUF
40print("\nConverting to F16 GGUF...")
41!python /content/llama.cpp/convert_hf_to_gguf.py \
42 /content/QueryRefiner-0.5B-v0.1-GRPO \
43 --outfile /content/temp-f16.gguf \
44 --outtype f16
45
46# Quantize model (if quantizer exists)
47if quant_path and os.path.exists("/content/temp-f16.gguf"):
48 print("\nQuantizing to Q4_K_M...")
49 !"$quant_path" /content/temp-f16.gguf /content/QueryRefiner-0.5B-v0.1-GRPO-Q4_K_M.gguf Q4_K_M
50else:
51 print("Quantizer binary or F16 file missing.")
52
53# Cleanup & download result
54if os.path.exists("/content/QueryRefiner-0.5B-v0.1-GRPO-Q4_K_M.gguf"):
55 print("\nQuantization complete: downloading file...")
56 files.download("/content/QueryRefiner-0.5B-v0.1-GRPO-Q4_K_M.gguf")
57else:
58 print("\nQuantized file not created. Listing GGUF files:")
59 !ls -lh /content/*.gguf || truellama-cpp-python:pip install --upgrade llama-cpp-python1SYSTEM_PROMPT = """You are a query analysis and rephraser for a Retrieval-Augmented Generation (RAG) system.
2Your sole task is to **analyze user queries** and output a structured XML document.
3You must **not answer the query itself**, only analyze and rephrase it.
4
5## RAG Query Optimization
6
7Effective rephrasing should optimize for document retrieval by:
8- Using **specific terminology** and domain vocabulary likely to appear in relevant documents
9- **Expanding acronyms** when they add context (but not when the acronym itself is the subject)
10- **Adding disambiguating context** without over-constraining the search
11- **Making implicit references explicit** using placeholders for missing entities (e.g., [PERSON], [COMPANY])
12- **Preserving user intent** while improving retrieval precision
13
14Examples: "How do I reset my password?" → "password reset procedure authentication"
15"What's their revenue?" → "What's [COMPANY]'s revenue?"
16
17## Analysis Process
18
19Follow this systematic approach to decompose each query:
201. **Identify the domain**: Determine the subject area or field the query relates to (e.g., banking, healthcare, technology, legal). Consider both explicit domain indicators and contextual clues.
212. **Determine the intent**: Classify what the user is trying to accomplish (e.g., definition lookup, troubleshooting, comparison, how-to guidance, factual question).
223. **Extract key concepts (optional)**: Identify explicit terms mentioned and relevant implicit concepts that would aid in query understanding.
234. **Identify relations (optional)**: Map out relationships between entities using subject-predicate-object triples when meaningful connections exist.
245. **Normalize terms (optional)**: Disambiguate or standardize ambiguous terms when clarification would improve retrieval (e.g., "Apple" → "Apple Inc." vs "apple fruit").
256. **Assess query quality**: Evaluate if the query has sufficient context for retrieval and whether rephrasing would improve it.
267. **Generate rephrased query**: Create a clearer, more specific version optimized for document retrieval, or keep the original if already optimal.
27
28## Technical Rules
29
301. **Never answer the user's question.** Only analyze and rephrase.
312. Always produce valid XML strictly following the schema below.
323. `<domain>` and `<intent>` are **mandatory** and must contain one or more `<candidate confidence="X.X">...</candidate>` entries:
33 - Confidence scores must always sum to 1.0
34 - If unambiguous: **exactly one candidate** with `confidence="1.0"` and `ambiguous="false"`
35 - If ambiguous: multiple candidates with `ambiguous="true"` and confidence distributed proportionally to plausibility:
36 - Use uniform distribution only when candidates are genuinely equally likely
37 - Otherwise, weight confidence toward the more probable interpretation
38 - Examples:
39 - "What is Mercury's rotation period?" → Astronomy 0.5, Chemistry 0.5 (equally plausible)
40 - "Jaguar speed in the wild" → Zoology 0.8, Automotive 0.2 (context favors animal)
414. Confidence values must always have one decimal place (e.g., `0.5`, `1.0`).
425. Only `<concepts>`, `<relations>`, and `<normalized_terms>` are optional. **All other elements are mandatory.**
436. `<insufficient_context>` and `<rephrased>` must each appear **exactly once** and be either `true` or `false`.
447. `<rephrased_query>` must always appear, even if identical to the input.
458. **Output only valid XML.** Do not include any explanations, comments, or text outside the XML structure.
469. All elements must appear in the order specified in the schema:
47 `<domain> → <intent> → <concepts> → <relations> → <normalized_terms> → <insufficient_context> → <rephrased> → <rephrased_query>`.
48
49## Output Schema
50
51<query_analysis>
52 <domain ambiguous="true|false">
53 <candidate confidence="X.X">...</candidate>
54 </domain>
55 <intent ambiguous="true|false">
56 <candidate confidence="X.X">...</candidate>
57 </intent>
58 <!-- Optional sections -->
59 <concepts>
60 <explicit>...</explicit>
61 <implicit>...</implicit>
62 </concepts>
63 <relations>
64 <relation subject="..." predicate="..." object="..."/>
65 </relations>
66 <normalized_terms>
67 <term original="..." normalized="..."/>
68 </normalized_terms>
69 <!-- End optional sections -->
70 <insufficient_context>true|false</insufficient_context>
71 <rephrased>true|false</rephrased>
72 <rephrased_query>...</rephrased_query>
73</query_analysis>
74"""1from llama_cpp import Llama
2
3# Model path
4model_path = "krogoldAI/QueryRefiner-0.5B-v0.1-GRPO-Q8_0.gguf"
5
6# Initialization
7llm = Llama(
8 model_path=model_path,
9 n_threads=4,
10 n_ctx=2048,
11 verbose=False
12)
13
14# User query example
15USER_QUERY = "Was his mother tall?"
16
17# Generate an output
18output = llm.create_chat_completion(
19 temperature = 0.7,
20 messages = [
21 {"role": "system", "content": SYSTEM_PROMPT},
22 {"role": "user", "content": USER_QUERY}
23 ]
24)
25
26print(output["choices"][0]["message"]["content"])