Akjava commited on
Commit
0fb257c
·
verified ·
1 Parent(s): 5b94726

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +86 -128
app.py CHANGED
@@ -1,144 +1,102 @@
1
- #duplicated from https://huggingface.co/spaces/chheplo/DeepSeek-R1-Distill-Llama-8B
2
- import gradio as gr
3
- import os
4
  import spaces
5
- from transformers import GemmaTokenizer, AutoModelForCausalLM
6
- from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
 
 
7
  from threading import Thread
8
 
9
- # Set an environment variable
10
- HF_TOKEN = os.environ.get("HF_TOKEN", None)
11
-
12
 
13
- DESCRIPTION = '''
14
- <div>
15
- <h1 style="text-align: center;">deepseek-ai/DeepSeek-R1-Distill-Llama-8B</h1>
16
- </div>
17
- '''
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
- LICENSE = """
20
- <p/>
 
21
 
22
- ---
23
- """
24
 
25
- PLACEHOLDER = """
26
- <div style="padding: 30px; text-align: center; display: flex; flex-direction: column; align-items: center;">
27
- <h1 style="font-size: 28px; margin-bottom: 2px; opacity: 0.55;">DeepSeek-R1-Distill-Llama-8B</h1>
28
- <p style="font-size: 18px; margin-bottom: 2px; opacity: 0.65;">Ask me anything...</p>
29
- </div>
30
- """
31
 
 
32
 
33
- css = """
34
- h1 {
35
- text-align: center;
36
- display: block;
37
- }
38
 
39
- #duplicate-button {
40
- margin: auto;
41
- color: white;
42
- background: #1565c0;
43
- border-radius: 100vh;
44
- }
45
- """
46
- model_id = "AXCXEPT/phi-4-deepseek-R1K-RL-EZO"
47
- #model_id = "AXCXEPT/phi-4-open-R1-Distill-EZOv1"
48
- model_id = "mradermacher/phi-4-deepseek-R1K-RL-EZO-GGUF"
49
- filename = "phi-4-deepseek-R1K-RL-EZO.Q8_0.gguf"
50
- # Load the tokenizer and model
51
- tokenizer = AutoTokenizer.from_pretrained(model_id,gguf_file=filename)
52
- model = AutoModelForCausalLM.from_pretrained(model_id,gguf_file=filename) # to("cuda:0")
53
- terminators = [
54
- tokenizer.eos_token_id,
55
- tokenizer.convert_tokens_to_ids("<|eot_id|>")
56
- ]
57
-
58
- @spaces.GPU(duration=120)
59
- def chat_llama3_8b(message: str,
60
- history: list,
61
- temperature: float,
62
- max_new_tokens: int
63
- ) -> str:
64
- """
65
- Generate a streaming response using the llama3-8b model.
66
- Args:
67
- message (str): The input message.
68
- history (list): The conversation history used by ChatInterface.
69
- temperature (float): The temperature for generating the response.
70
- max_new_tokens (int): The maximum number of new tokens to generate.
71
- Returns:
72
- str: The generated response.
73
- """
74
- conversation = []
75
- for user, assistant in history:
76
- conversation.extend([{"role": "user", "content": user}, {"role": "assistant", "content": assistant}])
77
- conversation.append({"role": "user", "content": message})
78
-
79
- input_ids = tokenizer.apply_chat_template(conversation, return_tensors="pt").to(model.device)
80
-
81
- streamer = TextIteratorStreamer(tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
82
-
83
- generate_kwargs = dict(
84
- input_ids= input_ids,
85
- streamer=streamer,
86
- max_new_tokens=max_new_tokens,
87
- do_sample=True,
88
- temperature=temperature,
89
- eos_token_id=terminators,
90
- )
91
- # This will enforce greedy generation (do_sample=False) when the temperature is passed 0, avoiding the crash.
92
- if temperature == 0:
93
- generate_kwargs['do_sample'] = False
94
-
95
- t = Thread(target=model.generate, kwargs=generate_kwargs)
96
- t.start()
97
-
98
- outputs = []
99
- for text in streamer:
100
- outputs.append(text)
101
- #print(outputs)
102
- yield "".join(outputs)
103
-
104
 
105
- # Gradio block
106
- chatbot=gr.Chatbot(height=450, placeholder=PLACEHOLDER, label='Gradio ChatInterface')
107
 
108
- with gr.Blocks(fill_height=True, css=css) as demo:
 
 
 
 
109
 
110
- gr.Markdown(DESCRIPTION)
111
- gr.ChatInterface(
112
- fn=chat_llama3_8b,
113
- chatbot=chatbot,
114
- fill_height=True,
115
- additional_inputs_accordion=gr.Accordion(label="⚙️ Parameters", open=False, render=False),
116
- additional_inputs=[
117
- gr.Slider(minimum=0,
118
- maximum=1,
119
- step=0.1,
120
- value=0.5,
121
- label="Temperature",
122
- render=False),
123
- gr.Slider(minimum=128,
124
- maximum=4096,
125
- step=1,
126
- value=1024,
127
- label="Max new tokens",
128
- render=False ),
129
- ],
130
- examples=[
131
- ['How to setup a human base on Mars? Give short answer.'],
132
- ['Explain theory of relativity to me like I’m 8 years old.'],
133
- ['What is 9,000 * 9,000?'],
134
- ['Write a pun-filled happy birthday message to my friend Alex.'],
135
- ['Justify why a penguin might make a good king of the jungle.']
136
- ],
137
- cache_examples=False,
138
- )
139
 
140
- gr.Markdown(LICENSE)
 
 
 
 
 
141
 
142
- if __name__ == "__main__":
143
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
 
 
 
 
 
 
 
 
 
1
  import spaces
2
+ import os
3
+ import torch
4
+ from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
5
+ from transformers import TextIteratorStreamer
6
  from threading import Thread
7
 
8
+ import gradio as gr
 
 
9
 
10
+ text_generator = None
11
+ is_hugging_face = True
12
+ model_id = "AXCXEPT/phi-4-deepseek-R1K-RL-EZO"
13
+ model_id = "AXCXEPT/phi-4-open-R1-Distill-EZOv1"
14
+
15
+ huggingface_token = os.getenv("HUGGINGFACE_TOKEN")
16
+ huggingface_token = None
17
+ device = "auto" # torch.device("cuda" if torch.cuda.is_available() else "cpu")
18
+ device = "cuda"
19
+ dtype = torch.bfloat16
20
+ dtype = torch.float16
21
+
22
+ if not huggingface_token:
23
+ pass
24
+ print("no HUGGINGFACE_TOKEN if you need set secret ")
25
+ #raise ValueError("HUGGINGFACE_TOKEN environment variable is not set")
26
+
27
 
28
+
29
+
30
+
31
 
 
 
32
 
 
 
 
 
 
 
33
 
34
+ tokenizer = AutoTokenizer.from_pretrained(model_id, token=huggingface_token)
35
 
36
+ print(model_id,device,dtype)
37
+ histories = []
38
+ #model = None
 
 
39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
 
 
41
 
42
+ if not is_hugging_face:
43
+ model = AutoModelForCausalLM.from_pretrained(
44
+ model_id, token=huggingface_token ,torch_dtype=dtype,device_map=device
45
+ )
46
+ text_generator = pipeline("text-generation", model=model, tokenizer=tokenizer,torch_dtype=dtype,device_map=device,stream=True ) #pipeline has not to(device)
47
 
48
+ if next(model.parameters()).is_cuda:
49
+ print("The model is on a GPU")
50
+ else:
51
+ print("The model is on a CPU")
52
+
53
+ #print(f"text_generator.device='{text_generator.device}")
54
+ if str(text_generator.device).strip() == 'cuda':
55
+ print("The pipeline is using a GPU")
56
+ else:
57
+ print("The pipeline is using a CPU")
58
+
59
+ print("initialized")
60
+
61
+
62
+ def generate_text(messages):
63
+ if is_hugging_face:#need everytime initialize for ZeroGPU
64
+ model = AutoModelForCausalLM.from_pretrained(
65
+ model_id, token=huggingface_token ,torch_dtype=dtype,device_map=device
66
+ )
67
+ model.to(device)
68
+ question = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
69
+ question = tokenizer(question, return_tensors="pt").to(device)
70
+
71
+ streamer = TextIteratorStreamer(tokenizer, skip_prompt=True)
72
+ generation_kwargs = dict(question, streamer=streamer, max_new_tokens=200)
73
+ thread = Thread(target=model.generate, kwargs=generation_kwargs)
 
 
 
74
 
75
+ generated_output = ""
76
+ thread.start()
77
+ for new_text in streamer:
78
+ generated_output += new_text
79
+ yield generated_output
80
+ generate_text.zerogpu = True
81
 
82
+
83
+
84
+ @spaces.GPU(duration=60)
85
+ def call_generate_text(message, history):
86
+ # history.append({"role": "user", "content": message})
87
+ #print(message)
88
+ #print(history)
89
+
90
+ messages = history+[{"role":"user","content":message}]
91
+ try:
92
+
93
+ for text in generate_text(messages):
94
+ yield text
95
+ except RuntimeError as e:
96
+ print(f"An unexpected error occurred: {e}")
97
+ yield ""
98
 
99
+ demo = gr.ChatInterface(call_generate_text,type="messages")
100
+
101
+ if __name__ == "__main__":
102
+ demo.launch()