Ravi21 commited on
Commit
debd5f8
β€’
1 Parent(s): 6a6c805

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -30
app.py CHANGED
@@ -1,16 +1,36 @@
1
  from typing import Iterator
2
 
3
  import gradio as gr
4
-
5
 
6
  from model import get_input_token_length, run
7
- MAX_MAX_NEW_TOKENS = 512
 
 
 
 
8
  DEFAULT_MAX_NEW_TOKENS = 1024
9
- MAX_INPUT_TOKEN_LENGTH = 512
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
  if not torch.cuda.is_available():
12
  DESCRIPTION += '\n<p>Running on CPU πŸ₯Ά This demo does not work on CPU.</p>'
13
-
 
14
  def clear_and_save_textbox(message: str) -> tuple[str, str]:
15
  return '', message
16
 
@@ -29,6 +49,7 @@ def delete_prev_fn(
29
  message = ''
30
  return history, message or ''
31
 
 
32
  def generate(
33
  message: str,
34
  history_with_input: list[tuple[str, str]],
@@ -51,28 +72,20 @@ def generate(
51
  for response in generator:
52
  yield history + [(message, response)]
53
 
54
- def preprocess(sample):
55
- first_sentences = [sample["prompt"]] * 5
56
- second_sentences = [sample[option] for option in "ABCDE"]
57
- tokenized_sentences = tokenizer(first_sentences, second_sentences, truncation=True, padding=True, return_tensors="pt")
58
- sample["input_ids"] = tokenized_sentences["input_ids"]
59
- sample["attention_mask"] = tokenized_sentences["attention_mask"]
60
- return sample
61
-
62
- # Define the prediction function
63
- def predict(data):
64
- inputs = torch.stack(data["input_ids"])
65
- masks = torch.stack(data["attention_mask"])
66
- with torch.no_grad():
67
- logits = model(inputs, attention_mask=masks).logits
68
- predictions_as_ids = torch.argsort(-logits, dim=1)
69
- answers = np.array(list("ABCDE"))[predictions_as_ids.tolist()]
70
- return ["".join(i) for i in answers[:, :3]]
71
  def check_input_token_length(message: str, chat_history: list[tuple[str, str]], system_prompt: str) -> None:
72
  input_token_length = get_input_token_length(message, chat_history, system_prompt)
73
  if input_token_length > MAX_INPUT_TOKEN_LENGTH:
74
  raise gr.Error(f'The accumulated input is too long ({input_token_length} > {MAX_INPUT_TOKEN_LENGTH}). Clear your chat history and try again.')
75
 
 
76
  with gr.Blocks(css='style.css') as demo:
77
  gr.Markdown(DESCRIPTION)
78
  gr.DuplicateButton(value='Duplicate Space for private use',
@@ -131,18 +144,20 @@ with gr.Blocks(css='style.css') as demo:
131
  value=50,
132
  )
133
 
134
- gr.Interface(
135
-
136
- fn=predict,
137
- inputs=gr.Interface.DataType.json,
138
- outputs=gr.outputs.Label(num_top_classes=3),
139
- live=True,
140
  examples=[
141
- {"prompt": "This is the prompt", "A": "Option A text", "B": "Option B text", "C": "Option C text", "D": "Option D text", "E": "Option E text"}
 
 
 
 
142
  ],
143
- title="LLM Science Exam Demo",
144
- description="Enter the prompt and options (A to E) below and get predictions.",
 
 
145
  )
 
146
  gr.Markdown(LICENSE)
147
 
148
  textbox.submit(
@@ -258,3 +273,4 @@ with gr.Blocks(css='style.css') as demo:
258
  )
259
 
260
  demo.queue(max_size=20).launch()
 
 
1
  from typing import Iterator
2
 
3
  import gradio as gr
4
+ import torch
5
 
6
  from model import get_input_token_length, run
7
+
8
+ DEFAULT_SYSTEM_PROMPT = """\
9
+ You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.\n\nIf a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.\
10
+ """
11
+ MAX_MAX_NEW_TOKENS = 2048
12
  DEFAULT_MAX_NEW_TOKENS = 1024
13
+ MAX_INPUT_TOKEN_LENGTH = 4000
14
+
15
+ DESCRIPTION = """
16
+ # Llama-2 13B Chat
17
+ This Space demonstrates model [Llama-2-13b-chat](https://huggingface.co/meta-llama/Llama-2-13b-chat) by Meta, a Llama 2 model with 13B parameters fine-tuned for chat instructions. Feel free to play with it, or duplicate to run generations without a queue! If you want to run your own service, you can also [deploy the model on Inference Endpoints](https://huggingface.co/inference-endpoints).
18
+ πŸ”Ž For more details about the Llama 2 family of models and how to use them with `transformers`, take a look [at our blog post](https://huggingface.co/blog/llama2).
19
+ πŸ”¨ Looking for an even more powerful model? Check out the large [**70B** model demo](https://huggingface.co/spaces/ysharma/Explore_llamav2_with_TGI).
20
+ πŸ‡ For a smaller model that you can run on many GPUs, check our [7B model demo](https://huggingface.co/spaces/huggingface-projects/llama-2-7b-chat).
21
+ """
22
+
23
+ LICENSE = """
24
+ <p/>
25
+ ---
26
+ As a derivate work of [Llama-2-13b-chat](https://huggingface.co/meta-llama/Llama-2-13b-chat) by Meta,
27
+ this demo is governed by the original [license](https://huggingface.co/spaces/huggingface-projects/llama-2-13b-chat/blob/main/LICENSE.txt) and [acceptable use policy](https://huggingface.co/spaces/huggingface-projects/llama-2-13b-chat/blob/main/USE_POLICY.md).
28
+ """
29
 
30
  if not torch.cuda.is_available():
31
  DESCRIPTION += '\n<p>Running on CPU πŸ₯Ά This demo does not work on CPU.</p>'
32
+
33
+
34
  def clear_and_save_textbox(message: str) -> tuple[str, str]:
35
  return '', message
36
 
 
49
  message = ''
50
  return history, message or ''
51
 
52
+
53
  def generate(
54
  message: str,
55
  history_with_input: list[tuple[str, str]],
 
72
  for response in generator:
73
  yield history + [(message, response)]
74
 
75
+
76
+ def process_example(message: str) -> tuple[str, list[tuple[str, str]]]:
77
+ generator = generate(message, [], DEFAULT_SYSTEM_PROMPT, 1024, 1, 0.95, 50)
78
+ for x in generator:
79
+ pass
80
+ return '', x
81
+
82
+
 
 
 
 
 
 
 
 
 
83
  def check_input_token_length(message: str, chat_history: list[tuple[str, str]], system_prompt: str) -> None:
84
  input_token_length = get_input_token_length(message, chat_history, system_prompt)
85
  if input_token_length > MAX_INPUT_TOKEN_LENGTH:
86
  raise gr.Error(f'The accumulated input is too long ({input_token_length} > {MAX_INPUT_TOKEN_LENGTH}). Clear your chat history and try again.')
87
 
88
+
89
  with gr.Blocks(css='style.css') as demo:
90
  gr.Markdown(DESCRIPTION)
91
  gr.DuplicateButton(value='Duplicate Space for private use',
 
144
  value=50,
145
  )
146
 
147
+ gr.Examples(
 
 
 
 
 
148
  examples=[
149
+ 'Hello there! How are you doing?',
150
+ 'Can you explain briefly to me what is the Python programming language?',
151
+ 'Explain the plot of Cinderella in a sentence.',
152
+ 'How many hours does it take a man to eat a Helicopter?',
153
+ "Write a 100-word article on 'Benefits of Open-Source in AI research'",
154
  ],
155
+ inputs=textbox,
156
+ outputs=[textbox, chatbot],
157
+ fn=process_example,
158
+ cache_examples=True,
159
  )
160
+
161
  gr.Markdown(LICENSE)
162
 
163
  textbox.submit(
 
273
  )
274
 
275
  demo.queue(max_size=20).launch()
276
+