tarun5986 commited on
Commit
eab01ab
Β·
verified Β·
1 Parent(s): 6678872

Upload folder using huggingface_hub

Browse files
Files changed (3) hide show
  1. README.md +7 -7
  2. app.py +251 -0
  3. requirements.txt +5 -0
README.md CHANGED
@@ -1,12 +1,12 @@
1
  ---
2
- title: MicroGuard
3
- emoji: πŸ“‰
4
  colorFrom: blue
5
- colorTo: pink
6
  sdk: gradio
7
- sdk_version: 6.9.0
8
  app_file: app.py
9
- pinned: false
 
 
10
  ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: MicroGuard - RAG Faithfulness Detector
3
+ emoji: πŸ›‘οΈ
4
  colorFrom: blue
5
+ colorTo: green
6
  sdk: gradio
7
+ sdk_version: "4.44.0"
8
  app_file: app.py
9
+ pinned: true
10
+ license: apache-2.0
11
+ suggested_hardware: cpu-basic
12
  ---
 
 
app.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ MicroGuard β€” RAG Faithfulness Detector
3
+ Free, real-time, privacy-preserving quality checker for RAG systems.
4
+ """
5
+
6
+ import gradio as gr
7
+ import torch
8
+ import torch.nn.functional as F
9
+ import time
10
+ import json
11
+ import os
12
+ from transformers import AutoModelForCausalLM, AutoTokenizer
13
+ from peft import PeftModel
14
+
15
+ # ─── Configuration ───
16
+ MODEL_CONFIGS = {
17
+ "Gemma-270M (Fastest)": {
18
+ "base": "google/gemma-3-270m-it",
19
+ "adapter": "tarun5986/MicroGuard-Gemma-270M",
20
+ },
21
+ "Qwen-0.5B (Balanced)": {
22
+ "base": "Qwen/Qwen2.5-0.5B-Instruct",
23
+ "adapter": "tarun5986/MicroGuard-Qwen-0.5B",
24
+ },
25
+ "Gemma-1B (Best Accuracy)": {
26
+ "base": "google/gemma-3-1b-it",
27
+ "adapter": "tarun5986/MicroGuard-Gemma-1B",
28
+ },
29
+ }
30
+
31
+ DEFAULT_MODEL = "Gemma-270M (Fastest)"
32
+
33
+ current_model = None
34
+ current_tokenizer = None
35
+ current_model_name = None
36
+ faithful_ids = None
37
+ unfaithful_ids = None
38
+
39
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
40
+ DTYPE = torch.float16 if DEVICE == "cuda" else torch.float32
41
+
42
+ SYSTEM_PROMPT = "You are a faithfulness evaluator for RAG systems. You must respond with exactly one word."
43
+ USER_TEMPLATE = """Context: {context}
44
+ Question: {query}
45
+ Answer: {answer}
46
+
47
+ Is every claim in the answer fully supported by the context? Respond with exactly one word: FAITHFUL or UNFAITHFUL."""
48
+
49
+
50
+ def load_model(model_choice):
51
+ global current_model, current_tokenizer, current_model_name, faithful_ids, unfaithful_ids
52
+
53
+ if model_choice == current_model_name:
54
+ return f"Model loaded: {model_choice}"
55
+
56
+ config = MODEL_CONFIGS[model_choice]
57
+
58
+ try:
59
+ tokenizer = AutoTokenizer.from_pretrained(config["base"], trust_remote_code=True)
60
+ if tokenizer.pad_token is None:
61
+ tokenizer.pad_token = tokenizer.eos_token
62
+
63
+ base_model = AutoModelForCausalLM.from_pretrained(
64
+ config["base"], torch_dtype=DTYPE, trust_remote_code=True
65
+ )
66
+ model = PeftModel.from_pretrained(base_model, config["adapter"])
67
+ model = model.to(DEVICE)
68
+ model.eval()
69
+
70
+ current_model = model
71
+ current_tokenizer = tokenizer
72
+ current_model_name = model_choice
73
+ faithful_ids = tokenizer.encode("FAITHFUL", add_special_tokens=False)
74
+ unfaithful_ids = tokenizer.encode("UNFAITHFUL", add_special_tokens=False)
75
+
76
+ return f"Loaded: {model_choice}"
77
+ except Exception as e:
78
+ return f"Error: {str(e)}"
79
+
80
+
81
+ def check_faithfulness(context, question, answer, model_choice):
82
+ global current_model, current_tokenizer, faithful_ids, unfaithful_ids
83
+
84
+ if not context or not answer:
85
+ return "", "Please provide both context and answer.", ""
86
+
87
+ if model_choice != current_model_name:
88
+ status = load_model(model_choice)
89
+ if "Error" in status:
90
+ return "", status, ""
91
+
92
+ context = context[:900]
93
+ question = (question or "N/A")[:200]
94
+ answer = answer[:400]
95
+
96
+ msg = USER_TEMPLATE.format(context=context, query=question, answer=answer)
97
+ messages = [{"role": "user", "content": SYSTEM_PROMPT + "\n\n" + msg}]
98
+
99
+ try:
100
+ prompt = current_tokenizer.apply_chat_template(
101
+ messages, tokenize=False, add_generation_prompt=True
102
+ )
103
+ except Exception:
104
+ prompt = f"<|im_start|>user\n{SYSTEM_PROMPT}\n\n{msg}<|im_end|>\n<|im_start|>assistant\n"
105
+
106
+ inputs = current_tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512)
107
+ inputs = {k: v.to(DEVICE) for k, v in inputs.items()}
108
+
109
+ start_time = time.time()
110
+ with torch.no_grad():
111
+ outputs = current_model(**inputs)
112
+ logits = outputs.logits[:, -1, :]
113
+ f_score = logits[0, faithful_ids[0]].item()
114
+ u_score = logits[0, unfaithful_ids[0]].item()
115
+ latency = (time.time() - start_time) * 1000
116
+
117
+ scores = torch.tensor([f_score, u_score])
118
+ probs = F.softmax(scores, dim=0)
119
+ confidence = probs.max().item() * 100
120
+
121
+ if f_score > u_score:
122
+ verdict = "FAITHFUL"
123
+ color = "#22c55e"
124
+ explanation = "The answer appears to be supported by the provided context."
125
+ else:
126
+ verdict = "UNFAITHFUL"
127
+ color = "#ef4444"
128
+ explanation = "The answer may contain claims not supported by the context."
129
+
130
+ result_html = f"""
131
+ <div style="text-align: center; padding: 30px; border-radius: 12px; background: linear-gradient(135deg, {color}15, {color}05);">
132
+ <div style="font-size: 56px; font-weight: 800; color: {color}; margin: 0; letter-spacing: 2px;">{verdict}</div>
133
+ <div style="font-size: 18px; color: #666; margin-top: 8px;">Confidence: {confidence:.1f}%</div>
134
+ <div style="font-size: 13px; color: #999; margin-top: 4px;">{latency:.0f}ms | {current_model_name} | Zero API cost</div>
135
+ </div>
136
+ """
137
+
138
+ details = f"""**{explanation}**
139
+
140
+ | Metric | Value |
141
+ |--------|-------|
142
+ | Verdict | {verdict} |
143
+ | Confidence | {confidence:.1f}% |
144
+ | Latency | {latency:.0f}ms |
145
+ | Model | {current_model_name} |
146
+
147
+ *All processing runs locally. No data sent to external APIs.*"""
148
+
149
+ return result_html, details, f"{latency:.0f}ms"
150
+
151
+
152
+ # ─── Examples ───
153
+ EXAMPLES = [
154
+ [
155
+ "The Eiffel Tower is a wrought-iron lattice tower on the Champ de Mars in Paris, France. It was designed by engineer Gustave Eiffel and built from 1887 to 1889 as the centerpiece of the 1889 World's Fair.",
156
+ "Who designed the Eiffel Tower?",
157
+ "The Eiffel Tower was designed by engineer Gustave Eiffel. It was built between 1887 and 1889 for the World's Fair in Paris.",
158
+ ],
159
+ [
160
+ "The Eiffel Tower is a wrought-iron lattice tower on the Champ de Mars in Paris, France. It was designed by engineer Gustave Eiffel and built from 1887 to 1889 as the centerpiece of the 1889 World's Fair.",
161
+ "Who designed the Eiffel Tower?",
162
+ "The Eiffel Tower was designed by Alexander Graham Bell in 1920 and is located in London, England.",
163
+ ],
164
+ [
165
+ "Python was conceived in the late 1980s by Guido van Rossum at Centrum Wiskunde & Informatica (CWI) in the Netherlands. Its first version, Python 0.9.0, was released in February 1991.",
166
+ "When was Python first released?",
167
+ "Python was first released in February 1991. It was created by Guido van Rossum while working at CWI in the Netherlands.",
168
+ ],
169
+ [
170
+ "Python was conceived in the late 1980s by Guido van Rossum at Centrum Wiskunde & Informatica (CWI) in the Netherlands. Its first version, Python 0.9.0, was released in February 1991.",
171
+ "When was Python first released?",
172
+ "Python was created by James Gosling at Sun Microsystems and first released in 1995. It is primarily used for building Android applications.",
173
+ ],
174
+ ]
175
+
176
+ # ─── Interface ───
177
+ DESCRIPTION = """
178
+ # MicroGuard: RAG Faithfulness Detector
179
+
180
+ **Instantly check if your RAG system's answers are faithful to the retrieved context.**
181
+
182
+ No API keys. No data leaves your device. Completely free.
183
+
184
+ Built on fine-tuned sub-1B parameter language models. [Paper](https://github.com/tarun-ks/MicroGuard) | [Models](https://huggingface.co/tarun5986) | [GitHub](https://github.com/tarun-ks/MicroGuard)
185
+ """
186
+
187
+ with gr.Blocks(
188
+ title="MicroGuard β€” RAG Faithfulness Detector",
189
+ theme=gr.themes.Soft(),
190
+ css=".gradio-container {max-width: 900px !important}",
191
+ ) as demo:
192
+
193
+ gr.Markdown(DESCRIPTION)
194
+
195
+ with gr.Row():
196
+ model_selector = gr.Dropdown(
197
+ choices=list(MODEL_CONFIGS.keys()),
198
+ value=DEFAULT_MODEL,
199
+ label="Model",
200
+ scale=3,
201
+ )
202
+ latency_display = gr.Textbox(label="Latency", interactive=False, scale=1)
203
+
204
+ with gr.Row():
205
+ with gr.Column(scale=3):
206
+ context_input = gr.Textbox(
207
+ label="Retrieved Context",
208
+ placeholder="Paste the document or passage your RAG system retrieved...",
209
+ lines=6,
210
+ )
211
+ question_input = gr.Textbox(
212
+ label="User Question (optional)",
213
+ placeholder="What did the user ask?",
214
+ lines=1,
215
+ )
216
+ answer_input = gr.Textbox(
217
+ label="Generated Answer",
218
+ placeholder="Paste the answer your RAG system generated...",
219
+ lines=3,
220
+ )
221
+ check_btn = gr.Button("Check Faithfulness", variant="primary", size="lg")
222
+
223
+ with gr.Column(scale=2):
224
+ result_html = gr.HTML()
225
+ details_output = gr.Markdown()
226
+
227
+ check_btn.click(
228
+ fn=check_faithfulness,
229
+ inputs=[context_input, question_input, answer_input, model_selector],
230
+ outputs=[result_html, details_output, latency_display],
231
+ )
232
+
233
+ gr.Examples(
234
+ examples=EXAMPLES,
235
+ inputs=[context_input, question_input, answer_input],
236
+ label="Try these examples (first two faithful, last two unfaithful)",
237
+ )
238
+
239
+ gr.Markdown("""
240
+ ---
241
+ **How it works:** MicroGuard fine-tunes small language models with LoRA on 127K+ faithfulness-labeled examples from RAGBench, RAGTruth, and HaluBench. At inference, constrained decoding compares FAITHFUL vs UNFAITHFUL logits for deterministic classification with zero garbage outputs.
242
+
243
+ **Models:** [Gemma-270M](https://huggingface.co/tarun5986/MicroGuard-Gemma-270M) | [Qwen-0.5B](https://huggingface.co/tarun5986/MicroGuard-Qwen-0.5B) | [Gemma-1B](https://huggingface.co/tarun5986/MicroGuard-Gemma-1B) | [SmolLM-135M](https://huggingface.co/tarun5986/MicroGuard-SmolLM-135M) | [TinyLlama-1.1B](https://huggingface.co/tarun5986/MicroGuard-TinyLlama-1.1B)
244
+ """)
245
+
246
+
247
+ if __name__ == "__main__":
248
+ print(f"Loading default model: {DEFAULT_MODEL}")
249
+ load_model(DEFAULT_MODEL)
250
+ print("Starting MicroGuard demo...")
251
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ torch
2
+ transformers
3
+ peft
4
+ accelerate
5
+ gradio>=4.0