FlameF0X commited on
Commit
63a7f6a
·
verified ·
1 Parent(s): ce4ff83

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +109 -15
app.py CHANGED
@@ -1,13 +1,112 @@
1
  import gradio as gr
2
  from transformers import PreTrainedTokenizerFast, AutoConfig
3
- from safetensors.torch import load_model # Import load_model for safetensors
4
  import torch
5
- from EnhancedTransformerModel import EnhancedTransformerModel # Custom model class
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
  # --- Load Model and Tokenizer ---
8
- MODEL_PATH = "model.safetensors" # Path to the safetensors model file
9
- CONFIG_PATH = "config.json" # Path to the model configuration
10
- TOKENIZER_PATH = "tokenizer" # Path to the tokenizer directory
11
 
12
  # Load configuration
13
  config = AutoConfig.from_pretrained(CONFIG_PATH)
@@ -16,7 +115,7 @@ config = AutoConfig.from_pretrained(CONFIG_PATH)
16
  tokenizer = PreTrainedTokenizerFast.from_pretrained(TOKENIZER_PATH)
17
 
18
  # Initialize the custom model
19
- model = EnhancedTransformerModel(
20
  vocab_size=config.vocab_size,
21
  max_seq_length=config.max_position_embeddings,
22
  d_model=config.hidden_size,
@@ -32,26 +131,22 @@ model.load_state_dict(state_dict)
32
  model.eval()
33
  model.to("cuda" if torch.cuda.is_available() else "cpu")
34
 
 
35
  # --- Inference Function ---
36
  def generate_text(prompt, max_length=50):
37
- """
38
- Generate text based on the input prompt using the trained model.
39
- """
40
- # Tokenize the input prompt
41
  inputs = tokenizer(prompt, return_tensors="pt", truncation=True, padding=True, max_length=384)
42
  input_ids = inputs["input_ids"].to(model.device)
43
  attention_mask = inputs["attention_mask"].to(model.device)
44
 
45
- # Generate output tokens
46
  with torch.no_grad():
47
  outputs = model(input_ids, attention_mask)
48
- logits = outputs[:, -1, :] # Get the logits for the last token
49
- next_token = torch.argmax(logits, dim=-1) # Greedy decoding
50
 
51
- # Decode the generated token
52
  generated_text = tokenizer.decode(next_token, skip_special_tokens=True)
53
  return generated_text
54
 
 
55
  # --- Gradio Interface ---
56
  with gr.Blocks() as demo:
57
  gr.Markdown("# Snowflake-G0-stable Language Model")
@@ -68,5 +163,4 @@ with gr.Blocks() as demo:
68
 
69
  submit_button.click(on_submit, inputs=input_prompt, outputs=output_text)
70
 
71
- # Launch the app
72
  demo.launch()
 
1
  import gradio as gr
2
  from transformers import PreTrainedTokenizerFast, AutoConfig
3
+ from safetensors.torch import load_model
4
  import torch
5
+ import math
6
+ import torch.nn as nn
7
+
8
+
9
+ # --- Define Snowflake4CausalLM ---
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)
 
115
  tokenizer = PreTrainedTokenizerFast.from_pretrained(TOKENIZER_PATH)
116
 
117
  # Initialize the custom model
118
+ model = Snowflake4CausalLM(
119
  vocab_size=config.vocab_size,
120
  max_seq_length=config.max_position_embeddings,
121
  d_model=config.hidden_size,
 
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(input_ids, attention_mask)
143
+ logits = outputs[:, -1, :]
144
+ next_token = torch.argmax(logits, dim=-1)
145
 
 
146
  generated_text = tokenizer.decode(next_token, skip_special_tokens=True)
147
  return generated_text
148
 
149
+
150
  # --- Gradio Interface ---
151
  with gr.Blocks() as demo:
152
  gr.Markdown("# Snowflake-G0-stable Language Model")
 
163
 
164
  submit_button.click(on_submit, inputs=input_prompt, outputs=output_text)
165
 
 
166
  demo.launch()