HAMMALE commited on
Commit
0ce6a8e
·
verified ·
1 Parent(s): e1f72cd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +121 -59
app.py CHANGED
@@ -1,8 +1,9 @@
1
  import gradio as gr
2
- from transformers import AutoTokenizer, AutoModelForCausalLM
3
  import torch
 
4
 
5
- # Global variables to store current model and tokenizer
6
  current_model = None
7
  current_tokenizer = None
8
  current_model_name = None
@@ -12,114 +13,175 @@ def load_model(model_name):
12
  global current_model, current_tokenizer, current_model_name
13
 
14
  if current_model_name == model_name:
15
- return f"Model {model_name} is already loaded."
16
 
17
  try:
18
  print(f"Loading model: {model_name}")
19
  current_tokenizer = AutoTokenizer.from_pretrained(model_name)
 
 
20
  current_model = AutoModelForCausalLM.from_pretrained(
21
  model_name,
22
  torch_dtype=torch.float16,
23
  device_map="auto",
24
- low_cpu_mem_usage=True
 
25
  )
 
26
  current_model_name = model_name
27
- return f"✓ Successfully loaded {model_name}"
28
  except Exception as e:
29
- return f"Error loading model: {str(e)}"
30
 
31
- def chat(message, history, model_choice):
32
- """Process chat messages"""
33
  global current_model, current_tokenizer, current_model_name
34
 
35
- # Load model if not loaded or if different model selected
36
  if current_model_name != model_choice:
 
37
  status = load_model(model_choice)
38
  if "Error" in status:
39
- return status
 
40
 
41
- # Prepare conversation history
42
  conversation = []
43
- for user_msg, assistant_msg in history:
 
 
 
44
  conversation.append({"role": "user", "content": user_msg})
45
  if assistant_msg:
46
  conversation.append({"role": "assistant", "content": assistant_msg})
47
  conversation.append({"role": "user", "content": message})
48
 
49
- # Generate response
50
  try:
 
51
  inputs = current_tokenizer.apply_chat_template(
52
  conversation,
53
  return_tensors="pt",
54
  add_generation_prompt=True
55
  ).to(current_model.device)
56
 
57
- outputs = current_model.generate(
58
- inputs,
59
- max_new_tokens=512,
60
- temperature=0.7,
61
- top_p=0.9,
62
- do_sample=True,
63
- pad_token_id=current_tokenizer.eos_token_id
64
  )
65
 
66
- response = current_tokenizer.decode(outputs[0][inputs.shape[1]:], skip_special_tokens=True)
67
- return response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  except Exception as e:
69
- return f"Error generating response: {str(e)}"
70
 
71
  # Create Gradio interface
72
  with gr.Blocks(title="SauLM Legal Assistant", theme=gr.themes.Soft()) as demo:
73
- gr.Markdown("""
74
- # ⚖️ SauLM Legal Assistant
75
- Chat with specialized legal language models. Select a model and start your conversation.
76
- """)
77
 
78
  with gr.Row():
79
- model_dropdown = gr.Dropdown(
80
- choices=[
81
- "Equall/SaulLM-54B-Instruct",
82
- "Equall/SaulLM-141B-Instruct",
83
- "Equall/Saul-7B-Instruct-v1"
84
- ],
85
- value="Equall/Saul-7B-Instruct-v1",
86
- label="Select Model",
87
- info="Choose which SauLM model to use"
88
- )
 
 
 
89
 
90
  chatbot = gr.Chatbot(
91
- label="Legal Assistant Chat",
92
- height=500,
93
- show_copy_button=True
 
94
  )
95
 
96
  with gr.Row():
97
  msg = gr.Textbox(
98
- label="Your message",
99
- placeholder="Ask a legal question...",
100
- scale=4
 
 
101
  )
102
  submit = gr.Button("Send", scale=1, variant="primary")
103
 
104
- clear = gr.Button("Clear Chat")
105
-
106
- gr.Markdown("""
107
- ### About SauLM Models
108
- - **Saul-7B**: Smallest and fastest model, good for quick responses
109
- - **SaulLM-54B**: Balanced performance and quality
110
- - **SaulLM-141B**: Most capable model, best for complex legal queries
111
-
112
- *Note: Larger models require more memory and take longer to load.*
113
- """)
 
 
 
 
 
 
 
 
 
 
 
 
114
 
115
- # Event handlers
116
- msg.submit(chat, [msg, chatbot, model_dropdown], chatbot).then(
117
- lambda: "", None, msg
 
 
 
 
 
 
118
  )
119
- submit.click(chat, [msg, chatbot, model_dropdown], chatbot).then(
120
- lambda: "", None, msg
 
 
 
 
 
 
 
121
  )
122
- clear.click(lambda: None, None, chatbot)
 
123
 
124
  if __name__ == "__main__":
 
125
  demo.launch()
 
1
  import gradio as gr
2
+ from transformers import AutoTokenizer, AutoModelForCausalLM, TextIteratorStreamer
3
  import torch
4
+ from threading import Thread
5
 
6
+ # Global variables
7
  current_model = None
8
  current_tokenizer = None
9
  current_model_name = None
 
13
  global current_model, current_tokenizer, current_model_name
14
 
15
  if current_model_name == model_name:
16
+ return f"Model {model_name.split('/')[-1]} already loaded"
17
 
18
  try:
19
  print(f"Loading model: {model_name}")
20
  current_tokenizer = AutoTokenizer.from_pretrained(model_name)
21
+
22
+ # Optimized loading for speed
23
  current_model = AutoModelForCausalLM.from_pretrained(
24
  model_name,
25
  torch_dtype=torch.float16,
26
  device_map="auto",
27
+ low_cpu_mem_usage=True,
28
+ use_cache=True # Enable KV cache for faster generation
29
  )
30
+ current_model.eval() # Set to evaluation mode
31
  current_model_name = model_name
32
+ return f"Model {model_name.split('/')[-1]} loaded successfully"
33
  except Exception as e:
34
+ return f"Error: {str(e)}"
35
 
36
+ def chat_stream(message, history, model_choice):
37
+ """Stream chat responses for real-time display"""
38
  global current_model, current_tokenizer, current_model_name
39
 
40
+ # Load model if needed
41
  if current_model_name != model_choice:
42
+ yield history + [[message, "Loading model, please wait..."]]
43
  status = load_model(model_choice)
44
  if "Error" in status:
45
+ yield history + [[message, status]]
46
+ return
47
 
48
+ # Build conversation history (keep it short for speed)
49
  conversation = []
50
+ # Only use last 3 exchanges to keep context short
51
+ recent_history = history[-3:] if len(history) > 3 else history
52
+
53
+ for user_msg, assistant_msg in recent_history:
54
  conversation.append({"role": "user", "content": user_msg})
55
  if assistant_msg:
56
  conversation.append({"role": "assistant", "content": assistant_msg})
57
  conversation.append({"role": "user", "content": message})
58
 
 
59
  try:
60
+ # Prepare inputs
61
  inputs = current_tokenizer.apply_chat_template(
62
  conversation,
63
  return_tensors="pt",
64
  add_generation_prompt=True
65
  ).to(current_model.device)
66
 
67
+ # Setup streaming
68
+ streamer = TextIteratorStreamer(
69
+ current_tokenizer,
70
+ skip_prompt=True,
71
+ skip_special_tokens=True
 
 
72
  )
73
 
74
+ # Optimized generation parameters for SPEED
75
+ generation_kwargs = {
76
+ "input_ids": inputs,
77
+ "streamer": streamer,
78
+ "max_new_tokens": 256, # Reduced for faster responses
79
+ "temperature": 0.7,
80
+ "top_p": 0.9,
81
+ "top_k": 50, # Limit vocabulary for speed
82
+ "do_sample": True,
83
+ "pad_token_id": current_tokenizer.eos_token_id,
84
+ "repetition_penalty": 1.1,
85
+ "num_beams": 1 # No beam search for speed
86
+ }
87
+
88
+ # Start generation in separate thread
89
+ thread = Thread(target=current_model.generate, kwargs=generation_kwargs)
90
+ thread.start()
91
+
92
+ # Stream the response
93
+ partial_response = ""
94
+ for new_text in streamer:
95
+ partial_response += new_text
96
+ yield history + [[message, partial_response]]
97
+
98
  except Exception as e:
99
+ yield history + [[message, f"Error: {str(e)}"]]
100
 
101
  # Create Gradio interface
102
  with gr.Blocks(title="SauLM Legal Assistant", theme=gr.themes.Soft()) as demo:
103
+
104
+ gr.Markdown("# SauLM Legal Assistant")
105
+ gr.Markdown("Ask your legal questions in French or English")
 
106
 
107
  with gr.Row():
108
+ with gr.Column(scale=3):
109
+ model_dropdown = gr.Dropdown(
110
+ choices=[
111
+ "Equall/Saul-7B-Instruct-v1",
112
+ "Equall/SaulLM-54B-Instruct",
113
+ "Equall/SaulLM-141B-Instruct"
114
+ ],
115
+ value="Equall/Saul-7B-Instruct-v1",
116
+ label="Model",
117
+ info="Start with 7B model for faster responses"
118
+ )
119
+ with gr.Column(scale=1):
120
+ clear = gr.Button("Clear Chat", size="sm")
121
 
122
  chatbot = gr.Chatbot(
123
+ label="Chat",
124
+ height=550,
125
+ show_copy_button=True,
126
+ bubble_full_width=False
127
  )
128
 
129
  with gr.Row():
130
  msg = gr.Textbox(
131
+ label="",
132
+ placeholder="Type your message here...",
133
+ scale=9,
134
+ show_label=False,
135
+ container=False
136
  )
137
  submit = gr.Button("Send", scale=1, variant="primary")
138
 
139
+ with gr.Accordion("Model Information", open=False):
140
+ gr.Markdown("""
141
+ **Saul-7B-Instruct-v1**
142
+ - Size: 7 billion parameters
143
+ - Speed: Fast
144
+ - Quality: Good
145
+ - Recommended for quick responses
146
+
147
+ **SaulLM-54B-Instruct**
148
+ - Size: 54 billion parameters
149
+ - Speed: Medium
150
+ - Quality: Very good
151
+ - Requires more GPU memory
152
+
153
+ **SaulLM-141B-Instruct**
154
+ - Size: 141 billion parameters
155
+ - Speed: Slow
156
+ - Quality: Excellent
157
+ - Requires significant GPU resources
158
+
159
+ **Note**: Start with the 7B model for faster responses. Larger models provide better quality but are much slower.
160
+ """)
161
 
162
+ # Event handlers with streaming
163
+ msg.submit(
164
+ chat_stream,
165
+ [msg, chatbot, model_dropdown],
166
+ chatbot
167
+ ).then(
168
+ lambda: gr.update(value=""),
169
+ None,
170
+ msg
171
  )
172
+
173
+ submit.click(
174
+ chat_stream,
175
+ [msg, chatbot, model_dropdown],
176
+ chatbot
177
+ ).then(
178
+ lambda: gr.update(value=""),
179
+ None,
180
+ msg
181
  )
182
+
183
+ clear.click(lambda: [], None, chatbot)
184
 
185
  if __name__ == "__main__":
186
+ demo.queue(max_size=20) # Queue for streaming
187
  demo.launch()