Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
@@ -1,68 +1,70 @@
|
|
1 |
-
import os
|
2 |
import torch
|
3 |
-
from transformers import
|
4 |
-
from
|
5 |
-
import gradio as gr
|
6 |
from typing import Iterator, List, Tuple
|
|
|
7 |
|
8 |
# Constants
|
9 |
-
MAX_INPUT_TOKEN_LENGTH =
|
10 |
DEFAULT_MAX_NEW_TOKENS = 930
|
11 |
|
12 |
-
#
|
13 |
model_id = "meta-llama/Llama-2-7b-hf"
|
14 |
-
bnb_config = BitsAndBytesConfig(
|
15 |
-
load_in_4bit=True,
|
16 |
-
bnb_4bit_use_double_quant=False,
|
17 |
-
bnb_4bit_quant_type="nf4",
|
18 |
-
bnb_4bit_compute_dtype=torch.bfloat16
|
19 |
-
)
|
20 |
-
base_model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto", quantization_config=bnb_config)
|
21 |
-
model_generate = PeftModel.from_pretrained(base_model, "ranamhamoud/storytell")
|
22 |
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
24 |
|
25 |
-
|
26 |
-
|
|
|
|
|
|
|
27 |
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
context = "\n".join([f"{speaker}: {text}" for speaker, text in chat_history])
|
34 |
-
input_ids = tokenizer(context, return_tensors="pt").input_ids.to(model_generate.device)
|
35 |
-
outputs = model_generate.generate(input_ids, max_length=input_ids.shape[1] + max_tokens, do_sample=True)
|
36 |
-
for output in tokenizer.decode(outputs[0], skip_special_tokens=True).split():
|
37 |
-
yield output
|
38 |
-
chat_history.append(("assistant", tokenizer.decode(outputs[0], skip_special_tokens=True)))
|
39 |
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
for output in tokenizer.decode(outputs[0], skip_special_tokens=True).split():
|
45 |
-
yield output
|
46 |
|
47 |
# Gradio Interface
|
48 |
-
def switch_mode(
|
49 |
-
|
50 |
-
return edit_text(input_text, chat_history)
|
51 |
-
elif not is_editing:
|
52 |
-
return generate_text(input_text, chat_history)
|
53 |
-
else:
|
54 |
-
yield "Chat history is empty, cannot edit."
|
55 |
|
56 |
with gr.Blocks() as demo:
|
57 |
with gr.Row():
|
|
|
58 |
input_text = gr.Textbox(label="Input Text")
|
59 |
-
|
60 |
-
|
61 |
-
chat_history = gr.State([]) # Using State to maintain chat history
|
62 |
|
63 |
generate_button = gr.Button("Generate/Edit")
|
64 |
-
generate_button.click(switch_mode, inputs=[
|
65 |
|
66 |
-
# Main Execution
|
67 |
-
if __name__ == "__main__":
|
68 |
demo.launch()
|
|
|
|
|
1 |
import torch
|
2 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
3 |
+
from threading import Thread
|
|
|
4 |
from typing import Iterator, List, Tuple
|
5 |
+
import gradio as gr
|
6 |
|
7 |
# Constants
|
8 |
+
MAX_INPUT_TOKEN_LENGTH = 4096
|
9 |
DEFAULT_MAX_NEW_TOKENS = 930
|
10 |
|
11 |
+
# Load Models and Tokenizers
|
12 |
model_id = "meta-llama/Llama-2-7b-hf"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
13 |
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
14 |
+
model_generate = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float16, device_map="auto")
|
15 |
+
model_edit = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float16, device_map="auto") # Assuming a different setup or hyperparameters
|
16 |
+
|
17 |
+
# Helper function to process text
|
18 |
+
def process_text(text: str) -> str:
|
19 |
+
return text.replace("\n", " ").strip()
|
20 |
+
|
21 |
+
def run_model(input_ids, model, max_new_tokens, top_p, top_k, temperature, repetition_penalty):
|
22 |
+
return model.generate(
|
23 |
+
input_ids=input_ids,
|
24 |
+
max_length=input_ids.shape[1] + max_new_tokens,
|
25 |
+
do_sample=True,
|
26 |
+
top_p=top_p,
|
27 |
+
top_k=top_k,
|
28 |
+
temperature=temperature,
|
29 |
+
num_beams=1,
|
30 |
+
repetition_penalty=repetition_penalty
|
31 |
+
)
|
32 |
+
|
33 |
+
def generate_text(mode: str, message: str, chat_history: List[Tuple[str, str]], max_new_tokens: int = DEFAULT_MAX_NEW_TOKENS,
|
34 |
+
temperature: float = 0.6, top_p: float = 0.7, top_k: int = 20, repetition_penalty: float = 1.0) -> Iterator[str]:
|
35 |
+
conversation = [{"role": "user", "content": user} for user, _ in chat_history]
|
36 |
+
conversation.append({"role": "assistant", "content": assistant} for _, assistant in chat_history)
|
37 |
+
conversation.append({"role": "user", "content": message})
|
38 |
|
39 |
+
context = "\n".join(f"{entry['role']}: {entry['content']}" for entry in conversation)
|
40 |
+
input_ids = tokenizer(context, return_tensors="pt", padding=True, truncation=True).input_ids.to(model_generate.device)
|
41 |
+
if input_ids.shape[1] > MAX_INPUT_TOKEN_LENGTH:
|
42 |
+
input_ids = input_ids[:, -MAX_INPUT_TOKEN_LENGTH:]
|
43 |
+
gr.Warning(f"Trimmed input from conversation as it was longer than {MAX_INPUT_TOKEN_LENGTH} tokens.")
|
44 |
|
45 |
+
model = model_edit if mode == 'edit' else model_generate
|
46 |
+
outputs = []
|
47 |
+
t = Thread(target=lambda: outputs.extend(run_model(input_ids, model, max_new_tokens, top_p, top_k, temperature, repetition_penalty)))
|
48 |
+
t.start()
|
49 |
+
t.join()
|
|
|
|
|
|
|
|
|
|
|
|
|
50 |
|
51 |
+
for output in outputs:
|
52 |
+
for text in tokenizer.decode(output, skip_special_tokens=True).split():
|
53 |
+
processed_text = process_text(text)
|
54 |
+
yield processed_text
|
|
|
|
|
55 |
|
56 |
# Gradio Interface
|
57 |
+
def switch_mode(mode: str, message: str, chat_history: List[Tuple[str, str]]):
|
58 |
+
return list(generate_text(mode, message, chat_history))
|
|
|
|
|
|
|
|
|
|
|
59 |
|
60 |
with gr.Blocks() as demo:
|
61 |
with gr.Row():
|
62 |
+
mode_selector = gr.Radio(["generate", "edit"], label="Mode", value="generate")
|
63 |
input_text = gr.Textbox(label="Input Text")
|
64 |
+
output_text = gr.Textbox(label="Output")
|
65 |
+
chat_history = gr.State(default=[])
|
|
|
66 |
|
67 |
generate_button = gr.Button("Generate/Edit")
|
68 |
+
generate_button.click(switch_mode, inputs=[mode_selector, input_text, chat_history], outputs=output_text)
|
69 |
|
|
|
|
|
70 |
demo.launch()
|