Commit
·
35a6fb3
1
Parent(s):
32b39e3
Update space
Browse files- app.py +96 -50
- requirements.txt +5 -1
app.py
CHANGED
@@ -1,64 +1,110 @@
|
|
|
|
1 |
import gradio as gr
|
2 |
-
from
|
|
|
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 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
|
|
|
|
19 |
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
|
|
|
|
25 |
|
26 |
-
|
|
|
|
|
27 |
|
28 |
-
|
|
|
|
|
29 |
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
):
|
37 |
-
token = message.choices[0].delta.content
|
38 |
|
39 |
-
|
40 |
-
|
|
|
|
|
|
|
|
|
|
|
41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
42 |
|
43 |
-
|
44 |
-
|
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 |
-
|
|
|
1 |
+
import torch
|
2 |
import gradio as gr
|
3 |
+
from tokenizers import Tokenizer
|
4 |
+
from transformers import PreTrainedTokenizerFast
|
5 |
|
6 |
+
from transformer_chat import TransformerChatbot
|
|
|
|
|
|
|
7 |
|
8 |
+
# Load tokenizer & wrap for HF API
|
9 |
+
tokenizer_obj = Tokenizer.from_file("tokenizer.json")
|
10 |
+
hf_tok = PreTrainedTokenizerFast(
|
11 |
+
tokenizer_object=tokenizer_obj,
|
12 |
+
unk_token="[UNK]",
|
13 |
+
pad_token="[PAD]",
|
14 |
+
cls_token="[CLS]",
|
15 |
+
sep_token="[SEP]",
|
16 |
+
mask_token="[MASK]"
|
17 |
+
)
|
18 |
|
19 |
+
# Load model
|
20 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
21 |
+
model = TransformerChatbot(
|
22 |
+
vocab_size=hf_tok.vocab_size,
|
23 |
+
d_model=512, num_heads=8, d_ff=2048,
|
24 |
+
num_encoder_layers=6, num_decoder_layers=6,
|
25 |
+
num_roles=2, max_turns=16, num_slots=22,
|
26 |
+
dropout=0.1
|
27 |
+
).to(device)
|
28 |
+
model.load_state_dict(torch.load("atis_transformer.pt", map_location=device))
|
29 |
+
model.eval()
|
30 |
|
31 |
+
# Generation function
|
32 |
+
def chat_fn(prompt):
|
33 |
+
# Encode user input
|
34 |
+
enc = hf_tok(prompt, return_tensors="pt", padding=True, truncation=True, max_length=128)
|
35 |
+
src_ids = enc.input_ids.to(device)
|
36 |
+
# For cross-attention, we don't need to mask the encoder output
|
37 |
+
src_mask = None
|
38 |
|
39 |
+
# Roles & turns (user=0)
|
40 |
+
roles = torch.zeros_like(src_ids)
|
41 |
+
turns = torch.zeros_like(src_ids)
|
42 |
|
43 |
+
# Encode
|
44 |
+
with torch.no_grad():
|
45 |
+
enc_out = model.encode(src_ids, roles, turns, src_mask)
|
46 |
|
47 |
+
# Generate reply token-by-token
|
48 |
+
cls_id = hf_tok.cls_token_id
|
49 |
+
sep_id = hf_tok.sep_token_id
|
50 |
+
dec_input = torch.tensor([[cls_id]], device=device)
|
51 |
+
dec_roles = torch.zeros_like(dec_input)
|
52 |
+
dec_turns = torch.zeros_like(dec_input)
|
|
|
|
|
53 |
|
54 |
+
generated = []
|
55 |
+
for step in range(50):
|
56 |
+
T = dec_input.size(1)
|
57 |
+
# Create causal mask for decoder (upper triangular = masked)
|
58 |
+
# PyTorch's MultiheadAttention expects a 2D mask where True = masked
|
59 |
+
causal_mask = torch.triu(torch.ones((T, T), device=device), diagonal=1).bool()
|
60 |
+
tgt_mask = causal_mask
|
61 |
|
62 |
+
logits = model.decode(dec_input, enc_out, dec_roles, dec_turns, src_mask, tgt_mask)
|
63 |
+
|
64 |
+
# Get the last token's logits
|
65 |
+
last_logits = logits[0, -1, :]
|
66 |
+
|
67 |
+
# Apply repetition penalty
|
68 |
+
if generated:
|
69 |
+
for token_id in set(generated):
|
70 |
+
last_logits[token_id] *= 0.7 # Penalize repeated tokens
|
71 |
+
|
72 |
+
# Sample with temperature instead of greedy decoding
|
73 |
+
temperature = 0.8
|
74 |
+
probs = torch.softmax(last_logits / temperature, dim=-1)
|
75 |
+
next_id = torch.multinomial(probs, 1)
|
76 |
+
|
77 |
+
# Debug: print the token being generated
|
78 |
+
token_text = hf_tok.decode([next_id.item()])
|
79 |
+
print(f"Step {step}: Generated token ID {next_id.item()} -> '{token_text}'")
|
80 |
+
|
81 |
+
if next_id.item() == sep_id:
|
82 |
+
print("Found SEP token, stopping generation")
|
83 |
+
break
|
84 |
+
|
85 |
+
generated.append(next_id.item())
|
86 |
+
dec_input = torch.cat([dec_input, next_id.unsqueeze(0)], dim=1)
|
87 |
+
dec_roles = torch.cat([dec_roles, torch.zeros_like(next_id).unsqueeze(0)], dim=1)
|
88 |
+
dec_turns = torch.cat([dec_turns, torch.zeros_like(next_id).unsqueeze(0)], dim=1)
|
89 |
+
|
90 |
+
# Early stopping if we're stuck in a loop
|
91 |
+
if len(generated) >= 3 and len(set(generated[-3:])) == 1:
|
92 |
+
print("Detected repetition loop, stopping generation")
|
93 |
+
break
|
94 |
|
95 |
+
output_ids = [cls_id] + generated + [sep_id]
|
96 |
+
reply = hf_tok.decode(output_ids, skip_special_tokens=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
97 |
|
98 |
+
return reply
|
99 |
+
|
100 |
+
# Build Gradio interface
|
101 |
+
interface = gr.Interface(
|
102 |
+
fn=chat_fn,
|
103 |
+
inputs=gr.Textbox(lines=2, placeholder="Enter your question here..."),
|
104 |
+
outputs="text",
|
105 |
+
title="Transformer Chatbot Demo (currently trained with ATIS dataset)",
|
106 |
+
description="Ask flight-related questions and get an answer."
|
107 |
+
)
|
108 |
|
109 |
if __name__ == "__main__":
|
110 |
+
interface.launch(share=True)
|
requirements.txt
CHANGED
@@ -1 +1,5 @@
|
|
1 |
-
huggingface_hub==0.25.2
|
|
|
|
|
|
|
|
|
|
1 |
+
huggingface_hub==0.25.2
|
2 |
+
torch
|
3 |
+
transformers
|
4 |
+
tokenizers
|
5 |
+
datasets
|