amlanr66 commited on
Commit
2f38d24
·
verified ·
1 Parent(s): 6fa29e0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +95 -88
app.py CHANGED
@@ -1,89 +1,96 @@
1
- import gradio as gr
2
- import torch
3
- import torch.nn.functional as F
4
- import tiktoken
5
- from model import GPT, GPTConfig # We'll create this file next
6
-
7
- # Initialize model and load weights
8
- def load_model():
9
- model = GPT(GPTConfig(
10
- block_size=128,
11
- vocab_size=50257,
12
- n_layer=12,
13
- n_head=12,
14
- n_embd=768
15
- ))
16
-
17
- checkpoint = torch.load('best_model.pt', map_location=torch.device('cpu'))
18
- model.load_state_dict(checkpoint['model_state_dict'])
19
- model.eval()
20
- return model
21
-
22
- # Text generation function
23
- def generate_text(prompt, max_length=50, temperature=0.8, top_k=50):
24
- # Encode the prompt
25
- enc = tiktoken.get_encoding('gpt2')
26
- input_ids = torch.tensor(enc.encode(prompt)).unsqueeze(0) # Add batch dimension
27
-
28
- # Generate text
29
- with torch.no_grad():
30
- for _ in range(max_length):
31
- # Get the last block_size tokens
32
- input_ids_cond = input_ids[:, -model.config.block_size:]
33
-
34
- # Forward pass
35
- logits = model(input_ids_cond)[0]
36
- logits = logits[:, -1, :] / temperature
37
-
38
- # Apply top-k sampling
39
- if top_k is not None:
40
- v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
41
- logits[logits < v[:, [-1]]] = float('-inf')
42
-
43
- # Sample from the distribution
44
- probs = F.softmax(logits, dim=-1)
45
- next_token = torch.multinomial(probs, num_samples=1)
46
-
47
- # Append the new token
48
- input_ids = torch.cat((input_ids, next_token), dim=1)
49
-
50
- # Decode the generated text
51
- generated_text = enc.decode(input_ids[0].tolist())
52
- return generated_text
53
-
54
- # Load the model globally
55
- model = load_model()
56
-
57
- # Create Gradio interface
58
- def predict(text, length, temp):
59
- try:
60
- output = generate_text(
61
- prompt=text,
62
- max_length=int(length),
63
- temperature=float(temp)
64
- )
65
- return output
66
- except Exception as e:
67
- return f"Error: {str(e)}"
68
-
69
- # Define the interface
70
- iface = gr.Interface(
71
- fn=predict,
72
- inputs=[
73
- gr.Textbox(label="Input Text", placeholder="Enter your prompt here..."),
74
- gr.Slider(minimum=10, maximum=200, value=50, step=1, label="Maximum Length"),
75
- gr.Slider(minimum=0.1, maximum=2.0, value=0.8, step=0.1, label="Temperature")
76
- ],
77
- outputs=gr.Textbox(label="Generated Text"),
78
- title="GPT Text Generation",
79
- description="Enter a prompt and the model will continue the text.",
80
- examples=[
81
- ["The quick brown fox", 50, 0.8],
82
- ["Once upon a time", 100, 0.9],
83
- ["In a world where", 75, 0.7]
84
- ]
85
- )
86
-
87
- # Launch the app
88
- if __name__ == "__main__":
 
 
 
 
 
 
 
89
  iface.launch()
 
1
+ import gradio as gr
2
+ import torch
3
+ import torch.nn.functional as F
4
+ import tiktoken
5
+ from model import GPT, GPTConfig # We'll create this file next
6
+ from huggingface_hub import hf_hub_download
7
+
8
+ # Initialize model and load weights
9
+ def load_model():
10
+ model = GPT(GPTConfig(
11
+ block_size=128,
12
+ vocab_size=50257,
13
+ n_layer=12,
14
+ n_head=12,
15
+ n_embd=768
16
+ ))
17
+
18
+ # Download the model from the Hub
19
+ model_path = hf_hub_download(
20
+ repo_id="amlanr66/gpt2TransformerCustomeTrained", # Replace with your model repository
21
+ filename="best_model.pt"
22
+ )
23
+
24
+ checkpoint = torch.load(model_path, map_location=torch.device('cpu'))
25
+ model.load_state_dict(checkpoint['model_state_dict'])
26
+ model.eval()
27
+ return model
28
+
29
+ # Text generation function
30
+ def generate_text(prompt, max_length=50, temperature=0.8, top_k=50):
31
+ # Encode the prompt
32
+ enc = tiktoken.get_encoding('gpt2')
33
+ input_ids = torch.tensor(enc.encode(prompt)).unsqueeze(0) # Add batch dimension
34
+
35
+ # Generate text
36
+ with torch.no_grad():
37
+ for _ in range(max_length):
38
+ # Get the last block_size tokens
39
+ input_ids_cond = input_ids[:, -model.config.block_size:]
40
+
41
+ # Forward pass
42
+ logits = model(input_ids_cond)[0]
43
+ logits = logits[:, -1, :] / temperature
44
+
45
+ # Apply top-k sampling
46
+ if top_k is not None:
47
+ v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
48
+ logits[logits < v[:, [-1]]] = float('-inf')
49
+
50
+ # Sample from the distribution
51
+ probs = F.softmax(logits, dim=-1)
52
+ next_token = torch.multinomial(probs, num_samples=1)
53
+
54
+ # Append the new token
55
+ input_ids = torch.cat((input_ids, next_token), dim=1)
56
+
57
+ # Decode the generated text
58
+ generated_text = enc.decode(input_ids[0].tolist())
59
+ return generated_text
60
+
61
+ # Load the model globally
62
+ model = load_model()
63
+
64
+ # Create Gradio interface
65
+ def predict(text, length, temp):
66
+ try:
67
+ output = generate_text(
68
+ prompt=text,
69
+ max_length=int(length),
70
+ temperature=float(temp)
71
+ )
72
+ return output
73
+ except Exception as e:
74
+ return f"Error: {str(e)}"
75
+
76
+ # Define the interface
77
+ iface = gr.Interface(
78
+ fn=predict,
79
+ inputs=[
80
+ gr.Textbox(label="Input Text", placeholder="Enter your prompt here..."),
81
+ gr.Slider(minimum=10, maximum=200, value=50, step=1, label="Maximum Length"),
82
+ gr.Slider(minimum=0.1, maximum=2.0, value=0.8, step=0.1, label="Temperature")
83
+ ],
84
+ outputs=gr.Textbox(label="Generated Text"),
85
+ title="GPT Text Generation",
86
+ description="Enter a prompt and the model will continue the text.",
87
+ examples=[
88
+ ["The quick brown fox", 50, 0.8],
89
+ ["Once upon a time", 100, 0.9],
90
+ ["In a world where", 75, 0.7]
91
+ ]
92
+ )
93
+
94
+ # Launch the app
95
+ if __name__ == "__main__":
96
  iface.launch()