bau0221 commited on
Commit
2aa928f
Β·
verified Β·
1 Parent(s): 4990e58

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -50
app.py CHANGED
@@ -1,59 +1,82 @@
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("stabilityai/stablelm-2-1_6b")
8
-
9
-
10
-
11
- def respond(
12
- message,
13
- history: list[tuple[str, str]],
14
- system_message,
15
- max_tokens,
16
- temperature,
17
- top_p,
18
- ):
19
- MAX_HISTORY_LENGTH = 5 # δΏη•™ζœ€θΏ‘ 5 撝歷史
20
 
21
- # ι™εˆΆζ­·ε²ε°θ©±ηš„ι•·εΊ¦
22
- history = history[-MAX_HISTORY_LENGTH:]
23
 
24
- # ζ§‹ε»ΊζΆˆζ―εˆ—θ‘¨οΌŒεΎžη³»η΅±ζΆˆζ―ι–‹ε§‹
25
- messages = [{"role": "system", "content": system_message}]
26
 
27
- # 添加歷史對話
28
- for val in history:
29
- if val[0]:
30
- messages.append({"role": "user", "content": val[0]})
31
- if val[1]:
32
- messages.append({"role": "assistant", "content": val[1]})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
- # ζ·»εŠ ζœ€ζ–°ηš„η”¨ζˆΆθΌΈε…₯
35
- messages.append({"role": "user", "content": message})
36
 
37
- # εˆε§‹εŒ–η©Ίε›žζ‡‰
38
- response = ""
39
 
40
- # ε‘Όε«ζ¨‘εž‹δΈ¦η”Ÿζˆε›žζ‡‰οΌŒδ½Ώη”¨ stream 樑式逐ζ­₯ζ›΄ζ–°
41
- for message in client.chat_completion(
42
- messages,
43
- max_tokens=max_tokens,
44
- stream=True,
45
- temperature=temperature,
46
- top_p=top_p,
47
- ):
48
- token = message.choices[0].delta.content
49
- response += token
50
- yield response
51
 
 
52
 
53
 
54
- """
55
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
56
- """
57
  demo = gr.ChatInterface(
58
  respond,
59
  additional_inputs=[
@@ -128,7 +151,4 @@ demo = gr.ChatInterface(
128
  ),
129
  ],
130
  )
131
-
132
-
133
- if __name__ == "__main__":
134
- demo.launch()
 
1
  import gradio as gr
2
+ import torch
3
+ from transformers import (
4
+ AutoModelForCausalLM,
5
+ AutoTokenizer,
6
+ TextIteratorStreamer,
7
+ )
8
+ import os
9
+ from threading import Thread
10
+ import spaces
11
+ import time
12
+ import subprocess
13
+
14
+ subprocess.run(
15
+ "pip install flash-attn --no-build-isolation",
16
+ env={"FLASH_ATTENTION_SKIP_CUDA_BUILD": "TRUE"},
17
+ shell=True,
18
+ )
 
19
 
20
+ token = os.environ["HF_TOKEN"]
 
21
 
 
 
22
 
23
+ model = AutoModelForCausalLM.from_pretrained(
24
+ "microsoft/Phi-3-mini-128k-instruct",
25
+ token=token,
26
+ trust_remote_code=True,
27
+ )
28
+ tok = AutoTokenizer.from_pretrained("microsoft/Phi-3-mini-128k-instruct", token=token)
29
+ terminators = [
30
+ tok.eos_token_id,
31
+ ]
32
+
33
+ if torch.cuda.is_available():
34
+ device = torch.device("cuda")
35
+ print(f"Using GPU: {torch.cuda.get_device_name(device)}")
36
+ else:
37
+ device = torch.device("cpu")
38
+ print("Using CPU")
39
+
40
+ model = model.to(device)
41
+ # Dispatch Errors
42
+
43
+
44
+ @spaces.GPU(duration=60)
45
+ def chat(message, history, temperature, do_sample, max_tokens):
46
+ chat = []
47
+ for item in history:
48
+ chat.append({"role": "user", "content": item[0]})
49
+ if item[1] is not None:
50
+ chat.append({"role": "assistant", "content": item[1]})
51
+ chat.append({"role": "user", "content": message})
52
+ messages = tok.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)
53
+ model_inputs = tok([messages], return_tensors="pt").to(device)
54
+ streamer = TextIteratorStreamer(
55
+ tok, timeout=20.0, skip_prompt=True, skip_special_tokens=True
56
+ )
57
+ generate_kwargs = dict(
58
+ model_inputs,
59
+ streamer=streamer,
60
+ max_new_tokens=max_tokens,
61
+ do_sample=True,
62
+ temperature=temperature,
63
+ eos_token_id=terminators,
64
+ )
65
 
66
+ if temperature == 0:
67
+ generate_kwargs["do_sample"] = False
68
 
69
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
70
+ t.start()
71
 
72
+ partial_text = ""
73
+ for new_text in streamer:
74
+ partial_text += new_text
75
+ yield partial_text
 
 
 
 
 
 
 
76
 
77
+ yield partial_text
78
 
79
 
 
 
 
80
  demo = gr.ChatInterface(
81
  respond,
82
  additional_inputs=[
 
151
  ),
152
  ],
153
  )
154
+ demo.launch()