File size: 12,254 Bytes
a2d635b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
350e72d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
777df97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
572b1d5
 
 
 
6b538da
777df97
572b1d5
777df97
572b1d5
f1b302b
572b1d5
a2d635b
572b1d5
 
 
f1b302b
a2d635b
777df97
 
5885a0f
777df97
a2d635b
 
f1b302b
6b538da
 
 
 
572b1d5
a2d635b
572b1d5
 
 
 
5885a0f
 
572b1d5
 
 
 
 
a2d635b
5885a0f
 
 
 
 
 
 
 
 
 
 
777df97
f1b302b
777df97
 
 
 
f1b302b
777df97
 
 
f1b302b
777df97
 
 
f1b302b
777df97
 
 
 
 
 
 
f1b302b
777df97
 
 
 
 
 
 
 
 
 
 
 
f1b302b
777df97
f1b302b
 
777df97
 
 
 
 
 
 
 
 
 
 
f1b302b
 
777df97
 
 
 
 
 
 
 
f1b302b
777df97
 
 
 
 
 
 
 
 
 
 
 
572b1d5
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
# import gradio as gr
# import faiss
# import json
# import numpy as np
# from sentence_transformers import SentenceTransformer
# from transformers import pipeline

# embed_model = SentenceTransformer('all-MiniLM-L6-v2')
# index = faiss.read_index("faiss_index.bin")  
# with open("processed_chunks.json", "r") as f:
#     chunks = json.load(f)


# #weights load automatically to the Space
# pipe = pipeline("text-generation", model="ibm-granite/granite-3.1-2b-instruct")
# # pipe = pipeline("text-generation", model="ibm-granite/granite-3.3-8b-instruct")


# def ask_hr_bot(question):
#     # Retrieval
#     query_vec = embed_model.encode([question])
#     distances, indices = index.search(np.array(query_vec).astype('float32'), k=1)
    
#     # out-of-scope questions
#     if distances[0][0] > 1.5:
#         return "I could not find information on this in the HR documents.", "N/A"

#     # Context Retrieval
#     relevant_chunk = chunks[indices[0][0]]
#     context = relevant_chunk['text']
#     source = relevant_chunk['doc_name']

#     # Grounded Generation
#     prompt = f"Context: {context}\nQuestion: {question}\nAnswer only from context. Cite source: {source}\nAnswer:"
#     res = pipe(prompt, max_new_tokens=60, do_sample=False)
    
#     answer = res[0]['generated_text'].split("Answer:")[-1].strip()
#     return answer, source


# interface = gr.Interface(
#     fn=ask_hr_bot,
#     inputs=gr.Textbox(label="Ask an HR Question"),
#     outputs=[gr.Textbox(label="Bot Answer"), gr.Textbox(label="Source Used")],
#     title="HR Knowledge Assistant",
#     description="Enterprise RAG Prototype using IBM Granite Instruct Family."
# )

# interface.launch()

# import gradio as gr
# import faiss
# import json
# import numpy as np
# import torch
# from sentence_transformers import SentenceTransformer
# from transformers import pipeline

# # 1. Load Retrieval Logic
# embed_model = SentenceTransformer('all-MiniLM-L6-v2')
# index = faiss.read_index("faiss_index.bin")
# with open("processed_chunks.json", "r") as f:
#     chunks = json.load(f)

# # (Using Path 1: Ungated models to avoid the 401 Unauthorized Error)
# MODELS = {
#     "Granite 3.1 2B": "ibm-granite/granite-3.1-2b-instruct",
#     "Qwen 2.5 1.5B": "Qwen/Qwen2.5-1.5B-Instruct",
#     "SmolLM 1.7B": "HuggingFaceTB/SmolLM-1.7B-Instruct",
#     "Phi 3.5 Mini": "microsoft/Phi-3.5-mini-instruct",
# }

# def ask_specific_model(model_name, prompt):
#     # Load model, generate, and delete to save RAM
#     pipe = pipeline("text-generation", model=MODELS[model_name], device_map="cpu")
#     res = pipe(prompt, max_new_tokens=60, do_sample=False)
#     return res[0]['generated_text'].split("Answer:")[-1].strip()

# def compare_hr_bots(question):
#     # 1. Retrieval
#     query_vec = embed_model.encode([question])
#     distances, indices = index.search(np.array(query_vec).astype('float32'), k=1)
    
#     # Fallback Rule
#     if distances[0][0] > 1.5:
#         # Yield the fallback immediately
#         yield "Out of scope", "Out of scope", "Out of scope", "Out of scope", "N/A"
#         return

#     # 2. Context Setup
#     relevant_chunk = chunks[indices[0][0]]
#     context = relevant_chunk['text']
#     source = relevant_chunk['doc_name']
#     prompt = f"Context: {context}\nQuestion: {question}\nAnswer only from context. Cite source: {source}\nAnswer:"

#     # 3. Setup progressive output array
#     # This acts as our visual placeholders
#     results = ["⏳ Waiting...", "⏳ Waiting...", "⏳ Waiting...", "⏳ Waiting..."]
    
#     # Yield the initial state so the user sees the source document immediately
#     yield results[0], results[1], results[2], results[3], source

#     # 4. Sequential Generation with Yield
#     model_names = list(MODELS.keys())
#     for i, name in enumerate(model_names):
#         # Update the current box to show it is actively generating
#         results[i] = "⚙️ Generating..."
#         yield results[0], results[1], results[2], results[3], source
        
#         # Run the model
#         ans = ask_specific_model(name, prompt)
        
#         # Save the answer and yield the updated UI
#         results[i] = ans
#         yield results[0], results[1], results[2], results[3], source

# # 5. Multi-Output Interface
# interface = gr.Interface(
#     fn=compare_hr_bots,
#     inputs=gr.Textbox(label="Ask an HR Question"),
#     outputs=[
#         gr.Textbox(label="IBM Granite 3.1"),
#         gr.Textbox(label="Alibaba Qwen 2.5 1.5B"),
#         gr.Textbox(label="HuggingFaceTB SmolLM 1.7B"),
#         gr.Textbox(label="Microsoft Phi 3.5"),
#         gr.Textbox(label="Source Used")
#     ],
#     title="RAG Model Benchmarking",
#     description="Sequential model comparison. Answers yield progressively to manage CPU RAM limits."
# )

# interface.launch()










# import gradio as gr
# import faiss
# import json
# import numpy as np
# import torch
# from sentence_transformers import SentenceTransformer
# from transformers import pipeline

# embed_model = SentenceTransformer('all-MiniLM-L6-v2')
# index = faiss.read_index("faiss_index.bin")
# with open("processed_chunks.json", "r") as f:
#     chunks = json.load(f)

# MODELS = {
#     "Granite 3.1 2B": "ibm-granite/granite-3.1-2b-instruct",
#     "Qwen 2.5 1.5B": "Qwen/Qwen2.5-1.5B-Instruct",
#     "SmolLM 1.7B": "HuggingFaceTB/SmolLM-1.7B-Instruct",
#      "Phi 3.5 Mini": "microsoft/Phi-3.5-mini-instruct"
# }

# def ask_specific_model(model_name, prompt):
#     pipe = pipeline("text-generation", model=MODELS[model_name], device_map="cpu")
#     res = pipe(prompt, max_new_tokens=60, do_sample=False)
#     return res[0]['generated_text'].split("Answer:")[-1].strip()

# def compare_hr_bots(question):
#     query_vec = embed_model.encode([question])
#     distances, indices = index.search(np.array(query_vec).astype('float32'), k=1)
    
#     if distances[0][0] > 1.5:
#         yield "Out of scope", "Out of scope", "Out of scope", "Out of scope", "N/A"
#         return

#     relevant_chunk = chunks[indices[0][0]]
#     context = relevant_chunk['text']
#     source = relevant_chunk['doc_name']
#     prompt = f"Context: {context}\nQuestion: {question}\nAnswer only from context. Cite source: {source}\nAnswer:"

#     results = ["⏳ Waiting...", "⏳ Waiting...", "⏳ Waiting...", "⏳ Waiting..."]
#     yield results[0], results[1], results[2], results[3], source

#     # Sequential Generation
#     model_names = list(MODELS.keys())
#     for i, name in enumerate(model_names):
#         results[i] = "⚙️ Generating..."
#         yield results[0], results[1], results[2], results[3], source
#         ans = ask_specific_model(name, prompt)
#         results[i] = ans
#         yield results[0], results[1], results[2], results[3], source

# interface = gr.Interface(
#     fn=compare_hr_bots,
#     inputs=gr.Textbox(label="Ask an HR Question", placeholder="e.g., How many annual leave days do I get?"),
#     outputs=[
#         gr.Textbox(label="IBM Granite 3.1 2B"),
#         gr.Textbox(label="Qwen 2.5 1.5B"),
#         gr.Textbox(label="SmolLM 1.7B"),
#         gr.Textbox(label="Microsoft Phi 3.5 Mini"),
#         gr.Textbox(label="Source Used")
#     ],
#     title="ADU Enterprise HR Knowledge Assistant: Model Benchmarking",
#     description="Comparing grounding quality across 4 open-source LLMs using Enterprise HR Policies. Please be patient since there is a limit of 16GB RAM :)"
# )

# interface.launch()


import gradio as gr
import faiss
import json
import numpy as np
import torch
import gc
from sentence_transformers import SentenceTransformer
from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer


embed_model = SentenceTransformer('all-MiniLM-L6-v2')
index = faiss.read_index("faiss_index.bin")
with open("processed_chunks.json", "r") as f:
    chunks = json.load(f)


MODELS = {
    "IBM Granite 3.1 2B": "ibm-granite/granite-3.1-2b-instruct",
    "Microsoft Phi 3.5 Mini": "microsoft/Phi-3.5-mini-instruct",
    "Qwen 2.5 1.5B": "Qwen/Qwen2.5-1.5B-Instruct",
    "SmolLM 1.7B": "HuggingFaceTB/SmolLM-1.7B-Instruct"
}


def ask_specific_model(model_name, prompt):
    pipe = pipeline("text-generation", model=MODELS[model_name], device_map="cpu")
    res = pipe(prompt, max_new_tokens=60, do_sample=False)
    return res[0]['generated_text'].split("Answer:")[-1].strip()

def compare_hr_bots(question):
    query_vec = embed_model.encode([question])
    distances, indices = index.search(np.array(query_vec).astype('float32'), k=1)
    
    if distances[0][0] > 1.5:
        yield "Out of scope", "Out of scope", "Out of scope", "Out of scope", "N/A"
        return

    relevant_chunk = chunks[indices[0][0]]
    context = relevant_chunk['text']
    source = relevant_chunk['doc_name']
    prompt = f"Context: {context}\nQuestion: {question}\nAnswer only from context. Cite source: {source}\nAnswer:"

    results = ["⏳ Waiting...", "⏳ Waiting...", "⏳ Waiting...", "⏳ Waiting..."]
    yield results[0], results[1], results[2], results[3], source

    model_names = list(MODELS.keys())
    for i, name in enumerate(model_names):
        results[i] = "⚙️ Generating..."
        yield results[0], results[1], results[2], results[3], source
        ans = ask_specific_model(name, prompt)
        results[i] = ans
        yield results[0], results[1], results[2], results[3], source



def calculate_perplexity(model_name):
    try:
        model_id = MODELS[model_name]
        
        
        sample_texts = [chunk['text'] for chunk in chunks[:3]]
        test_text = " ".join(sample_texts)
        
        
        tokenizer = AutoTokenizer.from_pretrained(model_id)
        model = AutoModelForCausalLM.from_pretrained(model_id, device_map="cpu")
        
        
        inputs = tokenizer(test_text, return_tensors="pt")
        with torch.no_grad():
            outputs = model(input_ids=inputs["input_ids"], labels=inputs["input_ids"])
            loss = outputs.loss
            
        perplexity = torch.exp(loss).item()
        
       
        del model
        del tokenizer
        del inputs
        del outputs
        gc.collect()
        
        return f"Perplexity Score: {perplexity:.2f}\n\n(Tested on internal HR policies. Lower is better.)"
        
    except Exception as e:
        return f"Error calculating perplexity: {str(e)}"



with gr.Blocks(theme=gr.themes.Soft()) as interface:
    gr.Markdown("# ADQ Enterprise HR Knowledge Assistant & Evaluation Toolkit")
    gr.Markdown("Comparing grounding quality across 4 open-source LLMs using Enterprise HR Policies. Please be patient since there is a limit of 16GB RAM :)")
    
    with gr.Tabs():
        # TAB 1 UI
        with gr.TabItem("💬 RAG Chatbot (Benchmarking)"):
            question_input = gr.Textbox(label="Ask an HR Question", placeholder="e.g., How many annual leave days do I get?")
            submit_btn = gr.Button("Compare Models")
            
            with gr.Row():
                out_granite = gr.Textbox(label="IBM Granite 3.1 2B")
                out_phi = gr.Textbox(label="Microsoft Phi 3.5 Mini")
            with gr.Row():
                out_qwen = gr.Textbox(label="Alibaba Qwen 2.5 1.5B")
                out_smol = gr.Textbox(label="HuggingFace SmolLM 1.7B")
            out_source = gr.Textbox(label="Source Document Used")
            
            submit_btn.click(
                fn=compare_hr_bots,
                inputs=question_input,
                outputs=[out_granite, out_phi, out_qwen, out_smol, out_source]
            )
            
       
        with gr.TabItem("📊 Perplexity Evaluator"):
            gr.Markdown("Select a single model to calculate its perplexity against our internal HR dataset. **Warning: Takes 30-60 seconds on CPU.**")
            
            model_dropdown = gr.Dropdown(choices=list(MODELS.keys()), label="Select Model to Evaluate", value="IBM Granite 3.1 2B")
            eval_btn = gr.Button("Calculate Perplexity")
            eval_output = gr.Textbox(label="Evaluation Result")
            
            eval_btn.click(
                fn=calculate_perplexity,
                inputs=model_dropdown,
                outputs=eval_output
            )

interface.launch()