huang342 commited on
Commit
b520632
·
verified ·
1 Parent(s): 0f9539f

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +135 -50
app.py CHANGED
@@ -1,64 +1,149 @@
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
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  )
61
 
 
 
62
 
63
- if __name__ == "__main__":
64
- demo.launch()
 
1
+ # -*- coding: utf-8 -*-
2
+ """app
3
 
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1OBF9xRogFp1BlMVFwZX6R-0jD8yU_tEk
8
  """
 
 
 
9
 
10
+ import torch
11
+ import torch.nn as nn
12
+ from torch.nn import functional as F
13
+ import gradio as gr
14
+
15
+ # hyperparameters
16
+ batch_size = 16
17
+ block_size = 32
18
+ n_embd = 64
19
+ n_head = 4
20
+ n_layer = 4
21
+ dropout = 0.0
22
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
23
 
24
+ # Load Book of Mormon text
25
+ with open('Book of Mormon.txt', 'r', encoding='utf-8') as f:
26
+ text = f.read()
 
 
 
 
 
 
27
 
28
+ # Tokenizer setup
29
+ chars = sorted(list(set(text)))
30
+ stoi = {ch: i for i, ch in enumerate(chars)}
31
+ itos = {i: ch for i, ch in enumerate(chars)}
32
+ encode = lambda s: [stoi[c] for c in s]
33
+ decode = lambda l: ''.join([itos[i] for i in l])
34
 
35
+ # Model definition
36
+ class BigramLanguageModel(nn.Module):
37
+ def __init__(self):
38
+ super().__init__()
39
+ self.token_embedding_table = nn.Embedding(len(chars), n_embd)
40
+ self.position_embedding_table = nn.Embedding(block_size, n_embd)
41
+ self.blocks = nn.Sequential(*[Block(n_embd, n_head=n_head) for _ in range(n_layer)])
42
+ self.ln_f = nn.LayerNorm(n_embd)
43
+ self.lm_head = nn.Linear(n_embd, len(chars))
44
 
45
+ def forward(self, idx, targets=None):
46
+ tok_emb = self.token_embedding_table(idx)
47
+ pos_emb = self.position_embedding_table(torch.arange(idx.shape[1], device=device))
48
+ x = tok_emb + pos_emb
49
+ x = self.blocks(x)
50
+ x = self.ln_f(x)
51
+ logits = self.lm_head(x)
52
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1)) if targets is not None else None
53
+ return logits, loss
54
 
55
+ def generate(self, idx, max_new_tokens):
56
+ for _ in range(max_new_tokens):
57
+ idx_cond = idx[:, -block_size:]
58
+ logits, _ = self(idx_cond)
59
+ logits = logits[:, -1, :]
60
+ probs = F.softmax(logits, dim=-1)
61
+ idx_next = torch.multinomial(probs, num_samples=1)
62
+ idx = torch.cat((idx, idx_next), dim=1)
63
+ return idx
64
 
65
+ class Block(nn.Module):
66
+ def __init__(self, n_embd, n_head):
67
+ super().__init__()
68
+ head_size = n_embd // n_head
69
+ self.sa = MultiHeadAttention(n_head, head_size)
70
+ self.ffwd = FeedForward(n_embd)
71
+ self.ln1 = nn.LayerNorm(n_embd)
72
+ self.ln2 = nn.LayerNorm(n_embd)
73
 
74
+ def forward(self, x):
75
+ x = x + self.sa(self.ln1(x))
76
+ x = x + self.ffwd(self.ln2(x))
77
+ return x
78
 
79
+ class MultiHeadAttention(nn.Module):
80
+ def __init__(self, num_heads, head_size):
81
+ super().__init__()
82
+ self.heads = nn.ModuleList([Head(head_size) for _ in range(num_heads)])
83
+ self.proj = nn.Linear(n_embd, n_embd)
84
+ self.dropout = nn.Dropout(dropout)
85
+
86
+ def forward(self, x):
87
+ out = torch.cat([h(x) for h in self.heads], dim=-1)
88
+ out = self.dropout(self.proj(out))
89
+ return out
90
+
91
+ class Head(nn.Module):
92
+ def __init__(self, head_size):
93
+ super().__init__()
94
+ self.key = nn.Linear(n_embd, head_size, bias=False)
95
+ self.query = nn.Linear(n_embd, head_size, bias=False)
96
+ self.value = nn.Linear(n_embd, head_size, bias=False)
97
+ self.register_buffer('tril', torch.tril(torch.ones(block_size, block_size)))
98
+
99
+ def forward(self, x):
100
+ k, q, v = self.key(x), self.query(x), self.value(x)
101
+ wei = q @ k.transpose(-2, -1) * (k.size(-1) ** -0.5)
102
+ wei = wei.masked_fill(self.tril[:x.size(1), :x.size(1)] == 0, float('-inf'))
103
+ wei = F.softmax(wei, dim=-1)
104
+ return wei @ v
105
+
106
+ class FeedForward(nn.Module):
107
+ def __init__(self, n_embd):
108
+ super().__init__()
109
+ self.net = nn.Sequential(
110
+ nn.Linear(n_embd, 4 * n_embd),
111
+ nn.ReLU(),
112
+ nn.Linear(4 * n_embd, n_embd),
113
+ nn.Dropout(dropout)
114
+ )
115
+
116
+ def forward(self, x):
117
+ return self.net(x)
118
+
119
+ # Load pre-trained model
120
+ model = BigramLanguageModel()
121
+ model.load_state_dict(torch.load('model.pth', map_location=device))
122
+ model.eval()
123
+
124
+ # Gradio functions
125
+ def ask_question(question, max_new_tokens=100):
126
+ context_text = f"Q: {question}\nA:"
127
+ context_tokens = torch.tensor(encode(context_text), dtype=torch.long, device=device).unsqueeze(0)
128
+ generated_tokens = model.generate(context_tokens, max_new_tokens=max_new_tokens)
129
+ generated_text = decode(generated_tokens[0].tolist())
130
+ return generated_text.split("A:")[1].strip()
131
+
132
+ def chatbot_response(question):
133
+ try:
134
+ return ask_question(question)
135
+ except Exception as e:
136
+ return f"Error: {e}"
137
+
138
+ # Gradio Interface
139
+ demo = gr.Interface(
140
+ fn=chatbot_response,
141
+ inputs="text",
142
+ outputs="text",
143
+ title="Religious Chatbot",
144
+ description="Ask questions about the Book of Mormon."
145
  )
146
 
147
+ # Launch the app
148
+ demo.launch()
149