bobpopboom commited on
Commit
1757e26
·
verified ·
1 Parent(s): 9f3d29f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +79 -47
app.py CHANGED
@@ -1,64 +1,96 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
 
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
 
26
- messages.append({"role": "user", "content": message})
 
 
27
 
28
- response = ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
 
 
 
 
 
 
 
 
 
 
 
38
 
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
  demo = gr.ChatInterface(
47
  respond,
48
  additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
  ),
 
59
  ],
60
  )
61
 
62
-
63
  if __name__ == "__main__":
64
- demo.launch()
 
1
  import gradio as gr
2
+ from transformers import AutoModelForCausalLM, AutoTokenizer
3
+ import torch
4
 
5
+ # Determine device
6
+ device = "cuda" if torch.cuda.is_available() else "cpu"
 
 
7
 
8
+ model_id = "GRMenon/mental-health-mistral-7b-instructv0.2-finetuned-V2"
9
 
10
+ try:
11
+ # Load model with appropriate settings
12
+ model = AutoModelForCausalLM.from_pretrained(
13
+ model_id,
14
+ device_map="auto",
15
+ torch_dtype=torch.float16,
16
+ low_cpu_mem_usage=True,
17
+ max_memory={0: "15GiB"} if torch.cuda.is_available() else None,
18
+ offload_folder="offload",
19
+ ).eval()
20
 
21
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
22
+ tokenizer.pad_token = tokenizer.eos_token
23
+ tokenizer.model_max_length = 4096 # Set to model's actual context length
 
 
24
 
25
+ except Exception as e:
26
+ print(f"Error loading model: {e}")
27
+ exit()
28
 
29
+ def generate_text_streaming(prompt, max_new_tokens=128):
30
+ inputs = tokenizer(
31
+ prompt,
32
+ return_tensors="pt",
33
+ truncation=True,
34
+ max_length=4096 # Match model's context length
35
+ ).to(model.device)
36
+
37
+ generated_tokens = []
38
+ with torch.no_grad():
39
+ for _ in range(max_new_tokens):
40
+ outputs = model.generate(
41
+ **inputs,
42
+ max_new_tokens=1,
43
+ do_sample=False,
44
+ eos_token_id=tokenizer.eos_token_id,
45
+ return_dict_in_generate=True
46
+ )
47
+
48
+ new_token = outputs.sequences[0, -1]
49
+ generated_tokens.append(new_token)
50
+
51
+ # Update inputs for next iteration
52
+ inputs = {
53
+ "input_ids": torch.cat([inputs["input_ids"], new_token.unsqueeze(0).unsqueeze(0)], dim=-1),
54
+ "attention_mask": torch.cat([inputs["attention_mask"], torch.ones(1, 1, device=model.device)], dim=-1)
55
+ }
56
+
57
+ # Decode the accumulated tokens
58
+ current_text = tokenizer.decode(generated_tokens, skip_special_tokens=True)
59
+ yield current_text # Yield the full text so far
60
+
61
+ if new_token == tokenizer.eos_token_id:
62
+ break
63
 
64
+ def respond(message, history, system_message, max_tokens):
65
+ # Build prompt with full history
66
+ prompt = f"{system_message}\n"
67
+ for user_msg, bot_msg in history:
68
+ prompt += f"User: {user_msg}\nAssistant: {bot_msg}\n"
69
+ prompt += f"User: {message}\nAssistant:"
70
+
71
+ # Keep track of the full response
72
+ full_response = ""
73
+
74
+ try:
75
+ for token_chunk in generate_text_streaming(prompt, max_tokens):
76
+ # Update the full response and yield incremental changes
77
+ full_response = token_chunk
78
+ yield full_response
79
+
80
+ except Exception as e:
81
+ print(f"Error during generation: {e}")
82
+ yield "An error occurred."
83
 
 
 
 
 
 
 
 
84
  demo = gr.ChatInterface(
85
  respond,
86
  additional_inputs=[
87
+ gr.Textbox(
88
+ value="You are a friendly and helpful mental health chatbot.",
89
+ label="System message",
 
 
 
 
 
 
90
  ),
91
+ gr.Slider(minimum=1, maximum=512, value=128, step=1, label="Max new tokens"),
92
  ],
93
  )
94
 
 
95
  if __name__ == "__main__":
96
+ demo.launch()