Wedyan2023 commited on
Commit
41dfeef
·
verified ·
1 Parent(s): d87e84c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +129 -11
app.py CHANGED
@@ -1,18 +1,136 @@
 
 
 
 
1
  import gradio as gr
2
- from transformers import pipeline
 
 
 
 
 
 
 
 
 
3
 
4
- pipeline = pipeline(task="image-classification", model="meta-llama/Llama-3.2-11B-Vision-Instruct")
 
 
5
 
6
- def predict(input_img):
7
- predictions = pipeline(input_img)
8
- return input_img, {p["label"]: p["score"] for p in predictions}
9
 
10
- gradio_app = gr.Interface(
11
- predict,
12
- inputs=gr.Image(label="Select hot dog candidate", sources=['upload', 'webcam'], type="pil"),
13
- outputs=[gr.Image(label="Processed Image"), gr.Label(label="Result", num_top_classes=2)],
14
- title="Hot Dog? Or Not?",
 
15
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
  if __name__ == "__main__":
18
- gradio_app.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
+ # Llama 3.2 3B Instruct
12
+ Llama 3.2 3B is Meta's latest iteration of open LLMs.
13
+ This is a demo of [`meta-llama/Llama-3.2-3B-Instruct`](https://huggingface.co/meta-llama/Llama-3.2-3B-Instruct), fine-tuned for instruction following.
14
+ For more details, please check [our post](https://huggingface.co/blog/llama32).
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", "4096"))
20
 
21
+ device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
 
 
22
 
23
+ model_id = "nltpt/Llama-3.2-3B-Instruct"
24
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
25
+ model = AutoModelForCausalLM.from_pretrained(
26
+ model_id,
27
+ device_map="auto",
28
+ torch_dtype=torch.bfloat16,
29
  )
30
+ model.eval()
31
+
32
+
33
+ @spaces.GPU(duration=90)
34
+ def generate(
35
+ message: str,
36
+ chat_history: list[tuple[str, str]],
37
+ max_new_tokens: int = 1024,
38
+ temperature: float = 0.6,
39
+ top_p: float = 0.9,
40
+ top_k: int = 50,
41
+ repetition_penalty: float = 1.2,
42
+ ) -> Iterator[str]:
43
+ conversation = []
44
+ for user, assistant in chat_history:
45
+ conversation.extend(
46
+ [
47
+ {"role": "user", "content": user},
48
+ {"role": "assistant", "content": assistant},
49
+ ]
50
+ )
51
+ conversation.append({"role": "user", "content": message})
52
+
53
+ input_ids = tokenizer.apply_chat_template(conversation, add_generation_prompt=True, return_tensors="pt")
54
+ if input_ids.shape[1] > MAX_INPUT_TOKEN_LENGTH:
55
+ input_ids = input_ids[:, -MAX_INPUT_TOKEN_LENGTH:]
56
+ gr.Warning(f"Trimmed input from conversation as it was longer than {MAX_INPUT_TOKEN_LENGTH} tokens.")
57
+ input_ids = input_ids.to(model.device)
58
+
59
+ streamer = TextIteratorStreamer(tokenizer, timeout=20.0, skip_prompt=True, skip_special_tokens=True)
60
+ generate_kwargs = dict(
61
+ {"input_ids": input_ids},
62
+ streamer=streamer,
63
+ max_new_tokens=max_new_tokens,
64
+ do_sample=True,
65
+ top_p=top_p,
66
+ top_k=top_k,
67
+ temperature=temperature,
68
+ num_beams=1,
69
+ repetition_penalty=repetition_penalty,
70
+ )
71
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
72
+ t.start()
73
+
74
+ outputs = []
75
+ for text in streamer:
76
+ outputs.append(text)
77
+ yield "".join(outputs)
78
+
79
+
80
+ chat_interface = gr.ChatInterface(
81
+ fn=generate,
82
+ additional_inputs=[
83
+ gr.Slider(
84
+ label="Max new tokens",
85
+ minimum=1,
86
+ maximum=MAX_MAX_NEW_TOKENS,
87
+ step=1,
88
+ value=DEFAULT_MAX_NEW_TOKENS,
89
+ ),
90
+ gr.Slider(
91
+ label="Temperature",
92
+ minimum=0.1,
93
+ maximum=4.0,
94
+ step=0.1,
95
+ value=0.6,
96
+ ),
97
+ gr.Slider(
98
+ label="Top-p (nucleus sampling)",
99
+ minimum=0.05,
100
+ maximum=1.0,
101
+ step=0.05,
102
+ value=0.9,
103
+ ),
104
+ gr.Slider(
105
+ label="Top-k",
106
+ minimum=1,
107
+ maximum=1000,
108
+ step=1,
109
+ value=50,
110
+ ),
111
+ gr.Slider(
112
+ label="Repetition penalty",
113
+ minimum=1.0,
114
+ maximum=2.0,
115
+ step=0.05,
116
+ value=1.2,
117
+ ),
118
+ ],
119
+ stop_btn=None,
120
+ examples=[
121
+ ["Hello there! How are you doing?"],
122
+ ["Can you explain briefly to me what is the Python programming language?"],
123
+ ["Explain the plot of Cinderella in a sentence."],
124
+ ["How many hours does it take a man to eat a Helicopter?"],
125
+ ["Write a 100-word article on 'Benefits of Open-Source in AI research'"],
126
+ ],
127
+ cache_examples=False,
128
+ )
129
+
130
+ with gr.Blocks(css="style.css", fill_height=True) as demo:
131
+ gr.Markdown(DESCRIPTION)
132
+ gr.DuplicateButton(value="Duplicate Space for private use", elem_id="duplicate-button")
133
+ chat_interface.render()
134
 
135
  if __name__ == "__main__":
136
+ demo.queue(max_size=20).launch()