Akjava commited on
Commit
03a1e68
Β·
verified Β·
1 Parent(s): 1f956b3

Update app.py

Browse files

test 1,but return tensor

Files changed (1) hide show
  1. app.py +99 -70
app.py CHANGED
@@ -1,74 +1,103 @@
1
- import gradio as gr
2
- import os
3
  import spaces
4
- from huggingface_hub import InferenceClient
5
-
6
- """
7
- 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
8
- """
9
- token = os.getenv("HUGGINGFACE_TOKEN")
10
- if token =="":
11
- raise ValueError("HUGGINGFACE_TOKEN environment variable is not set")
12
- print(token)
13
-
14
- client = InferenceClient("google/gemma-2-2b-it",token = token)
15
-
16
- @spaces.GPU(duration=30)
17
- def respond(
18
- message,
19
- history: list[tuple[str, str]],
20
- system_message,
21
- max_tokens,
22
- temperature,
23
- top_p,
24
- ):
25
- #messages = [{"role": "system", "content": system_message}] #system not supported
26
- messages = []
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
- messages.append({"role": "user", "content": message})
35
- response = ""
36
-
37
- # Load model directly
38
-
39
- for message in client.chat_completion(
40
- messages,
41
- max_tokens=max_tokens,
42
- stream=True,
43
- temperature=temperature,
44
- top_p=top_p,
45
- ):
46
- token = message.choices[0].delta.content
47
-
48
- response += token
49
- yield response
50
-
51
- """
52
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
53
- """
54
- demo = gr.ChatInterface(
55
- respond,
56
- additional_inputs=[
57
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
58
- gr.Slider(minimum=1, maximum=512, value=32, step=1, label="Max new tokens"),
59
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
60
- gr.Slider(
61
- minimum=0.1,
62
- maximum=1.0,
63
- value=0.95,
64
- step=0.05,
65
- label="Top-p (nucleus sampling)",
66
- ),
67
- ],
68
- )
69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
- if __name__ == "__main__":
72
- demo.launch()
73
 
74
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import spaces
2
+ import os
3
+ import torch
4
+ from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
5
+ from transformers import TextStreamer
6
+ import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
+ text_generator = None
9
+ is_hugging_face = True
10
+ model_id = "google/gemma-2-9b-it"# too big
11
+ model_id = "google/gemma-2-2b-it"
12
+ huggingface_token = os.getenv("HUGGINGFACE_TOKEN")
13
+ device = "auto" # torch.device("cuda" if torch.cuda.is_available() else "cpu")
14
+ device = "cuda"
15
+ dtype = torch.bfloat16
16
+ dtype = torch.float16
17
+
18
+ if not huggingface_token:
19
+ pass
20
+ print("no HUGGINGFACE_TOKEN if you need set secret ")
21
+ #raise ValueError("HUGGINGFACE_TOKEN environment variable is not set")
22
+
23
+
24
+
25
+
26
+
27
+
28
+
29
+
30
+ tokenizer = AutoTokenizer.from_pretrained(model_id, token=huggingface_token)
31
+
32
+ print(model_id,device,dtype)
33
+ histories = []
34
+ #model = None
35
 
 
 
36
 
37
+
38
+ if not is_hugging_face:
39
+ model = AutoModelForCausalLM.from_pretrained(
40
+ model_id, token=huggingface_token ,torch_dtype=dtype,device_map=device
41
+ )
42
+ text_generator = pipeline("text-generation", model=model, tokenizer=tokenizer,torch_dtype=dtype,device_map=device,stream=True ) #pipeline has not to(device)
43
+
44
+ if next(model.parameters()).is_cuda:
45
+ print("The model is on a GPU")
46
+ else:
47
+ print("The model is on a CPU")
48
+
49
+ #print(f"text_generator.device='{text_generator.device}")
50
+ if str(text_generator.device).strip() == 'cuda':
51
+ print("The pipeline is using a GPU")
52
+ else:
53
+ print("The pipeline is using a CPU")
54
+
55
+ print("initialized")
56
+
57
+ @spaces.GPU(duration=60)
58
+ def generate_text(messages):
59
+ if is_hugging_face:#need everytime initialize for ZeroGPU
60
+ model = AutoModelForCausalLM.from_pretrained(
61
+ model_id, token=huggingface_token ,torch_dtype=dtype,device_map=device
62
+ )
63
+ model.to(device)
64
+ question = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
65
+ question = tokenizer(question, return_tensors="pt").to(device)
66
+
67
+ streamer = TextStreamer(tokenizer, skip_prompt=True)
68
+
69
+ #text_generator = pipeline("text-generation", model=model, tokenizer=tokenizer,torch_dtype=dtype,device_map=device ,streamer=streamer) #pipeline has not to(device)
70
+ #result = text_generator(messages, max_new_tokens=256, do_sample=True, temperature=0.7)
71
+ result = model.generate(**question, streamer=streamer,
72
+ pad_token_id=tokenizer.eos_token_id,
73
+ max_length=2048,
74
+ temperature=0,
75
+ top_p=0.8,
76
+ repetition_penalty=1.25)
77
+
78
+ print(f"result={result}")
79
+ generated_output = ""
80
+ for token in result:
81
+ print(f"token={token}")
82
+ generated_output += token["text"]
83
+ yield generated_output
84
+
85
+
86
+ def call_generate_text(message, history):
87
+ # history.append({"role": "user", "content": message})
88
+ print(message)
89
+ print(history)
90
+
91
+ messages = history+[{"role":"user","content":message}]
92
+ try:
93
+
94
+ for text in generate_text(messages):
95
+ yield text
96
+ except RuntimeError as e:
97
+ print(f"An unexpected error occurred: {e}")
98
+ yield ""
99
+
100
+ demo = gr.ChatInterface(call_generate_text,type="messages")
101
+
102
+ if __name__ == "__main__":
103
+ demo.launch(share=True)