wiklif commited on
Commit
b7844b5
·
1 Parent(s): 9d9f151

dodany InferenceClient

Browse files
Files changed (1) hide show
  1. app.py +24 -55
app.py CHANGED
@@ -1,69 +1,45 @@
1
- import os
2
  import spaces
 
3
  import gradio as gr
4
- import transformers
5
- import torch
6
- from huggingface_hub import login
7
- import logging
8
-
9
- logging.basicConfig(level=logging.INFO)
10
- logger = logging.getLogger(__name__)
11
-
12
- model_id = "meta-llama/Meta-Llama-3.1-8B"
13
-
14
- def create_pipeline():
15
- login(token=os.environ.get("MY_API_LLAMA_3_1"))
16
- logger.info("Login successful")
17
-
18
- config = transformers.AutoConfig.from_pretrained(model_id)
19
- model = transformers.AutoModelForCausalLM.from_pretrained(
20
- model_id,
21
- config=config,
22
- torch_dtype=torch.bfloat16,
23
- device_map="auto",
24
- use_cache=False
25
- )
26
- model.tie_weights()
27
- tokenizer = transformers.AutoTokenizer.from_pretrained(model_id)
28
 
29
- return transformers.pipeline(
30
- "text-generation",
31
- model=model,
32
- tokenizer=tokenizer,
33
- torch_dtype=torch.bfloat16,
34
- device_map="auto"
35
- )
36
 
37
  @spaces.GPU(duration=60)
38
  def generate_response(chat, kwargs):
39
- pipeline = create_pipeline()
40
- try:
41
- output = pipeline(chat, **kwargs)[0]['generated_text']
42
- if output.endswith("</s>"):
43
- output = output[:-4]
44
- return output
45
- except Exception as e:
46
- logger.error(f"Error generating response: {str(e)}")
47
- return f"Wystąpił błąd podczas generowania odpowiedzi: {str(e)}"
48
 
49
  def function(prompt, history=[]):
50
  chat = "<s>"
51
  for user_prompt, bot_response in history:
52
  chat += f"[INST] {user_prompt} [/INST] {bot_response}</s> <s>"
53
- chat += f"[INST] {prompt} [/INST]"
54
-
55
  kwargs = dict(
56
- max_new_tokens=4096,
57
- do_sample=True,
58
  temperature=0.5,
 
59
  top_p=0.95,
60
  repetition_penalty=1.0,
 
61
  seed=1337
62
  )
63
 
64
- return generate_response(chat, kwargs)
 
 
 
 
 
65
 
66
- # Interfejs Gradio
67
  interface = gr.ChatInterface(
68
  fn=function,
69
  chatbot=gr.Chatbot(
@@ -85,11 +61,4 @@ interface = gr.ChatInterface(
85
  clear_btn=None
86
  )
87
 
88
- # API endpoint
89
- def api_predict(prompt):
90
- return function(prompt)
91
-
92
- interface.launch(show_api=True, share=True)
93
-
94
- # Dodanie endpointu API
95
- gr.Interface(fn=api_predict, inputs="text", outputs="text").launch(share=True)
 
 
1
  import spaces
2
+ from huggingface_hub import InferenceClient
3
  import gradio as gr
4
+ import os
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
+ # Inicjalizacja klienta
7
+ client = InferenceClient(
8
+ model='meta-llama/Meta-Llama-3.1-8B',
9
+ token=os.environ.get("MY_API_LLAMA_3_1")
10
+ )
 
 
11
 
12
  @spaces.GPU(duration=60)
13
  def generate_response(chat, kwargs):
14
+ output = ''
15
+ stream = client.text_generation(chat, **kwargs, stream=True, details=True, return_full_text=False)
16
+ for response in stream:
17
+ output += response.token.text
18
+ if output.endswith("</s>"): # Sprawdzamy, czy odpowiedź kończy się tagiem </s>
19
+ output = output[:-4] # Usuwamy tag </s> z końca odpowiedzi
20
+ return output
 
 
21
 
22
  def function(prompt, history=[]):
23
  chat = "<s>"
24
  for user_prompt, bot_response in history:
25
  chat += f"[INST] {user_prompt} [/INST] {bot_response}</s> <s>"
26
+ chat += f"[INST] {prompt} [/INST]" # Zostawiamy tylko tag otwierający <s> na początku i kończymy ciąg zwykłym znacznikiem
 
27
  kwargs = dict(
 
 
28
  temperature=0.5,
29
+ max_new_tokens=4096,
30
  top_p=0.95,
31
  repetition_penalty=1.0,
32
+ do_sample=True,
33
  seed=1337
34
  )
35
 
36
+ try:
37
+ output = generate_response(chat, kwargs)
38
+ return output
39
+ except Exception as e:
40
+ print(f"Error: {str(e)}")
41
+ return ''
42
 
 
43
  interface = gr.ChatInterface(
44
  fn=function,
45
  chatbot=gr.Chatbot(
 
61
  clear_btn=None
62
  )
63
 
64
+ interface.launch(show_api=True, share=True)