SandLogicTechnologies commited on
Commit
5e5249d
1 Parent(s): 51b1e53

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +115 -40
app.py CHANGED
@@ -1,64 +1,139 @@
 
 
 
 
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
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
9
 
10
+ DESCRIPTION = """\
11
+ # SHAKTI - 2.5B
12
+ Shakti is a 2.5 billion 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
13
+ For more details, please check [here](https://arxiv.org/pdf/2410.11331v1).
14
  """
 
 
 
15
 
16
+ MAX_MAX_NEW_TOKENS = 2048
17
+ DEFAULT_MAX_NEW_TOKENS = 1024
18
+ MAX_INPUT_TOKEN_LENGTH = 4096
19
+ # MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096"))
20
+
21
+ device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
22
 
23
+ model_id = "SandLogicTechnologies/Shakti-2.5B"
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
+ os.getenv("PROMPT"),
50
+ {"role": "user", "content": user},
51
+ {"role": "assistant", "content": assistant},
52
+ ]
53
+ )
54
+ conversation.append({"role": "user", "content": message})
55
 
56
+ input_ids = tokenizer.apply_chat_template(conversation, add_generation_prompt=True, return_tensors="pt")
57
+ if input_ids.shape[1] > MAX_INPUT_TOKEN_LENGTH:
58
+ input_ids = input_ids[:, -MAX_INPUT_TOKEN_LENGTH:]
59
+ gr.Warning(f"Trimmed input from conversation as it was longer than {MAX_INPUT_TOKEN_LENGTH} tokens.")
60
+ input_ids = input_ids.to(model.device)
61
+
62
+ streamer = TextIteratorStreamer(tokenizer, timeout=20.0, skip_prompt=True, skip_special_tokens=True)
63
+ generate_kwargs = dict(
64
+ {"input_ids": input_ids},
65
+ streamer=streamer,
66
+ max_new_tokens=max_new_tokens,
67
+ do_sample=True,
68
  top_p=top_p,
69
+ top_k=top_k,
70
+ temperature=temperature,
71
+ num_beams=1,
72
+ repetition_penalty=repetition_penalty,
73
+ )
74
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
75
+ t.start()
76
 
77
+ outputs = []
78
+ for text in streamer:
79
+ outputs.append(text)
80
+ yield "".join(outputs)
81
 
82
 
83
+ chat_interface = gr.ChatInterface(
84
+ fn=generate,
 
 
 
85
  additional_inputs=[
 
 
 
86
  gr.Slider(
87
+ label="Max new tokens",
88
+ minimum=1,
89
+ maximum=MAX_MAX_NEW_TOKENS,
90
+ step=1,
91
+ value=DEFAULT_MAX_NEW_TOKENS,
92
+ ),
93
+ gr.Slider(
94
+ label="Temperature",
95
  minimum=0.1,
96
+ maximum=4.0,
97
+ step=0.1,
98
+ value=0.6,
99
+ ),
100
+ gr.Slider(
101
+ label="Top-p (nucleus sampling)",
102
+ minimum=0.05,
103
  maximum=1.0,
 
104
  step=0.05,
105
+ value=0.9,
106
+ ),
107
+ gr.Slider(
108
+ label="Top-k",
109
+ minimum=1,
110
+ maximum=1000,
111
+ step=1,
112
+ value=50,
113
  ),
114
+ gr.Slider(
115
+ label="Repetition penalty",
116
+ minimum=1.0,
117
+ maximum=2.0,
118
+ step=0.05,
119
+ value=1.2,
120
+ ),
121
+ ],
122
+ stop_btn=None,
123
+ examples=[
124
+ ["Hello there! How are you doing?"],
125
+ ["Can you explain briefly to me what is the Python programming language?"],
126
+ ["Explain the plot of Cinderella in a sentence."],
127
+ ["How many hours does it take a man to eat a Helicopter?"],
128
+ ["Write a 100-word article on 'Benefits of AI research'"],
129
  ],
130
+ cache_examples=False,
131
  )
132
 
133
+ with gr.Blocks(css="style.css", fill_height=True) as demo:
134
+ gr.Markdown(DESCRIPTION)
135
+ gr.DuplicateButton(value="Duplicate Space for private use", elem_id="duplicate-button")
136
+ chat_interface.render()
137
 
138
  if __name__ == "__main__":
139
+ demo.queue(max_size=20).launch()