SandLogicTechnologies commited on
Commit
fa553a3
1 Parent(s): ef4aed0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +120 -42
app.py CHANGED
@@ -1,64 +1,142 @@
 
 
 
 
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 os
2
+ from threading import Thread
3
+ from typing import Iterator
4
+
5
  import gradio as gr
6
+ import spaces
7
+ import torch
8
+ import json
9
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
10
 
11
+
12
+ DESCRIPTION = """\
13
+ Shakti is a 250 million parameter language model specifically optimized for resource-constrained environments such as edge devices, including smartphones, wearables, and IoT systems. With support for vernacular languages and domain-specific tasks, Shakti excels in industries such as healthcare, finance, and customer service
14
+ For more details, please check [here](https://arxiv.org/pdf/2410.11331v1).
15
  """
 
 
 
16
 
17
+ MAX_MAX_NEW_TOKENS = 2048
18
+ DEFAULT_MAX_NEW_TOKENS = 1024
19
+ MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "2048"))
20
 
21
+ device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
 
 
 
 
 
 
 
 
22
 
23
+ model_id = "SandLogicTechnologies/Shakti-250M"
24
+ tokenizer = AutoTokenizer.from_pretrained(model_id, token=os.getenv("SHAKTI"))
25
+ model = AutoModelForCausalLM.from_pretrained(
26
+ model_id,
27
+ device_map="auto",
28
+ torch_dtype=torch.bfloat16,
29
+ token=os.getenv("SHAKTI")
30
 
31
+ )
32
+ model.eval()
33
 
 
34
 
35
+ @spaces.GPU(duration=90)
36
+ def generate(
37
+ message: str,
38
+ chat_history: list[tuple[str, str]],
39
+ max_new_tokens: int = 1024,
40
+ temperature: float = 0.6,
41
+ top_p: float = 0.9,
42
+ top_k: int = 50,
43
+ repetition_penalty: float = 1.2,
44
+ ) -> Iterator[str]:
45
+ conversation = []
46
+ for user, assistant in chat_history:
47
+ conversation.extend(
48
+ [
49
+ {"role": "user", "content": user},
50
+ {"role": "assistant", "content": assistant},
51
+ ]
52
+ )
53
+ conversation.append({"role": "user", "content": message})
54
+
55
+ input_ids = tokenizer.apply_chat_template(conversation, add_generation_prompt=True, return_tensors="pt")
56
+ if input_ids.shape[1] > MAX_INPUT_TOKEN_LENGTH:
57
+ input_ids = input_ids[:, -MAX_INPUT_TOKEN_LENGTH:]
58
+ gr.Warning(f"Trimmed input from conversation as it was longer than {MAX_INPUT_TOKEN_LENGTH} tokens.")
59
+ input_ids = input_ids.to(model.device)
60
+
61
+ streamer = TextIteratorStreamer(tokenizer, timeout=20.0, skip_prompt=True, skip_special_tokens=True)
62
+ generate_kwargs = dict(
63
+ {"input_ids": input_ids},
64
+ streamer=streamer,
65
+ max_new_tokens=max_new_tokens,
66
+ do_sample=True,
67
  top_p=top_p,
68
+ top_k=top_k,
69
+ temperature=temperature,
70
+ num_beams=1,
71
+ repetition_penalty=repetition_penalty,
72
+ )
73
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
74
+ t.start()
75
 
76
+ outputs = []
77
+ for text in streamer:
78
+ outputs.append(text)
79
+ yield "".join(outputs)
80
 
81
 
82
+ chat_interface = gr.ChatInterface(
83
+ fn=generate,
 
 
 
84
  additional_inputs=[
 
 
 
85
  gr.Slider(
86
+ label="Max new tokens",
87
+ minimum=1,
88
+ maximum=MAX_MAX_NEW_TOKENS,
89
+ step=1,
90
+ value=DEFAULT_MAX_NEW_TOKENS,
91
+ ),
92
+ gr.Slider(
93
+ label="Temperature",
94
  minimum=0.1,
95
+ maximum=4.0,
96
+ step=0.1,
97
+ value=0.6,
 
98
  ),
99
+ # gr.Slider(
100
+ # label="Top-p (nucleus sampling)",
101
+ # minimum=0.05,
102
+ # maximum=1.0,
103
+ # step=0.05,
104
+ # value=0.9,
105
+ # ),
106
+ # gr.Slider(
107
+ # label="Top-k",
108
+ # minimum=1,
109
+ # maximum=1000,
110
+ # step=1,
111
+ # value=50,
112
+ # ),
113
+ # gr.Slider(
114
+ # label="Repetition penalty",
115
+ # minimum=1.0,
116
+ # maximum=2.0,
117
+ # step=0.05,
118
+ # value=1.2,
119
+ # ),
120
+ ],
121
+ stop_btn=None,
122
+ examples=[
123
+ ["Can you explain the pathophysiology of hypertension and its impact on the cardiovascular system?"],
124
+ ["What are the potential side effects of beta-blockers in the treatment of arrhythmias?"],
125
+ ["What foods are good for boosting the immune system?"],
126
+ ["What is the difference between a stock and a bond?"],
127
+ ["How can I start saving for retirement?"],
128
+ ["What are some low-risk investment options?"],
129
+ ["What is a power of attorney and when is it used?"],
130
+ ["What are the key differences between a will and a trust?"],
131
+ ["How do I legally protect my business name?"]
132
  ],
133
+ cache_examples=False,
134
  )
135
 
136
+ with gr.Blocks(css="style.css", fill_height=True) as demo:
137
+ gr.Markdown(DESCRIPTION)
138
+ gr.DuplicateButton(value="Duplicate Space for private use", elem_id="duplicate-button")
139
+ chat_interface.render()
140
 
141
  if __name__ == "__main__":
142
+ demo.queue(max_size=20).launch()