jatingocodeo commited on
Commit
25c11ba
·
verified ·
1 Parent(s): fea4095

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -110
app.py CHANGED
@@ -1,94 +1,85 @@
1
- import os
2
  import torch
3
  import gradio as gr
4
- from train_optimized import GPT, GPTConfig
5
- from huggingface_hub import hf_hub_download
6
- import json
7
 
8
  # Cache for model and tokenizer
9
  MODEL = None
10
- CHARS = None
11
- STOI = None
12
- ITOS = None
13
 
14
  def initialize():
15
- global MODEL, CHARS, STOI, ITOS
16
 
17
  if MODEL is None:
18
  print("Loading model and tokenizer...")
19
- # Download model files from HF Hub
20
- config_path = hf_hub_download(repo_id="jatingocodeo/shakespeare-decoder", filename="config.json")
21
- model_path = hf_hub_download(repo_id="jatingocodeo/shakespeare-decoder", filename="pytorch_model.bin")
22
 
23
- # Load config
24
- with open(config_path, 'r') as f:
25
- config_dict = json.load(f)
26
-
27
- # Initialize model with config
28
- config = GPTConfig(
29
- vocab_size=config_dict['vocab_size'],
30
- n_layer=config_dict['n_layer'],
31
- n_head=config_dict['n_head'],
32
- n_embd=config_dict['n_embd'],
33
- block_size=config_dict['block_size'],
34
- dropout=config_dict['dropout'],
35
- bias=config_dict['bias']
36
- )
37
- model = GPT(config)
38
-
39
- # Load model weights
40
- state_dict = torch.load(model_path, map_location='cpu')
41
- model.load_state_dict(state_dict)
42
- model.eval()
43
- MODEL = model
44
-
45
- # Initialize tokenizer
46
  try:
47
- # First try to download input.txt from the repository
48
- input_path = hf_hub_download(repo_id="jatingocodeo/shakespeare-decoder", filename="input.txt")
49
- with open(input_path, 'r', encoding='utf-8') as f:
50
- text = f.read()
51
- except:
52
- print("Warning: Could not load input.txt from repository. Using default character set.")
53
- # Use a comprehensive set of characters that would be in Shakespeare's text
54
- text = """
55
- ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,!?-_:;'"()[]{}\n </>\t@#$%^&*+=~`|\\
56
- """
57
-
58
- CHARS = sorted(list(set(text)))
59
- STOI = {ch:i for i,ch in enumerate(CHARS)}
60
- ITOS = {i:ch for i,ch in enumerate(CHARS)}
61
-
62
- print(f"Model loaded successfully! Vocabulary size: {len(CHARS)} characters")
63
- print("Available characters:", ''.join(CHARS))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
 
65
- def generate_text(
66
- prompt,
67
- max_new_tokens=100,
68
- temperature=0.8,
69
- top_k=50
70
- ):
71
  # Initialize if not already done
72
  if MODEL is None:
73
  initialize()
74
 
75
- # Encode the prompt
76
- encode = lambda s: [STOI[c] for c in s]
77
- decode = lambda l: ''.join([ITOS[i] for i in l])
78
-
79
  try:
80
- # Convert prompt to tensor
81
- x = torch.tensor(encode(prompt), dtype=torch.long)[None,...]
 
 
 
 
 
 
 
 
82
 
83
  # Generate
84
  with torch.no_grad():
85
- y = MODEL.generate(x, max_new_tokens, temperature, top_k)[0]
 
 
 
 
 
 
 
 
 
86
 
87
  # Decode and return
88
- generated_text = decode(y.tolist())
89
- return generated_text
90
- except KeyError:
91
- return "Error: The prompt contains characters that are not in the training data. Please use only standard English characters."
92
  except Exception as e:
93
  return f"Error generating text: {str(e)}"
94
 
@@ -96,52 +87,27 @@ def generate_text(
96
  initialize()
97
 
98
  # Create Gradio interface
99
- demo = gr.Interface(
100
  fn=generate_text,
101
  inputs=[
102
- gr.Textbox(
103
- label="Prompt",
104
- placeholder="Enter your prompt here...",
105
- lines=5
106
- ),
107
- gr.Slider(
108
- label="Max New Tokens",
109
- minimum=10,
110
- maximum=500,
111
- value=100,
112
- step=10
113
- ),
114
- gr.Slider(
115
- label="Temperature",
116
- minimum=0.1,
117
- maximum=2.0,
118
- value=0.8,
119
- step=0.1
120
- ),
121
- gr.Slider(
122
- label="Top-k",
123
- minimum=1,
124
- maximum=100,
125
- value=50,
126
- step=1
127
- ),
128
  ],
129
- outputs=gr.Textbox(label="Generated Text", lines=10),
130
- title="Shakespeare GPT",
131
- description="""
132
- This is a GPT model trained on Shakespeare's text. Enter a prompt and the model will continue it in Shakespeare's style.
133
-
134
- Parameters:
135
- - Temperature: Higher values make the output more random, lower values make it more deterministic
136
- - Top-k: Number of highest probability tokens to consider at each step
137
- - Max New Tokens: Maximum number of tokens to generate
138
- """,
139
  examples=[
140
- ["To be, or not to be,", 100, 0.8, 50],
141
- ["Friends, Romans, countrymen,", 150, 0.7, 40],
142
- ["Now is the winter of", 200, 0.9, 30],
143
- ]
 
144
  )
145
 
146
  if __name__ == "__main__":
147
- demo.launch()
 
 
1
  import torch
2
  import gradio as gr
3
+ from transformers import AutoModelForCausalLM, AutoTokenizer
 
 
4
 
5
  # Cache for model and tokenizer
6
  MODEL = None
7
+ TOKENIZER = None
 
 
8
 
9
  def initialize():
10
+ global MODEL, TOKENIZER
11
 
12
  if MODEL is None:
13
  print("Loading model and tokenizer...")
14
+ model_id = "jatingocodeo/SmolLM2"
 
 
15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  try:
17
+ # Load tokenizer
18
+ print("\n1. Loading tokenizer...")
19
+ TOKENIZER = AutoTokenizer.from_pretrained(model_id)
20
+ print("✓ Tokenizer loaded successfully")
21
+
22
+ # Add special tokens if needed
23
+ special_tokens = {
24
+ 'pad_token': '[PAD]',
25
+ 'eos_token': '</s>',
26
+ 'bos_token': '<s>'
27
+ }
28
+ num_added = TOKENIZER.add_special_tokens(special_tokens)
29
+ print(f"✓ Added {num_added} special tokens")
30
+
31
+ # Load model
32
+ print("\n2. Loading model...")
33
+ MODEL = AutoModelForCausalLM.from_pretrained(
34
+ model_id,
35
+ trust_remote_code=True,
36
+ torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
37
+ low_cpu_mem_usage=True
38
+ )
39
+
40
+ # Move model to appropriate device
41
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
42
+ MODEL = MODEL.to(device)
43
+ print(f"✓ Model loaded successfully and moved to {device}")
44
+
45
+ except Exception as e:
46
+ print(f"Error initializing model: {str(e)}")
47
+ raise
48
 
49
+ def generate_text(prompt, max_length=100, temperature=0.7, top_k=50):
 
 
 
 
 
50
  # Initialize if not already done
51
  if MODEL is None:
52
  initialize()
53
 
 
 
 
 
54
  try:
55
+ # Process prompt
56
+ if not prompt.strip():
57
+ return "Please enter a prompt."
58
+
59
+ if not prompt.startswith(TOKENIZER.bos_token):
60
+ prompt = TOKENIZER.bos_token + prompt
61
+
62
+ # Encode prompt
63
+ input_ids = TOKENIZER.encode(prompt, return_tensors="pt", truncation=True, max_length=2048)
64
+ input_ids = input_ids.to(MODEL.device)
65
 
66
  # Generate
67
  with torch.no_grad():
68
+ output_ids = MODEL.generate(
69
+ input_ids,
70
+ max_length=min(max_length + len(input_ids[0]), 2048),
71
+ temperature=temperature,
72
+ top_k=top_k,
73
+ do_sample=True,
74
+ pad_token_id=TOKENIZER.pad_token_id,
75
+ eos_token_id=TOKENIZER.eos_token_id,
76
+ num_return_sequences=1
77
+ )
78
 
79
  # Decode and return
80
+ generated_text = TOKENIZER.decode(output_ids[0], skip_special_tokens=True)
81
+ return generated_text.strip()
82
+
 
83
  except Exception as e:
84
  return f"Error generating text: {str(e)}"
85
 
 
87
  initialize()
88
 
89
  # Create Gradio interface
90
+ iface = gr.Interface(
91
  fn=generate_text,
92
  inputs=[
93
+ gr.Textbox(label="Prompt", placeholder="Enter your prompt here...", lines=2),
94
+ gr.Slider(minimum=10, maximum=200, value=100, step=1, label="Max Length"),
95
+ gr.Slider(minimum=0.1, maximum=1.0, value=0.7, step=0.1, label="Temperature"),
96
+ gr.Slider(minimum=1, maximum=100, value=50, step=1, label="Top K"),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
  ],
98
+ outputs=gr.Textbox(label="Generated Text", lines=5),
99
+ title="SmolLM2 Text Generator",
100
+ description="""Generate text using the fine-tuned SmolLM2 model.
101
+ - Max Length: Controls the length of generated text
102
+ - Temperature: Controls randomness (higher = more creative)
103
+ - Top K: Controls diversity of word choices""",
 
 
 
 
104
  examples=[
105
+ ["Once upon a time", 100, 0.7, 50],
106
+ ["The quick brown fox", 150, 0.8, 40],
107
+ ["In a galaxy far far away", 200, 0.9, 30],
108
+ ],
109
+ allow_flagging="never"
110
  )
111
 
112
  if __name__ == "__main__":
113
+ iface.launch()