ReshmiMaulik commited on
Commit
c4f34f9
·
verified ·
1 Parent(s): 1de551b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +78 -0
app.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import AutoTokenizer, AutoModelForCausalLM
3
+ import torch
4
+
5
+ # -----------------------------
6
+ # Load IBM Granite Model
7
+ # -----------------------------
8
+ MODEL_NAME = "ibm-granite/granite-3.3-2b-instruct"
9
+
10
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
11
+ model = AutoModelForCausalLM.from_pretrained(
12
+ MODEL_NAME,
13
+ torch_dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32,
14
+ device_map="auto"
15
+ )
16
+
17
+ # -----------------------------
18
+ # Chat Function
19
+ # -----------------------------
20
+ def chat_with_model(user_message, history):
21
+ """
22
+ history = list of [user, bot] messages
23
+ Convert to Chat template the way Granite expects:
24
+ [{"role": "user", "content": "..."}]
25
+ """
26
+ messages = []
27
+
28
+ # Load previous history into model format
29
+ if history:
30
+ for h in history:
31
+ messages.append({"role": "user", "content": h[0]})
32
+ if h[1] is not None:
33
+ messages.append({"role": "assistant", "content": h[1]})
34
+
35
+ # Add new user input
36
+ messages.append({"role": "user", "content": user_message})
37
+
38
+ # Prepare model input
39
+ inputs = tokenizer.apply_chat_template(
40
+ messages,
41
+ add_generation_prompt=True,
42
+ tokenize=True,
43
+ return_dict=True,
44
+ return_tensors="pt"
45
+ ).to(model.device)
46
+
47
+ # Generate output
48
+ output_tokens = model.generate(
49
+ **inputs,
50
+ max_new_tokens=300,
51
+ do_sample=True,
52
+ temperature=0.7,
53
+ top_p=0.9
54
+ )
55
+
56
+ # Decode only the newly generated tokens
57
+ output_text = tokenizer.decode(
58
+ output_tokens[0][inputs["input_ids"].shape[-1]:],
59
+ skip_special_tokens=True
60
+ )
61
+
62
+ return output_text
63
+
64
+
65
+ # -----------------------------
66
+ # Create Gradio UI
67
+ # -----------------------------
68
+ chatbot_ui = gr.ChatInterface(
69
+ fn=chat_with_model,
70
+ title="IBM Granite 3.3 - Chatbot",
71
+ description="Chat with IBM Granite 3.3-2B-Instruct model",
72
+ )
73
+
74
+ # -----------------------------
75
+ # Launch the App
76
+ # -----------------------------
77
+ if __name__ == "__main__":
78
+ chatbot_ui.launch()