SandLogicTechnologies commited on
Commit
9fd6bb0
·
verified ·
1 Parent(s): 7df2477

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +95 -42
app.py CHANGED
@@ -1,64 +1,117 @@
 
 
 
 
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 500 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-500M"
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=180)
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 = [json.loads(os.getenv("PROMPT"))]
46
+ # conversation = []
47
+ for user, assistant in chat_history:
48
+ conversation.extend(
49
+ [
50
+ json.loads(os.getenv("PROMPT")),
51
+ {"role": "user", "content": user},
52
+ {"role": "assistant", "content": assistant},
53
+ ]
54
+ )
55
+ conversation.append({"role": "user", "content": message})
56
 
57
+ input_ids = tokenizer.apply_chat_template(conversation, add_generation_prompt=True, return_tensors="pt")
58
+ if input_ids.shape[1] > MAX_INPUT_TOKEN_LENGTH:
59
+ input_ids = input_ids[:, -MAX_INPUT_TOKEN_LENGTH:]
60
+ gr.Warning(f"Trimmed input from conversation as it was longer than {MAX_INPUT_TOKEN_LENGTH} tokens.")
61
+ input_ids = input_ids.to(model.device)
62
+
63
+ streamer = TextIteratorStreamer(tokenizer, timeout=50.0, skip_prompt=True, skip_special_tokens=True)
64
+ generate_kwargs = dict(
65
+ {"input_ids": input_ids},
66
+ streamer=streamer,
67
+ max_new_tokens=max_new_tokens,
68
+ do_sample=True,
69
  top_p=top_p,
70
+ top_k=top_k,
71
+ temperature=temperature,
72
+ num_beams=1,
73
+ repetition_penalty=repetition_penalty,
74
+ )
75
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
76
+ t.start()
77
 
78
+ outputs = []
79
+ for text in streamer:
80
+ outputs.append(text)
81
+ yield "".join(outputs)
82
 
83
 
84
+ chat_interface = gr.ChatInterface(
85
+ fn=generate,
 
 
 
86
  additional_inputs=[
 
 
 
87
  gr.Slider(
88
+ label="Max new tokens",
89
+ minimum=1,
90
+ maximum=MAX_MAX_NEW_TOKENS,
91
+ step=1,
92
+ value=DEFAULT_MAX_NEW_TOKENS,
93
+ ),
94
+ gr.Slider(
95
+ label="Temperature",
96
  minimum=0.1,
97
+ maximum=4.0,
98
+ step=0.1,
99
+ value=0.6,
 
100
  ),
101
  ],
102
+ stop_btn=None,
103
+ examples=[
104
+ ["Tell me a story"], ["write a short poem which is hard to sing"]
105
+ ],
106
+ cache_examples=False,
107
  )
108
 
109
+ with gr.Blocks(css="style.css", fill_height=True) as demo:
110
+ gr.Markdown(DESCRIPTION)
111
+ gr.DuplicateButton(value="Duplicate Space for private use", elem_id="duplicate-button")
112
+ chat_interface.render()
113
 
114
  if __name__ == "__main__":
115
+ demo.queue(max_size=20).launch()
116
+
117
+