Update app.py
Browse files
app.py
CHANGED
@@ -1,152 +1,44 @@
|
|
1 |
import gradio as gr
|
2 |
-
from transformers import
|
3 |
-
from safetensors.torch import load_model
|
4 |
import torch
|
5 |
-
import math
|
6 |
-
import torch.nn as nn
|
7 |
|
8 |
-
|
9 |
-
|
10 |
-
class FusedQKVAttention(nn.Module):
|
11 |
-
def __init__(self, d_model, num_heads):
|
12 |
-
super().__init__()
|
13 |
-
self.d_model = d_model
|
14 |
-
self.num_heads = num_heads
|
15 |
-
self.head_dim = d_model // num_heads
|
16 |
-
self.qkv_proj = nn.Linear(d_model, 3 * d_model)
|
17 |
-
self.wo = nn.Linear(d_model, d_model)
|
18 |
-
nn.init.xavier_uniform_(self.qkv_proj.weight)
|
19 |
-
nn.init.xavier_uniform_(self.wo.weight)
|
20 |
-
nn.init.zeros_(self.qkv_proj.bias)
|
21 |
-
nn.init.zeros_(self.wo.bias)
|
22 |
-
|
23 |
-
def forward(self, x, attention_mask=None):
|
24 |
-
batch_size, seq_len, _ = x.shape
|
25 |
-
qkv = self.qkv_proj(x).reshape(batch_size, seq_len, 3, self.num_heads, self.head_dim)
|
26 |
-
qkv = qkv.permute(2, 0, 3, 1, 4)
|
27 |
-
q, k, v = qkv[0], qkv[1], qkv[2]
|
28 |
-
attention_scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.head_dim)
|
29 |
-
if attention_mask is not None:
|
30 |
-
attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
|
31 |
-
attention_scores = attention_scores.masked_fill(attention_mask == 0, float('-inf'))
|
32 |
-
attention_weights = torch.softmax(attention_scores, dim=-1)
|
33 |
-
context = torch.matmul(attention_weights, v)
|
34 |
-
context = context.transpose(1, 2).reshape(batch_size, seq_len, self.d_model)
|
35 |
-
return self.wo(context)
|
36 |
-
|
37 |
-
|
38 |
-
class EnhancedFeedForward(nn.Module):
|
39 |
-
def __init__(self, d_model, ff_dim, dropout=0.1):
|
40 |
-
super().__init__()
|
41 |
-
self.linear1 = nn.Linear(d_model, ff_dim)
|
42 |
-
self.dropout1 = nn.Dropout(dropout)
|
43 |
-
self.linear2 = nn.Linear(ff_dim, d_model)
|
44 |
-
self.dropout2 = nn.Dropout(dropout)
|
45 |
-
self.activation = nn.GELU()
|
46 |
-
nn.init.xavier_uniform_(self.linear1.weight)
|
47 |
-
nn.init.xavier_uniform_(self.linear2.weight)
|
48 |
-
nn.init.zeros_(self.linear1.bias)
|
49 |
-
nn.init.zeros_(self.linear2.bias)
|
50 |
-
|
51 |
-
def forward(self, x):
|
52 |
-
return self.dropout2(self.linear2(self.dropout1(self.activation(self.linear1(x)))))
|
53 |
-
|
54 |
-
|
55 |
-
class EnhancedTransformerBlock(nn.Module):
|
56 |
-
def __init__(self, d_model, num_heads, ff_dim, dropout=0.1):
|
57 |
-
super().__init__()
|
58 |
-
self.attention = FusedQKVAttention(d_model, num_heads)
|
59 |
-
self.norm1 = nn.LayerNorm(d_model, eps=1e-6)
|
60 |
-
self.dropout1 = nn.Dropout(dropout)
|
61 |
-
self.feed_forward = EnhancedFeedForward(d_model, ff_dim, dropout)
|
62 |
-
self.norm2 = nn.LayerNorm(d_model, eps=1e-6)
|
63 |
-
self.dropout2 = nn.Dropout(dropout)
|
64 |
-
|
65 |
-
def forward(self, x, attention_mask=None):
|
66 |
-
attn_input = self.norm1(x)
|
67 |
-
attn_output = self.attention(attn_input, attention_mask)
|
68 |
-
x = x + self.dropout1(attn_output)
|
69 |
-
ff_input = self.norm2(x)
|
70 |
-
ff_output = self.feed_forward(ff_input)
|
71 |
-
x = x + self.dropout2(ff_output)
|
72 |
-
return x
|
73 |
-
|
74 |
-
|
75 |
-
class Snowflake4CausalLM(nn.Module):
|
76 |
-
def __init__(self, vocab_size, max_seq_length, d_model, num_heads, num_layers, ff_dim, dropout=0.1):
|
77 |
-
super().__init__()
|
78 |
-
self.embedding = nn.Embedding(vocab_size, d_model)
|
79 |
-
self.pos_encoding = nn.Parameter(torch.zeros(1, max_seq_length, d_model))
|
80 |
-
position = torch.arange(max_seq_length).unsqueeze(1).float()
|
81 |
-
div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
|
82 |
-
pos_enc = torch.zeros(1, max_seq_length, d_model)
|
83 |
-
pos_enc[0, :, 0::2] = torch.sin(position * div_term)
|
84 |
-
pos_enc[0, :, 1::2] = torch.cos(position * div_term)
|
85 |
-
self.pos_encoding.data = pos_enc.data
|
86 |
-
self.layers = nn.ModuleList([
|
87 |
-
EnhancedTransformerBlock(d_model, num_heads, ff_dim, dropout)
|
88 |
-
for _ in range(num_layers)
|
89 |
-
])
|
90 |
-
self.final_norm = nn.LayerNorm(d_model, eps=1e-6)
|
91 |
-
self.dropout = nn.Dropout(dropout)
|
92 |
-
self.fc_out = nn.Linear(d_model, vocab_size)
|
93 |
-
self.fc_out.weight = self.embedding.weight
|
94 |
-
nn.init.normal_(self.embedding.weight, mean=0, std=0.02)
|
95 |
-
|
96 |
-
def forward(self, input_ids, attention_mask=None):
|
97 |
-
seq_length = input_ids.size(1)
|
98 |
-
x = self.embedding(input_ids) + self.pos_encoding[:, :seq_length, :]
|
99 |
-
x = self.dropout(x)
|
100 |
-
for layer in self.layers:
|
101 |
-
x = layer(x, attention_mask)
|
102 |
-
x = self.final_norm(x)
|
103 |
-
return self.fc_out(x)
|
104 |
-
|
105 |
-
|
106 |
-
# --- Load Model and Tokenizer ---
|
107 |
-
MODEL_PATH = "model.safetensors"
|
108 |
-
CONFIG_PATH = "config.json"
|
109 |
-
TOKENIZER_PATH = "tokenizer"
|
110 |
-
|
111 |
-
# Load configuration
|
112 |
-
config = AutoConfig.from_pretrained(CONFIG_PATH)
|
113 |
|
114 |
# Load tokenizer
|
115 |
-
tokenizer =
|
116 |
|
117 |
-
#
|
118 |
-
model =
|
119 |
-
|
120 |
-
|
121 |
-
d_model=config.hidden_size,
|
122 |
-
num_heads=config.num_attention_heads,
|
123 |
-
num_layers=config.num_hidden_layers,
|
124 |
-
ff_dim=config.intermediate_size,
|
125 |
-
dropout=0.1
|
126 |
)
|
127 |
-
|
128 |
-
# Load the model weights from safetensors
|
129 |
-
state_dict = load_model(MODEL_PATH)
|
130 |
-
model.load_state_dict(state_dict)
|
131 |
model.eval()
|
132 |
model.to("cuda" if torch.cuda.is_available() else "cpu")
|
133 |
|
134 |
-
|
135 |
# --- Inference Function ---
|
136 |
def generate_text(prompt, max_length=50):
|
|
|
|
|
|
|
|
|
137 |
inputs = tokenizer(prompt, return_tensors="pt", truncation=True, padding=True, max_length=384)
|
138 |
input_ids = inputs["input_ids"].to(model.device)
|
139 |
attention_mask = inputs["attention_mask"].to(model.device)
|
140 |
|
|
|
141 |
with torch.no_grad():
|
142 |
-
outputs = model(
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
|
|
|
|
|
|
|
|
147 |
return generated_text
|
148 |
|
149 |
-
|
150 |
# --- Gradio Interface ---
|
151 |
with gr.Blocks() as demo:
|
152 |
gr.Markdown("# Snowflake-G0-stable Language Model")
|
@@ -163,4 +55,5 @@ with gr.Blocks() as demo:
|
|
163 |
|
164 |
submit_button.click(on_submit, inputs=input_prompt, outputs=output_text)
|
165 |
|
|
|
166 |
demo.launch()
|
|
|
1 |
import gradio as gr
|
2 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
|
|
3 |
import torch
|
|
|
|
|
4 |
|
5 |
+
# --- Load Model and Tokenizer from Hugging Face Hub ---
|
6 |
+
MODEL_NAME = "FlameF0X/Snowflake-G0-stable"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
7 |
|
8 |
# Load tokenizer
|
9 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
10 |
|
11 |
+
# Load model
|
12 |
+
model = AutoModelForCausalLM.from_pretrained(
|
13 |
+
MODEL_NAME,
|
14 |
+
torch_dtype=torch.float16 # Use half precision for memory efficiency
|
|
|
|
|
|
|
|
|
|
|
15 |
)
|
|
|
|
|
|
|
|
|
16 |
model.eval()
|
17 |
model.to("cuda" if torch.cuda.is_available() else "cpu")
|
18 |
|
|
|
19 |
# --- Inference Function ---
|
20 |
def generate_text(prompt, max_length=50):
|
21 |
+
"""
|
22 |
+
Generate text based on the input prompt using the trained model.
|
23 |
+
"""
|
24 |
+
# Tokenize the input prompt
|
25 |
inputs = tokenizer(prompt, return_tensors="pt", truncation=True, padding=True, max_length=384)
|
26 |
input_ids = inputs["input_ids"].to(model.device)
|
27 |
attention_mask = inputs["attention_mask"].to(model.device)
|
28 |
|
29 |
+
# Generate output tokens
|
30 |
with torch.no_grad():
|
31 |
+
outputs = model.generate(
|
32 |
+
input_ids=input_ids,
|
33 |
+
attention_mask=attention_mask,
|
34 |
+
max_length=max_length,
|
35 |
+
pad_token_id=tokenizer.eos_token_id # Use EOS token for padding
|
36 |
+
)
|
37 |
+
|
38 |
+
# Decode the generated tokens
|
39 |
+
generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
40 |
return generated_text
|
41 |
|
|
|
42 |
# --- Gradio Interface ---
|
43 |
with gr.Blocks() as demo:
|
44 |
gr.Markdown("# Snowflake-G0-stable Language Model")
|
|
|
55 |
|
56 |
submit_button.click(on_submit, inputs=input_prompt, outputs=output_text)
|
57 |
|
58 |
+
# Launch the app
|
59 |
demo.launch()
|