CyberNative commited on
Commit
a203e8e
1 Parent(s): eeb43dd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +126 -47
app.py CHANGED
@@ -1,63 +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("CyberNative-AI/Colibri_8b_v0.1")
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
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
44
- """
45
- demo = gr.ChatInterface(
46
- respond,
47
- additional_inputs=[
48
- gr.Textbox(value="You are Colibri, an advanced cybersecurity AI assistant developed by CyberNative AI.", label="System message"),
49
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
50
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
51
- gr.Slider(
52
- minimum=0.1,
53
- maximum=1.0,
54
- value=0.95,
55
- step=0.05,
56
- label="Top-p (nucleus sampling)",
57
- ),
58
- ],
59
- )
60
 
 
 
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  if __name__ == "__main__":
63
  demo.launch()
 
1
  import gradio as gr
2
+ import os
3
+ import spaces
4
+ from transformers import GemmaTokenizer, AutoModelForCausalLM
5
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
6
+ from threading import Thread
7
 
8
+ # Set an environment variable
9
+ HF_TOKEN = os.environ.get("HF_TOKEN", None)
10
+
11
+
12
+ DESCRIPTION = '''
13
+ <div>
14
+ <h1 style="text-align: center;">Colibri v0.1 Dolphin Meta Llama3 8B</h1>
15
+ <p>This Space demonstrates the cybersecurity-tuned model <a href="https://huggingface.co/CyberNative-AI/Colibri_8b_v0.1"><b>Colibri_8b_v0.1</b></a>. Meta Llama3 is the new open LLM and comes in two sizes: 8b and 70b. Feel free to play with it, or duplicate to run privately!</p>
16
+ <p>🦕 Looking for an even more powerful model? Check out the <a href="https://huggingface.co/chat/"><b>Hugging Chat</b></a> integration for Meta Llama 3 70b</p>
17
+ </div>
18
+ '''
19
+
20
+ LICENSE = """
21
+ <p/>
22
+ ---
23
+ Built with Dolphin Meta Llama 3
24
  """
25
+
26
+ PLACEHOLDER = """
27
+ <div style="padding: 30px; text-align: center; display: flex; flex-direction: column; align-items: center;">
28
+ <img src="https://ysharma-dummy-chat-app.hf.space/file=/tmp/gradio/8e75e61cc9bab22b7ce3dec85ab0e6db1da5d107/Meta_lockup_positive%20primary_RGB.jpg" style="width: 80%; max-width: 550px; height: auto; opacity: 0.55; ">
29
+ <h1 style="font-size: 28px; margin-bottom: 2px; opacity: 0.55;">Colibri_v0.1 Dolphin Meta llama3</h1>
30
+ <p style="font-size: 18px; margin-bottom: 2px; opacity: 0.65;">Ask me anything...</p>
31
+ </div>
32
  """
 
33
 
34
 
35
+ css = """
36
+ h1 {
37
+ text-align: center;
38
+ display: block;
39
+ }
40
+ #duplicate-button {
41
+ margin: auto;
42
+ color: white;
43
+ background: #1565c0;
44
+ border-radius: 100vh;
45
+ }
46
+ """
47
 
48
+ # Load the tokenizer and model
49
+ tokenizer = AutoTokenizer.from_pretrained("CyberNative-AI/Colibri_8b_v0.1")
50
+ model = AutoModelForCausalLM.from_pretrained("CyberNative-AI/Colibri_8b_v0.1", device_map="auto") # to("cuda:0")
51
+ terminators = [
52
+ tokenizer.eos_token_id,
53
+ tokenizer.convert_tokens_to_ids("<|eot_id|>")
54
+ ]
55
 
56
+ @spaces.GPU(duration=120)
57
+ def chat_llama3_8b(message: str,
58
+ history: list,
59
+ temperature: float,
60
+ max_new_tokens: int
61
+ ) -> str:
62
+ """
63
+ Generate a streaming response using the llama3-8b model.
64
+ Args:
65
+ message (str): The input message.
66
+ history (list): The conversation history used by ChatInterface.
67
+ temperature (float): The temperature for generating the response.
68
+ max_new_tokens (int): The maximum number of new tokens to generate.
69
+ Returns:
70
+ str: The generated response.
71
+ """
72
+ conversation = []
73
+ for user, assistant in history:
74
+ conversation.extend([{"role": "user", "content": user}, {"role": "assistant", "content": assistant}])
75
+ conversation.append({"role": "user", "content": message})
76
 
77
+ input_ids = tokenizer.apply_chat_template(conversation, return_tensors="pt").to(model.device)
78
+
79
+ streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
80
 
81
+ generate_kwargs = dict(
82
+ input_ids= input_ids,
83
+ streamer=streamer,
84
+ max_new_tokens=max_new_tokens,
85
+ do_sample=True,
86
  temperature=temperature,
87
+ eos_token_id=terminators,
88
+ )
89
+ # This will enforce greedy generation (do_sample=False) when the temperature is passed 0, avoiding the crash.
90
+ if temperature == 0:
91
+ generate_kwargs['do_sample'] = False
92
+
93
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
94
+ t.start()
95
 
96
+ outputs = []
97
+ for text in streamer:
98
+ outputs.append(text)
99
+ #print(outputs)
100
+ yield "".join(outputs)
101
+
 
 
 
 
 
 
 
 
 
 
 
 
102
 
103
+ # Gradio block
104
+ chatbot=gr.Chatbot(height=450, placeholder=PLACEHOLDER, label='Gradio ChatInterface')
105
 
106
+ with gr.Blocks(fill_height=True, css=css) as demo:
107
+
108
+ gr.Markdown(DESCRIPTION)
109
+ gr.DuplicateButton(value="Duplicate Space for private use", elem_id="duplicate-button")
110
+ gr.ChatInterface(
111
+ fn=chat_llama3_8b,
112
+ chatbot=chatbot,
113
+ fill_height=True,
114
+ additional_inputs_accordion=gr.Accordion(label="⚙️ Parameters", open=False, render=False),
115
+ additional_inputs=[
116
+ gr.Slider(minimum=0,
117
+ maximum=1,
118
+ step=0.1,
119
+ value=0.95,
120
+ label="Temperature",
121
+ render=False),
122
+ gr.Slider(minimum=128,
123
+ maximum=4096,
124
+ step=1,
125
+ value=512,
126
+ label="Max new tokens",
127
+ render=False ),
128
+ ],
129
+ examples=[
130
+ ['What are the two main methods used in the research to collect DKIM information?'],
131
+ ['What is the primary purpose of OS fingerprinting using tools like Nmap, and why might it not always be 100% accurate?'],
132
+ ['What is 9,000 * 9,000?'],
133
+ ['What technique can be used to enumerate SMB shares within a Windows environment from a Windows client?'],
134
+ ['What is the primary benefit of interleaving in cybersecurity education and training?']
135
+ ],
136
+ cache_examples=False,
137
+ )
138
+
139
+ gr.Markdown(LICENSE)
140
+
141
  if __name__ == "__main__":
142
  demo.launch()