Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
@@ -1,43 +1,48 @@
|
|
|
|
1 |
import torch
|
2 |
import gradio as gr
|
3 |
-
from
|
4 |
-
|
5 |
-
# Load the tokenizer and the model
|
6 |
-
tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
|
7 |
-
model = GPT2LMHeadModel.from_pretrained('gpt2')
|
8 |
|
9 |
-
# Load the
|
10 |
-
|
|
|
|
|
|
|
|
|
|
|
11 |
|
12 |
-
#
|
13 |
-
|
14 |
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
|
|
|
|
28 |
|
29 |
-
#
|
30 |
-
|
31 |
fn=generate_text,
|
32 |
inputs=[
|
33 |
-
gr.
|
34 |
-
gr.
|
35 |
-
gr.
|
36 |
],
|
37 |
-
outputs=gr.
|
38 |
title="GPT-2 Text Generator",
|
39 |
-
description="Enter a prompt
|
40 |
)
|
41 |
|
42 |
-
# Launch the
|
43 |
-
|
|
|
1 |
+
|
2 |
import torch
|
3 |
import gradio as gr
|
4 |
+
from model import GPT, GPTConfig # Assuming your model code is in a file named model.py
|
5 |
+
import tiktoken
|
|
|
|
|
|
|
6 |
|
7 |
+
# Load the trained model
|
8 |
+
def load_model(model_path):
|
9 |
+
config = GPTConfig() # Adjust this if you've changed the default config
|
10 |
+
model = GPT(config)
|
11 |
+
model.load_state_dict(torch.load(model_path, map_location=torch.device('cpu')))
|
12 |
+
model.eval()
|
13 |
+
return model
|
14 |
|
15 |
+
model = load_model('GPT_model.pth') # Replace with the actual path to your .pth file
|
16 |
+
enc = tiktoken.get_encoding('gpt2')
|
17 |
|
18 |
+
def generate_text(prompt, max_length=100, temperature=0.7):
|
19 |
+
input_ids = torch.tensor(enc.encode(prompt)).unsqueeze(0)
|
20 |
+
|
21 |
+
with torch.no_grad():
|
22 |
+
for _ in range(max_length):
|
23 |
+
outputs = model(input_ids)
|
24 |
+
next_token_logits = outputs[0][:, -1, :] / temperature
|
25 |
+
next_token = torch.multinomial(torch.softmax(next_token_logits, dim=-1), num_samples=1)
|
26 |
+
input_ids = torch.cat([input_ids, next_token], dim=-1)
|
27 |
+
|
28 |
+
if next_token.item() == enc.encode('\n')[0]:
|
29 |
+
break
|
30 |
+
|
31 |
+
generated_text = enc.decode(input_ids[0].tolist())
|
32 |
+
return generated_text
|
33 |
|
34 |
+
# Gradio interface
|
35 |
+
iface = gr.Interface(
|
36 |
fn=generate_text,
|
37 |
inputs=[
|
38 |
+
gr.Textbox(label="Prompt", placeholder="Enter your prompt here..."),
|
39 |
+
gr.Slider(minimum=10, maximum=200, value=100, step=1, label="Max Length"),
|
40 |
+
gr.Slider(minimum=0.1, maximum=1.0, value=0.7, step=0.1, label="Temperature")
|
41 |
],
|
42 |
+
outputs=gr.Textbox(label="Generated Text"),
|
43 |
title="GPT-2 Text Generator",
|
44 |
+
description="Enter a prompt and generate text using a fine-tuned GPT-2 model."
|
45 |
)
|
46 |
|
47 |
+
# Launch the app
|
48 |
+
iface.launch()
|