Spaces:
Sleeping
Sleeping
File size: 11,653 Bytes
8371eb2 dba4dcb 8371eb2 dba4dcb 8371eb2 dba4dcb 8371eb2 dba4dcb 8371eb2 aad72ac 8371eb2 328c65b 8371eb2 dba4dcb 8371eb2 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 |
"""
HuggingFace Space: AST Training Dashboard
Live monitoring and model card generation
"""
import gradio as gr
import json
import time
from pathlib import Path
import plotly.graph_objects as go
from plotly.subplots import make_subplots
try:
from adaptive_sparse_training import AdaptiveSparseTrainer, ASTConfig
import torch
import torchvision
import timm
HAS_DEPS = True
except ImportError:
HAS_DEPS = False
class ASTDashboard:
"""Real-time AST training dashboard"""
def __init__(self):
self.active_training = None
self.training_history = []
def start_training(
self,
model_name: str,
dataset: str,
activation_rate: float,
epochs: int,
progress=gr.Progress()
):
"""Start AST training with live updates"""
if not HAS_DEPS:
return "β Dependencies not installed", None, None
progress(0, desc="Initializing...")
# Load dataset (CIFAR-10 for demo)
train_loader, val_loader = self._get_dataloaders(dataset)
# Create model
progress(0.1, desc="Creating model...")
if model_name == "resnet18":
model = torchvision.models.resnet18(num_classes=10)
else:
model = timm.create_model(model_name, pretrained=False, num_classes=10)
# AST Config (CPU mode for HuggingFace free tier)
config = ASTConfig(
target_activation_rate=activation_rate,
use_amp=False, # Disable AMP on CPU
device='cpu'
)
# Start training
progress(0.2, desc="Starting training...")
model = model.to('cpu')
trainer = AdaptiveSparseTrainer(model, train_loader, val_loader, config)
self.training_history = []
for epoch in range(epochs):
progress((epoch + 1) / epochs, desc=f"Epoch {epoch+1}/{epochs}")
# Train one epoch
epoch_stats = trainer.train_epoch(epoch)
val_acc = trainer.evaluate()
# Store history
self.training_history.append({
"epoch": epoch + 1,
"val_acc": val_acc,
"activation_rate": epoch_stats.get("activation_rate", activation_rate),
"threshold": epoch_stats.get("threshold", 1.0),
})
# Update dashboard
if (epoch + 1) % 5 == 0 or epoch == epochs - 1:
status = self._format_status(epoch + 1, epochs, val_acc, activation_rate)
plot = self._create_plot()
yield status, plot, None
# Generate model card
model_card = self._generate_model_card(model_name, activation_rate)
final_status = f"β
Training complete! Best accuracy: {max([h['val_acc'] for h in self.training_history]):.2%}"
yield final_status, self._create_plot(), model_card
def _get_dataloaders(self, dataset: str):
"""Get data loaders (CIFAR-10 demo)"""
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
train_dataset = torchvision.datasets.CIFAR10(
root='./data', train=True, download=True, transform=transform
)
val_dataset = torchvision.datasets.CIFAR10(
root='./data', train=False, download=True, transform=transform
)
train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True, num_workers=0)
val_loader = DataLoader(val_dataset, batch_size=64, shuffle=False, num_workers=0)
return train_loader, val_loader
def _format_status(self, epoch: int, total_epochs: int, accuracy: float, activation_rate: float):
"""Format training status"""
return f"""
### π Training in Progress
**Epoch:** {epoch}/{total_epochs}
**Accuracy:** {accuracy:.2%}
**Activation Rate:** {activation_rate:.1%}
**Energy Savings:** ~{(1-activation_rate)*100:.0f}%
*Updating every 5 epochs...*
"""
def _create_plot(self):
"""Create live training plot"""
if not self.training_history:
return None
fig = make_subplots(
rows=2, cols=2,
subplot_titles=("Validation Accuracy", "Activation Rate", "Threshold Evolution", "Energy Savings"),
)
epochs = [h["epoch"] for h in self.training_history]
accuracies = [h["val_acc"] * 100 for h in self.training_history]
activation_rates = [h["activation_rate"] * 100 for h in self.training_history]
thresholds = [h["threshold"] for h in self.training_history]
savings = [(1 - h["activation_rate"]) * 100 for h in self.training_history]
# Accuracy plot
fig.add_trace(
go.Scatter(x=epochs, y=accuracies, mode='lines+markers', name='Val Accuracy',
line=dict(color='#3498db', width=3)),
row=1, col=1
)
# Activation rate plot
fig.add_trace(
go.Scatter(x=epochs, y=activation_rates, mode='lines+markers', name='Activation Rate',
line=dict(color='#e74c3c', width=3)),
row=1, col=2
)
# Threshold plot
fig.add_trace(
go.Scatter(x=epochs, y=thresholds, mode='lines+markers', name='Threshold',
line=dict(color='#f39c12', width=3)),
row=2, col=1
)
# Energy savings plot
fig.add_trace(
go.Scatter(x=epochs, y=savings, mode='lines+markers', name='Energy Savings',
line=dict(color='#27ae60', width=3), fill='tozeroy'),
row=2, col=2
)
fig.update_xaxes(title_text="Epoch")
fig.update_yaxes(title_text="Accuracy (%)", row=1, col=1)
fig.update_yaxes(title_text="Activation (%)", row=1, col=2)
fig.update_yaxes(title_text="Threshold", row=2, col=1)
fig.update_yaxes(title_text="Savings (%)", row=2, col=2)
fig.update_layout(height=600, showlegend=False)
return fig
def _generate_model_card(self, model_name: str, activation_rate: float):
"""Generate HuggingFace model card"""
best_acc = max([h["val_acc"] for h in self.training_history])
energy_savings = (1 - activation_rate) * 100
return f"""---
tags:
- adaptive-sparse-training
- energy-efficient
- sustainability
metrics:
- accuracy
- energy_savings
---
# {model_name} (AST-Trained)
**Trained with {energy_savings:.0f}% less energy than standard training** β‘
## Model Details
- **Architecture:** {model_name}
- **Dataset:** CIFAR-10
- **Training Method:** Adaptive Sparse Training (AST)
- **Target Activation Rate:** {activation_rate:.0%}
## Performance
- **Accuracy:** {best_acc:.2%}
- **Energy Savings:** {energy_savings:.0f}%
- **Training Epochs:** {len(self.training_history)}
## Sustainability Report
This model was trained using Adaptive Sparse Training, which dynamically selects
the most important training samples. This resulted in:
- β‘ **{energy_savings:.0f}% energy savings** compared to standard training
- π **Lower carbon footprint**
- β±οΈ **Faster training time**
- π― **Maintained accuracy** (minimal degradation)
## How to Use
```python
import torch
from torchvision import models
# Load model
model = models.{model_name}(num_classes=10)
model.load_state_dict(torch.load("pytorch_model.bin"))
model.eval()
# Inference
# ... (your inference code)
```
## Training Details
**AST Configuration:**
- Target Activation Rate: {activation_rate:.0%}
- Adaptive PI Controller: Enabled
- Mixed Precision (AMP): Enabled
## Reproducing This Model
```bash
pip install adaptive-sparse-training
python -c "
from adaptive_sparse_training import AdaptiveSparseTrainer, ASTConfig
config = ASTConfig(target_activation_rate={activation_rate})
# ... (full training code)
"
```
## Citation
If you use this model or AST, please cite:
```bibtex
@software{{adaptive_sparse_training,
title={{Adaptive Sparse Training}},
author={{Idiakhoa, Oluwafemi}},
year={{2024}},
url={{https://github.com/oluwafemidiakhoa/adaptive-sparse-training}}
}}
```
## Acknowledgments
Trained using the `adaptive-sparse-training` package. Special thanks to the PyTorch and HuggingFace communities.
---
*This model card was auto-generated by the AST Training Dashboard.*
"""
# Initialize dashboard
dashboard = ASTDashboard()
# Gradio Interface
def create_demo():
"""Create Gradio demo interface"""
with gr.Blocks(title="AST Training Dashboard") as demo:
gr.Markdown("""
# β‘ Adaptive Sparse Training Dashboard
Train models with **60-70% less energy** while maintaining accuracy!
This demo trains a model on CIFAR-10 using AST and generates a HuggingFace model card.
""")
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### βοΈ Configuration")
model_name = gr.Dropdown(
choices=["resnet18", "efficientnet_b0", "mobilenetv3_small_100"],
value="resnet18",
label="Model Architecture"
)
dataset = gr.Dropdown(
choices=["cifar10"],
value="cifar10",
label="Dataset"
)
activation_rate = gr.Slider(
minimum=0.2,
maximum=0.8,
value=0.35,
step=0.05,
label="Target Activation Rate (lower = more savings)"
)
gr.Markdown(f"**Energy Savings:** ~{(1-0.35)*100:.0f}%")
epochs = gr.Slider(
minimum=5,
maximum=50,
value=10,
step=5,
label="Training Epochs"
)
train_btn = gr.Button("π Start Training", variant="primary", size="lg")
with gr.Column(scale=2):
gr.Markdown("### π Live Training Metrics")
status = gr.Markdown("*Ready to train...*")
plot = gr.Plot()
with gr.Row():
with gr.Column():
gr.Markdown("### π Generated Model Card")
model_card = gr.Textbox(
label="HuggingFace Model Card (Markdown)",
lines=20,
max_lines=30,
)
gr.Markdown("""
**Next Steps:**
1. Copy the model card above
2. Create a new model on [HuggingFace Hub](https://huggingface.co/new)
3. Paste the model card into `README.md`
4. Upload your trained model weights
""")
# Training logic
train_btn.click(
fn=dashboard.start_training,
inputs=[model_name, dataset, activation_rate, epochs],
outputs=[status, plot, model_card],
)
gr.Markdown("""
---
## π Learn More
- π¦ [PyPI Package](https://pypi.org/project/adaptive-sparse-training/)
- π [GitHub Repo](https://github.com/oluwafemidiakhoa/adaptive-sparse-training)
- π [Documentation](https://github.com/oluwafemidiakhoa/adaptive-sparse-training#readme)
**Made with β€οΈ using Adaptive Sparse Training**
""")
return demo
if __name__ == "__main__":
demo = create_demo()
demo.launch()
|