itriedcoding commited on
Commit
9f23f3f
·
verified ·
1 Parent(s): f62675d

Upload folder using huggingface_hub

Browse files
Files changed (3) hide show
  1. pytorch_model_state.bin +3 -0
  2. space_app.py +94 -0
  3. tokenizer.pkl +0 -0
pytorch_model_state.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c14f5af790583eeb531a1368f37869324ef11a8b6be307bf10db08c3834d9409
3
+ size 12804223
space_app.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ import torch.nn as nn
4
+ import math
5
+ import pickle
6
+ import json
7
+ from huggingface_hub import hf_hub_download
8
+
9
+ REPO_ID = "itriedcoding/Sage"
10
+
11
+ # Custom model class matching Sage architecture
12
+ class TransformerLM(nn.Module):
13
+ def __init__(self, vocab_size, d_model=256, nhead=8, num_layers=4, dim_feedforward=1024, max_seq_length=64):
14
+ super().__init__()
15
+ self.embedding = nn.Embedding(vocab_size, d_model)
16
+ self.pos_embedding = nn.Embedding(max_seq_length, d_model)
17
+ encoder_layer = nn.TransformerEncoderLayer(d_model=d_model, nhead=nhead, dim_feedforward=dim_feedforward, batch_first=True, dropout=0.1)
18
+ self.transformer_encoder = nn.TransformerEncoder(encoder_layer, num_layers=num_layers)
19
+ self.output_layer = nn.Linear(d_model, vocab_size)
20
+ self.max_seq_length = max_seq_length
21
+ self.vocab_size = vocab_size
22
+
23
+ def forward(self, src):
24
+ seq_len = src.size(1)
25
+ pos = torch.arange(0, seq_len, device=src.device).unsqueeze(0)
26
+ src_emb = self.embedding(src) * math.sqrt(self.embedding.embedding_dim)
27
+ pos_emb = self.pos_embedding(pos)
28
+ src_emb = src_emb + pos_emb
29
+ output = self.transformer_encoder(src_emb)
30
+ logits = self.output_layer(output)
31
+ return logits
32
+
33
+ # Download model files from Hugging Face
34
+ print("Downloading model files...")
35
+ config_path = hf_hub_download(repo_id=REPO_ID, filename="config.json")
36
+ state_path = hf_hub_download(repo_id=REPO_ID, filename="pytorch_model_state.bin")
37
+ tok_path = hf_hub_download(repo_id=REPO_ID, filename="tokenizer.pkl")
38
+
39
+ # Load config
40
+ with open(config_path) as f:
41
+ config = json.load(f)
42
+
43
+ # Load tokenizer
44
+ with open(tok_path, 'rb') as f:
45
+ tokenizer = pickle.load(f)
46
+
47
+ # Load model
48
+ model = TransformerLM(
49
+ vocab_size=config['vocab_size'],
50
+ d_model=config['hidden_size'],
51
+ nhead=config['num_attention_heads'],
52
+ num_layers=config['num_hidden_layers'],
53
+ dim_feedforward=config['intermediate_size'],
54
+ max_seq_length=config['max_position_embeddings']
55
+ )
56
+ state_dict = torch.load(state_path, map_location='cpu', weights_only=True)
57
+ model.load_state_dict(state_dict, strict=False)
58
+ model.eval()
59
+
60
+ def generate_text(prompt, max_length, temperature):
61
+ input_ids = tokenizer.encode(prompt, max_length=32, padding=False, truncation=False, return_tensors='pt')
62
+ generated = input_ids.clone()
63
+
64
+ with torch.no_grad():
65
+ for _ in range(int(max_length)):
66
+ logits = model(generated)
67
+ next_logits = logits[0, -1, :] / temperature
68
+ probs = torch.softmax(next_logits, dim=-1)
69
+ next_token = torch.multinomial(probs, num_samples=1)
70
+ generated = torch.cat([generated, next_token.unsqueeze(0)], dim=1)
71
+ if next_token.item() == tokenizer.char_to_idx.get('.', 0):
72
+ break
73
+
74
+ return tokenizer.decode(generated[0])
75
+
76
+ demo = gr.Interface(
77
+ fn=generate_text,
78
+ inputs=[
79
+ gr.Textbox(label="Prompt", value="Hello", placeholder="Enter your prompt here"),
80
+ gr.Slider(minimum=10, maximum=100, value=30, step=1, label="Max Length"),
81
+ gr.Slider(minimum=0.1, maximum=2.0, value=0.8, step=0.1, label="Temperature")
82
+ ],
83
+ outputs=gr.Textbox(label="Generated Text"),
84
+ title="Sage Text Generator",
85
+ description="Custom character-level language model built from scratch with PyTorch.",
86
+ examples=[
87
+ ["Hello", 30, 0.8],
88
+ ["The weather", 30, 0.8],
89
+ ["Deep learning", 30, 0.8]
90
+ ]
91
+ )
92
+
93
+ if __name__ == "__main__":
94
+ demo.launch()
tokenizer.pkl ADDED
Binary file (547 Bytes). View file