codinglabsong commited on
Commit
97ff2e1
·
verified ·
1 Parent(s): e73e872

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -0
app.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import gradio as gr
3
+ from transformers import AutoTokenizer
4
+ from transformers import BartForConditionalGeneration
5
+ from peft import PeftModel
6
+
7
+
8
+ def load_model():
9
+ """
10
+ Load environment variables, tokenizer, and the fine-tuned LoRA model.
11
+ """
12
+ load_environ_vars()
13
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
14
+
15
+ # Load tokenizer and base model
16
+ tokenizer = AutoTokenizer.from_pretrained("facebook/bart-base")
17
+ base_model = BartForConditionalGeneration.from_pretrained("facebook/bart-base")
18
+ # Use efficient attention if desired
19
+ base_model.config.attn_implementation = "sdpa"
20
+
21
+ # Load PEFT (LoRA) model for inference
22
+ model = PeftModel.from_pretrained(base_model, "outputs/bart-base-reddit-lora").eval()
23
+ model.to(device)
24
+ model.eval()
25
+
26
+ return tokenizer, model, device
27
+
28
+
29
+ # Load once at startup
30
+ tokenizer, model, device = load_model()
31
+
32
+
33
+ def predict(text: str) -> str:
34
+ """
35
+ Generate a response for a single input text.
36
+ """
37
+ # Tokenize and move inputs to device
38
+ inputs = tokenizer(
39
+ text,
40
+ return_tensors="pt",
41
+ padding=True,
42
+ truncation=True,
43
+ ).to(device)
44
+
45
+ # Generate with both beam search and sampling for diversity
46
+ outputs = model.generate(
47
+ **inputs,
48
+ max_length=500,
49
+ num_beams=5,
50
+ do_sample=True,
51
+ length_penalty=1.2,
52
+ repetition_penalty=1.3,
53
+ no_repeat_ngram_size=3,
54
+ top_p=0.9,
55
+ temperature=0.8,
56
+ early_stopping=True,
57
+ eos_token_id=tokenizer.eos_token_id,
58
+ )
59
+
60
+ # Decode the first generated sequence
61
+ return tokenizer.decode(outputs[0], skip_special_tokens=True)
62
+
63
+
64
+ def main():
65
+ interface = gr.Interface(
66
+ fn=predict,
67
+ inputs=gr.Textbox(lines=5, placeholder="Ask a Question", label="Your Question"),
68
+ outputs=gr.Textbox(label="Model Output"),
69
+ title="Bart-Reddit-LoRA Inference",
70
+ description="Enter your prompt and click Submit to get the model's response.",
71
+ allow_flagging="never",
72
+ )
73
+ interface.launch()
74
+
75
+
76
+ if __name__ == "__main__":
77
+ main()