FlameF0X commited on
Commit
553a5e7
·
verified ·
1 Parent(s): 63fe5cf

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +215 -0
app.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ from transformers import (
4
+ GPT2Config,
5
+ GPT2LMHeadModel,
6
+ GPT2Tokenizer,
7
+ Trainer,
8
+ TrainingArguments,
9
+ DataCollatorForLanguageModeling
10
+ )
11
+ from datasets import load_dataset
12
+ from huggingface_hub import whoami
13
+ import os
14
+
15
+ # --- Helper Functions ---
16
+
17
+ def get_user_info(token):
18
+ """Retrieves the username from the HF token."""
19
+ if not token:
20
+ return None
21
+ try:
22
+ info = whoami(token=token)
23
+ return info['name']
24
+ except Exception:
25
+ return None
26
+
27
+ def train_and_push(
28
+ dataset_id,
29
+ model_name,
30
+ num_layers,
31
+ n_embd,
32
+ epochs,
33
+ lr,
34
+ sample_limit,
35
+ oauth_token: gr.OAuthToken
36
+ ):
37
+ """
38
+ Main Logic:
39
+ 1. Authenticate
40
+ 2. Load & Prepare Data
41
+ 3. Initialize Tiny Model
42
+ 4. Train
43
+ 5. Push to Hub
44
+ """
45
+
46
+ # 1. Authentication Check
47
+ if oauth_token is None or oauth_token.token is None:
48
+ raise gr.Error("You must be logged in to train a model!")
49
+
50
+ token = oauth_token.token
51
+ username = get_user_info(token)
52
+
53
+ if not username:
54
+ raise gr.Error("Could not retrieve user info. Please try logging in again.")
55
+
56
+ full_repo_id = f"{username}/{model_name}"
57
+
58
+ progress = gr.Progress()
59
+
60
+ try:
61
+ # 2. Load Dataset
62
+ progress(0.1, desc=f"Loading dataset: {dataset_id}...")
63
+
64
+ # We try to load the dataset. We'll default to the 'train' split.
65
+ # We only take a small slice to keep it fast for this demo.
66
+ try:
67
+ # Try loading just the first 'sample_limit' rows to save bandwidth/memory
68
+ dataset = load_dataset(dataset_id, split=f"train[:{int(sample_limit)}]")
69
+ except Exception as e:
70
+ raise gr.Error(f"Error loading dataset: {str(e)}. Make sure it exists and has a 'train' split.")
71
+
72
+ # Heuristic: Find the text column (first string column)
73
+ text_column = "text"
74
+ if "text" not in dataset.column_names:
75
+ # simple fallback: look for the first string column
76
+ for col, dtype in zip(dataset.column_names, dataset.features.values()):
77
+ if hasattr(dtype, 'dtype') and dtype.dtype == 'string':
78
+ text_column = col
79
+ break
80
+
81
+ if text_column not in dataset.column_names:
82
+ raise gr.Error("Could not find a text column in this dataset. Please use a dataset with a 'text' column.")
83
+
84
+ progress(0.2, desc="Tokenizing data...")
85
+
86
+ # We use the standard GPT-2 tokenizer for convenience
87
+ tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
88
+ tokenizer.pad_token = tokenizer.eos_token
89
+
90
+ def tokenize_function(examples):
91
+ return tokenizer(examples[text_column], padding="max_length", truncation=True, max_length=128)
92
+
93
+ tokenized_datasets = dataset.map(tokenize_function, batched=True)
94
+
95
+ # 3. Initialize Model
96
+ progress(0.3, desc="Initializing Nano Model...")
97
+
98
+ # We create a custom configuration based on user inputs (Constrained for speed)
99
+ config = GPT2Config(
100
+ vocab_size=len(tokenizer),
101
+ n_positions=128, # Short context window for speed
102
+ n_ctx=128,
103
+ n_embd=int(n_embd), # Small embedding size
104
+ n_layer=int(num_layers), # Few layers
105
+ n_head=4,
106
+ )
107
+
108
+ model = GPT2LMHeadModel(config)
109
+
110
+ # 4. Training
111
+ progress(0.4, desc="Starting Training (this might take a minute)...")
112
+
113
+ training_args = TrainingArguments(
114
+ output_dir="./results",
115
+ overwrite_output_dir=True,
116
+ num_train_epochs=epochs,
117
+ per_device_train_batch_size=8,
118
+ save_steps=500,
119
+ save_total_limit=1,
120
+ prediction_loss_only=True,
121
+ learning_rate=lr,
122
+ logging_steps=10,
123
+ report_to="none", # Don't log to wandb/tensorboard
124
+ use_cpu=not torch.cuda.is_available(), # Force CPU if no GPU available
125
+ )
126
+
127
+ data_collator = DataCollatorForLanguageModeling(
128
+ tokenizer=tokenizer, mlm=False
129
+ )
130
+
131
+ trainer = Trainer(
132
+ model=model,
133
+ args=training_args,
134
+ data_collator=data_collator,
135
+ train_dataset=tokenized_datasets,
136
+ )
137
+
138
+ trainer.train()
139
+
140
+ # 5. Push to Hub
141
+ progress(0.9, desc=f"Pushing to {full_repo_id}...")
142
+
143
+ # We push both model and tokenizer
144
+ model.push_to_hub(full_repo_id, token=token, private=True) # Default to private for safety
145
+ tokenizer.push_to_hub(full_repo_id, token=token, private=True)
146
+
147
+ return f"🎉 Success! Model trained and pushed to: https://huggingface.co/{full_repo_id}"
148
+
149
+ except Exception as e:
150
+ raise gr.Error(f"An error occurred: {str(e)}")
151
+
152
+ # --- UI Layout ---
153
+
154
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
155
+ gr.Markdown(
156
+ """
157
+ # 🚂 Tiny AutoTrain Space
158
+ Login with your Hugging Face account, pick a dataset, and train a tiny language model from scratch!
159
+ The model will be automatically uploaded to your profile.
160
+ """
161
+ )
162
+
163
+ # Login Button (Native HF Integration)
164
+ with gr.Row():
165
+ login_btn = gr.LoginButton(value="Sign in with Hugging Face to Train")
166
+
167
+ with gr.Row():
168
+ with gr.Column():
169
+ gr.Markdown("### 1. Data Configuration")
170
+ dataset_input = gr.Textbox(
171
+ label="Dataset Name (from Hub)",
172
+ value="roneneldan/TinyStories",
173
+ placeholder="e.g. wikitext, roneneldan/TinyStories"
174
+ )
175
+ sample_limit = gr.Slider(
176
+ minimum=100, maximum=5000, value=500, step=100,
177
+ label="Training Sample Size (Keep small for speed)"
178
+ )
179
+
180
+ with gr.Column():
181
+ gr.Markdown("### 2. Model Hyperparameters")
182
+ model_name_input = gr.Textbox(
183
+ label="New Model Name",
184
+ value="my-tiny-model",
185
+ placeholder="Name of the repo to create"
186
+ )
187
+
188
+ with gr.Row():
189
+ layers = gr.Slider(minimum=1, maximum=6, value=2, step=1, label="Layers (Depth)")
190
+ embd = gr.Slider(minimum=32, maximum=256, value=64, step=32, label="Embedding Size (Width)")
191
+
192
+ with gr.Row():
193
+ epochs = gr.Slider(minimum=1, maximum=5, value=1, step=1, label="Epochs")
194
+ lr = gr.Number(label="Learning Rate", value=5e-4)
195
+
196
+ train_btn = gr.Button("🚀 Train & Publish", variant="primary")
197
+ output_text = gr.Textbox(label="Status", interactive=False)
198
+
199
+ # Wire up the button
200
+ train_btn.click(
201
+ fn=train_and_push,
202
+ inputs=[
203
+ dataset_input,
204
+ model_name_input,
205
+ layers,
206
+ embd,
207
+ epochs,
208
+ lr,
209
+ sample_limit
210
+ ],
211
+ outputs=output_text
212
+ )
213
+
214
+ if __name__ == "__main__":
215
+ demo.launch()