ranamhamoud commited on
Commit
841e4af
·
verified ·
1 Parent(s): f317c15

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -47
app.py CHANGED
@@ -1,68 +1,70 @@
1
- import os
2
  import torch
3
- from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
4
- from peft import PeftModel
5
- import gradio as gr
6
  from typing import Iterator, List, Tuple
 
7
 
8
  # Constants
9
- MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096"))
10
  DEFAULT_MAX_NEW_TOKENS = 930
11
 
12
- # Model Configuration for Generating Mode
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
- tokenizer.pad_token = tokenizer.eos_token
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
- # Editing mode uses the same tokenizer but might use a simpler or different model setup
26
- model_edit = model_generate # For simplicity, using the same model setup for editing in this example
 
 
 
27
 
28
- # Helper Functions
29
- def generate_text(input_text: str, chat_history: List[Tuple[str, str]], max_tokens: int = DEFAULT_MAX_NEW_TOKENS) -> Iterator[str]:
30
- # Append the new message to the chat history for context
31
- chat_history.append(("user", input_text))
32
- # Prepare the input with the conversation context
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
- def edit_text(input_text: str, chat_history: List[Tuple[str, str]]) -> Iterator[str]:
41
- context = "\n".join([f"{speaker}: {text}" for speaker, text in chat_history])
42
- input_ids = tokenizer(context, return_tensors="pt").input_ids.to(model_edit.device)
43
- outputs = model_edit.generate(input_ids, max_length=input_ids.shape[1] + DEFAULT_MAX_NEW_TOKENS, do_sample=True)
44
- for output in tokenizer.decode(outputs[0], skip_special_tokens=True).split():
45
- yield output
46
 
47
  # Gradio Interface
48
- def switch_mode(is_editing: bool, input_text: str, chat_history: List[Tuple[str, str]]) -> Iterator[str]:
49
- if is_editing and chat_history:
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
- is_editing = gr.Checkbox(label="Editing Mode", value=False)
60
- output_text = gr.Textbox(label="Output", interactive=True)
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=[is_editing, input_text, chat_history], outputs=output_text)
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()