CreitinGameplays commited on
Commit
f15ed8e
1 Parent(s): 5b58842

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +109 -64
app.py CHANGED
@@ -1,83 +1,128 @@
 
 
 
 
 
 
1
  import gradio as gr
2
- import torch
3
  import spaces
4
- import bitsandbytes as bnb
5
- from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
6
-
7
- # Define the model name
8
- model_name = "CreitinGameplays/ConvAI-9b"
9
 
10
- # Quantization configuration with bitsandbytes settings
11
- bnb_config = BitsAndBytesConfig(
12
- load_in_4bit=True,
13
- bnb_4bit_use_double_quant=True,
14
- bnb_4bit_quant_type="nf4",
15
- bnb_4bit_compute_dtype=torch.bfloat16
16
- )
17
 
18
- # Load tokenizer and model
19
- tokenizer = AutoTokenizer.from_pretrained(model_name)
20
- model = AutoModelForCausalLM.from_pretrained(model_name, quantization_config=bnb_config, low_cpu_mem_usage=True)
21
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
22
- #model.to(device)
23
 
24
- # Initialize chat history
25
- chat_history = []
 
26
 
27
- @spaces.GPU(duration=120)
28
- def generate_text(user_prompt, top_p, top_k, temperature):
29
- """Generates text using the ConvAI model from Hugging Face Transformers and maintains conversation history."""
30
- # System introduction
31
- system = "You are a helpful AI language model called ChatGPT, your goal is helping users with their questions."
32
 
33
- # Append user prompt to chat history
34
- chat_history.append(f"User: {user_prompt}")
35
 
36
- # Construct the full prompt with system introduction, user prompt, and assistant role
37
- prompt = f"{system} </s> {' '.join(chat_history)} </s>"
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
- # Encode the entire prompt into tokens
40
- prompt_encoded = tokenizer.encode(prompt, return_tensors="pt").to(device)
 
 
 
41
 
42
- # Generate text with the complete prompt and limit the maximum length to 256 tokens
43
- output = model.generate(
44
- input_ids=prompt_encoded,
45
- max_length=1550,
46
- num_beams=1,
47
- num_return_sequences=1,
48
  do_sample=True,
49
- top_k=top_k,
50
  top_p=top_p,
 
51
  temperature=temperature,
52
- repetition_penalty=1.2
 
53
  )
 
 
54
 
55
- # Decode the generated token sequence back to text
56
- generated_text = tokenizer.decode(output[0], skip_special_tokens=True)
57
-
58
- # Extract the assistant's response
59
- assistant_response = generated_text.split("User:")[-1].strip()
60
- chat_history.append(f"Assistant: {assistant_response}")
61
-
62
- return "\n".join(chat_history)
63
 
64
- def reset_history():
65
- global chat_history
66
- chat_history = []
67
- return "Chat history reset."
68
 
69
- # Define the Gradio interface
70
- interface = gr.Interface(
71
- fn=generate_text,
72
- inputs=[
73
- gr.Textbox(label="Text Prompt", value="What's an AI?"),
74
- gr.Slider(0, 1, value=0.9, label="Top-p"),
75
- gr.Slider(1, 100, value=50, step=1, label="Top-k"),
76
- gr.Slider(0.01, 1, value=0.2, label="Temperature")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  ],
78
- outputs="text",
79
- description="Interact with ConvAI (Loaded with Hugging Face Transformers)",
80
- live=True
81
  )
82
- # Launch the Gradio interface
83
- interface.launch()
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ import os
4
+ from threading import Thread
5
+ from typing import Iterator
6
+
7
  import gradio as gr
 
8
  import spaces
9
+ import torch
10
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
 
 
 
11
 
12
+ DESCRIPTION = "# Mistral-7B v0.2"
 
 
 
 
 
 
13
 
14
+ if not torch.cuda.is_available():
15
+ DESCRIPTION += "\n<p>Running on CPU 🥶 This demo does not work on CPU.</p>"
 
 
 
16
 
17
+ MAX_MAX_NEW_TOKENS = 2048
18
+ DEFAULT_MAX_NEW_TOKENS = 1024
19
+ MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096"))
20
 
21
+ if torch.cuda.is_available():
22
+ model_id = "mistralai/Mistral-7B-Instruct-v0.2"
23
+ model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float16, device_map="auto")
24
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
 
25
 
 
 
26
 
27
+ @spaces.GPU
28
+ def generate(
29
+ message: str,
30
+ chat_history: list[tuple[str, str]],
31
+ max_new_tokens: int = 1024,
32
+ temperature: float = 0.6,
33
+ top_p: float = 0.9,
34
+ top_k: int = 50,
35
+ repetition_penalty: float = 1.2,
36
+ ) -> Iterator[str]:
37
+ conversation = []
38
+ for user, assistant in chat_history:
39
+ conversation.extend([{"role": "user", "content": user}, {"role": "assistant", "content": assistant}])
40
+ conversation.append({"role": "user", "content": message})
41
 
42
+ input_ids = tokenizer.apply_chat_template(conversation, return_tensors="pt")
43
+ if input_ids.shape[1] > MAX_INPUT_TOKEN_LENGTH:
44
+ input_ids = input_ids[:, -MAX_INPUT_TOKEN_LENGTH:]
45
+ gr.Warning(f"Trimmed input from conversation as it was longer than {MAX_INPUT_TOKEN_LENGTH} tokens.")
46
+ input_ids = input_ids.to(model.device)
47
 
48
+ streamer = TextIteratorStreamer(tokenizer, timeout=20.0, skip_prompt=True, skip_special_tokens=True)
49
+ generate_kwargs = dict(
50
+ {"input_ids": input_ids},
51
+ streamer=streamer,
52
+ max_new_tokens=max_new_tokens,
 
53
  do_sample=True,
 
54
  top_p=top_p,
55
+ top_k=top_k,
56
  temperature=temperature,
57
+ num_beams=1,
58
+ repetition_penalty=repetition_penalty,
59
  )
60
+ t = Thread(target=model.generate, kwargs=generate_kwargs)
61
+ t.start()
62
 
63
+ outputs = []
64
+ for text in streamer:
65
+ outputs.append(text)
66
+ yield "".join(outputs)
 
 
 
 
67
 
 
 
 
 
68
 
69
+ chat_interface = gr.ChatInterface(
70
+ fn=generate,
71
+ additional_inputs=[
72
+ gr.Slider(
73
+ label="Max new tokens",
74
+ minimum=1,
75
+ maximum=MAX_MAX_NEW_TOKENS,
76
+ step=1,
77
+ value=DEFAULT_MAX_NEW_TOKENS,
78
+ ),
79
+ gr.Slider(
80
+ label="Temperature",
81
+ minimum=0.1,
82
+ maximum=4.0,
83
+ step=0.1,
84
+ value=0.6,
85
+ ),
86
+ gr.Slider(
87
+ label="Top-p (nucleus sampling)",
88
+ minimum=0.05,
89
+ maximum=1.0,
90
+ step=0.05,
91
+ value=0.9,
92
+ ),
93
+ gr.Slider(
94
+ label="Top-k",
95
+ minimum=1,
96
+ maximum=1000,
97
+ step=1,
98
+ value=50,
99
+ ),
100
+ gr.Slider(
101
+ label="Repetition penalty",
102
+ minimum=1.0,
103
+ maximum=2.0,
104
+ step=0.05,
105
+ value=1.2,
106
+ ),
107
+ ],
108
+ stop_btn=None,
109
+ examples=[
110
+ ["Hello there! How are you doing?"],
111
+ ["Can you explain briefly to me what is the Python programming language?"],
112
+ ["Explain the plot of Cinderella in a sentence."],
113
+ ["How many hours does it take a man to eat a Helicopter?"],
114
+ ["Write a 100-word article on 'Benefits of Open-Source in AI research'"],
115
  ],
 
 
 
116
  )
117
+
118
+ with gr.Blocks(css="style.css") as demo:
119
+ gr.Markdown(DESCRIPTION)
120
+ gr.DuplicateButton(
121
+ value="Duplicate Space for private use",
122
+ elem_id="duplicate-button",
123
+ visible=os.getenv("SHOW_DUPLICATE_BUTTON") == "1",
124
+ )
125
+ chat_interface.render()
126
+
127
+ if __name__ == "__main__":
128
+ demo.queue(max_size=20).launch()