sagar007 commited on
Commit
b8fabde
·
verified ·
1 Parent(s): 01898e8

update app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -62
app.py CHANGED
@@ -1,63 +1,84 @@
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
- """
43
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
44
- """
45
- demo = gr.ChatInterface(
46
- respond,
47
- additional_inputs=[
48
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
49
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
50
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
51
- gr.Slider(
52
- minimum=0.1,
53
- maximum=1.0,
54
- value=0.95,
55
- step=0.05,
56
- label="Top-p (nucleus sampling)",
57
- ),
58
- ],
59
- )
60
-
61
-
62
- if __name__ == "__main__":
63
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
  import gradio as gr
4
+ from torch.nn import functional as F
5
+
6
+ # Define your model and any necessary helper functions here
7
+ class BigramLanguageModel(nn.Module):
8
+ def __init__(self):
9
+ super().__init__()
10
+ # each token directly reads off the logits for the next token from a lookup table
11
+ self.token_embedding_table = nn.Embedding(vocab_size, n_embd)
12
+ self.position_embedding_table = nn.Embedding(block_size, n_embd)
13
+ self.blocks = nn.Sequential(*[Block(n_embd, n_head=n_head) for _ in range(n_layer)])
14
+ self.ln_f = nn.LayerNorm(n_embd) # final layer norm
15
+ self.lm_head = nn.Linear(n_embd, vocab_size)
16
+
17
+ def forward(self, idx, targets=None):
18
+ B, T = idx.shape
19
+
20
+ # idx and targets are both (B, T) tensor of integers
21
+ tok_emb = self.token_embedding_table(idx) # (B, T, C)
22
+ pos_emb = self.position_embedding_table(torch.arange(T, device=device)) # (T, C)
23
+ x = tok_emb + pos_emb # (B, T, C)
24
+ x = self.blocks(x) # (B, T, C)
25
+ x = self.ln_f(x) # (B, T, C)
26
+ logits = self.lm_head(x) # (B, T, vocab_size)
27
+
28
+ if targets is None:
29
+ loss = None
30
+ else:
31
+ B, T, C = logits.shape
32
+ logits = logits.view(B * T, C)
33
+ targets = targets.view(B * T)
34
+ loss = F.cross_entropy(logits, targets)
35
+
36
+ return logits, loss
37
+
38
+ def generate(self, idx, max_new_tokens):
39
+ for _ in range(max_new_tokens):
40
+ idx_cond = idx[:, -block_size:]
41
+ logits, loss = self(idx_cond)
42
+ logits = logits[:, -1, :]
43
+ probs = F.softmax(logits, dim=-1)
44
+ idx_next = torch.multinomial(probs, num_samples=1)
45
+ idx = torch.cat((idx, idx_next), dim=1)
46
+ return idx
47
+
48
+ # Initialize model
49
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
50
+ vocab_size = 65 # Update this with the correct vocab size
51
+ n_embd = 64
52
+ n_head = 4
53
+ n_layer = 4
54
+ block_size = 32
55
+
56
+ model = BigramLanguageModel()
57
+ model.load_state_dict(torch.load('bigram_language_model.pth', map_location=device))
58
+ model.to(device)
59
+ model.eval()
60
+
61
+ # Character mappings (ensure these match your training setup)
62
+ stoi = {ch: i for i, ch in enumerate(chars)}
63
+ itos = {i: ch for i, ch in enumerate(chars)}
64
+
65
+ def encode(s):
66
+ return [stoi[c] for c in s]
67
+
68
+ def decode(l):
69
+ return ''.join([itos[i] for i in l])
70
+
71
+ def generate_text(input_text):
72
+ idx = torch.tensor(encode(input_text), dtype=torch.long).unsqueeze(0).to(device)
73
+ generated_idx = model.generate(idx, max_new_tokens=200)
74
+ generated_text = decode(generated_idx[0].tolist())
75
+ return generated_text
76
+
77
+ # Create Gradio Interface
78
+ iface = gr.Interface(fn=generate_text,
79
+ inputs=gr.inputs.Textbox(lines=5, label="Input Text"),
80
+ outputs=gr.outputs.Textbox(label="Generated Text"),
81
+ title="Shakespeare-like Text Generator",
82
+ description="Enter some text and the model will generate Shakespeare-like text.")
83
+
84
+ iface.launch()