Spaces:
Running
on
Zero
Running
on
Zero
File size: 13,825 Bytes
454ecdd 6f1e643 454ecdd 566001b 454ecdd 566001b 6f1e643 454ecdd 6f1e643 454ecdd 6f1e643 454ecdd 566001b 454ecdd 6f1e643 454ecdd 566001b bb030c8 566001b bb030c8 566001b bb030c8 566001b 454ecdd 6f1e643 454ecdd 566001b 454ecdd 566001b 454ecdd 6f1e643 454ecdd 566001b 454ecdd 6f1e643 454ecdd 6f1e643 454ecdd 6f1e643 3945483 6f1e643 3ecafdf 6f1e643 454ecdd 6f1e643 454ecdd 6f1e643 3ecafdf 6f1e643 3ecafdf 6f1e643 454ecdd 6f1e643 454ecdd 6f1e643 3ecafdf 6f1e643 454ecdd 3945483 6f1e643 454ecdd 6f1e643 454ecdd 6f1e643 454ecdd 6f1e643 454ecdd 6f1e643 454ecdd 6f1e643 454ecdd 6f1e643 454ecdd 6f1e643 454ecdd 6f1e643 454ecdd 6f1e643 454ecdd 6f1e643 454ecdd 6f1e643 454ecdd 6f1e643 454ecdd 6f1e643 454ecdd 6f1e643 454ecdd 4cbf142 6f1e643 566001b 6f1e643 566001b 454ecdd 6f1e643 454ecdd 6f1e643 454ecdd 6f1e643 454ecdd |
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 |
#!/usr/bin/env python3
"""MANIFOLD Training Interface for Hugging Face Spaces with ZeroGPU."""
import gradio as gr
import torch
import numpy as np
import json
import time
import uuid
from pathlib import Path
from datetime import datetime
import spaces
import sys
sys.path.insert(0, str(Path(__file__).parent / "src"))
from manifold import MANIFOLDLite
from manifold.config import ModelConfig, TrainingConfig
from manifold.data.generator import SyntheticDataGenerator
from manifold.data.dataset import MANIFOLDDataset, create_dataloader
from manifold.training.trainer import train_epoch, validate
from manifold.training.curriculum import CurriculumScheduler
from manifold.training.losses import compute_total_loss
current_model = None
DATASET_REPO = "LimmeDev/manifold-synthetic-data"
def get_device_info():
if torch.cuda.is_available():
return f"GPU: {torch.cuda.get_device_name(0)} ({torch.cuda.get_device_properties(0).total_memory / 1e9:.1f} GB)"
return "CPU (GPU will be allocated when training starts)"
def contribute_to_dataset(features, labels, num_legit, num_cheaters, seed):
try:
from huggingface_hub import HfApi
import tempfile
import os
hf_token = os.environ.get("HF_TOKEN")
if not hf_token:
return False, "HF_TOKEN not configured"
api = HfApi(token=hf_token)
contribution_id = f"{datetime.now().strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:8]}"
with tempfile.TemporaryDirectory() as tmpdir:
features_path = os.path.join(tmpdir, f"features_{contribution_id}.npy")
labels_path = os.path.join(tmpdir, f"labels_{contribution_id}.npy")
meta_path = os.path.join(tmpdir, f"meta_{contribution_id}.json")
np.save(features_path, features)
np.save(labels_path, labels)
metadata = {
"contribution_id": contribution_id,
"timestamp": datetime.now().isoformat(),
"num_legit": int(num_legit),
"num_cheaters": int(num_cheaters),
"total_samples": len(labels),
"seed": int(seed),
"features_shape": list(features.shape),
}
with open(meta_path, "w") as f:
json.dump(metadata, f, indent=2)
api.upload_file(path_or_fileobj=features_path, path_in_repo=f"contributions/features_{contribution_id}.npy", repo_id=DATASET_REPO, repo_type="dataset")
api.upload_file(path_or_fileobj=labels_path, path_in_repo=f"contributions/labels_{contribution_id}.npy", repo_id=DATASET_REPO, repo_type="dataset")
api.upload_file(path_or_fileobj=meta_path, path_in_repo=f"contributions/meta_{contribution_id}.json", repo_id=DATASET_REPO, repo_type="dataset")
return True, contribution_id
except Exception as e:
return False, str(e)
def generate_data(num_legit, num_cheaters, seed, contribute, progress=gr.Progress()):
progress(0, desc="Initializing generator...")
generator = SyntheticDataGenerator(seed=int(seed), engagements_per_session=200)
all_features = []
all_labels = []
total = num_legit + num_cheaters
for i in progress.tqdm(range(int(num_legit)), desc="Generating legit players"):
session = generator.generate_player(is_cheater=False)
all_features.append(session.to_tensor())
all_labels.append(0)
for i in progress.tqdm(range(int(num_cheaters)), desc="Generating cheaters"):
session = generator.generate_player(is_cheater=True)
all_features.append(session.to_tensor())
all_labels.append(2)
features = np.array(all_features)
labels = np.array(all_labels)
rng = np.random.default_rng(int(seed))
indices = rng.permutation(total)
features = features[indices]
labels = labels[indices]
split_idx = int(total * 0.9)
data_dir = Path("/tmp/manifold_data")
data_dir.mkdir(exist_ok=True)
np.save(data_dir / "train_features.npy", features[:split_idx])
np.save(data_dir / "train_labels.npy", labels[:split_idx])
np.save(data_dir / "val_features.npy", features[split_idx:])
np.save(data_dir / "val_labels.npy", labels[split_idx:])
status = f"β
Generated {total} samples:\n- Train: {split_idx}\n- Val: {total - split_idx}\n- Shape: {features.shape}"
if contribute:
progress(0.95, desc="Contributing to community dataset...")
success, result = contribute_to_dataset(features, labels, num_legit, num_cheaters, seed)
if success:
status += f"\n\nπ Contributed to community dataset! ID: {result}"
else:
status += f"\n\nβ οΈ Dataset contribution failed: {result}"
return status
@spaces.GPU(duration=300)
def train_model(batch_size, learning_rate, num_epochs):
global current_model
device = "cuda" if torch.cuda.is_available() else "cpu"
gpu_info = f"Using: {torch.cuda.get_device_name(0)}" if torch.cuda.is_available() else "CPU only"
data_dir = Path("/tmp/manifold_data")
if not (data_dir / "train_features.npy").exists():
return "β No data found! Generate data first.", ""
train_features = np.load(data_dir / "train_features.npy")
train_labels = np.load(data_dir / "train_labels.npy")
val_features = np.load(data_dir / "val_features.npy")
val_labels = np.load(data_dir / "val_labels.npy")
train_dataset = MANIFOLDDataset(data=train_features, labels=train_labels)
val_dataset = MANIFOLDDataset(data=val_features, labels=val_labels)
actual_batch = min(int(batch_size), len(train_dataset))
from torch.utils.data import DataLoader
train_loader = DataLoader(train_dataset, batch_size=actual_batch, shuffle=True, num_workers=0, drop_last=False, pin_memory=False)
val_loader = DataLoader(val_dataset, batch_size=actual_batch, shuffle=False, num_workers=0, drop_last=False, pin_memory=False)
model = MANIFOLDLite.from_config(ModelConfig())
model = model.to(device)
optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate, weight_decay=0.01)
scaler = torch.amp.GradScaler(enabled=torch.cuda.is_available())
scheduler = CurriculumScheduler()
logs = []
logs.append(f"π {gpu_info}")
logs.append(f"π Train: {len(train_dataset)}, Val: {len(val_dataset)}")
logs.append(f"π§ Params: {model.get_num_params():,}")
logs.append("-" * 40)
global_step = 0
for epoch in range(int(num_epochs)):
stage_config = scheduler.get_stage_config()
for pg in optimizer.param_groups:
pg["lr"] = stage_config["learning_rate"]
model.train()
train_loss = 0
for batch in train_loader:
batch = {k: v.to(device) for k, v in batch.items()}
mask = batch.get("mask")
if mask is not None:
mask = mask.bool()
with torch.amp.autocast(device_type='cuda', dtype=torch.float16, enabled=torch.cuda.is_available()):
outputs = model(batch["features"], mask=mask, active_components=stage_config.get("components"))
loss, _ = compute_total_loss(outputs, {"labels": batch["labels"]}, stage_config["losses"], global_step)
scaler.scale(loss).backward()
scaler.unscale_(optimizer)
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
scaler.step(optimizer)
scaler.update()
optimizer.zero_grad(set_to_none=True)
train_loss += loss.item()
global_step += 1
train_loss /= len(train_loader)
model.eval()
val_loss = 0
correct = 0
total = 0
with torch.no_grad():
for batch in val_loader:
batch = {k: v.to(device) for k, v in batch.items()}
mask = batch.get("mask")
if mask is not None:
mask = mask.bool()
outputs = model(batch["features"], mask=mask, active_components=stage_config.get("components"))
loss, _ = compute_total_loss(outputs, {"labels": batch["labels"]}, stage_config["losses"])
val_loss += loss.item()
if "predicted_class" in outputs:
correct += (outputs["predicted_class"] == batch["labels"]).sum().item()
total += batch["labels"].size(0)
val_loss = val_loss / len(val_loader) if len(val_loader) > 0 else 0
val_acc = correct / total if total > 0 else 0
step_info = scheduler.step_epoch()
stage_name = step_info["stage_name"].split(":")[0] if ":" in step_info["stage_name"] else step_info["stage_name"]
logs.append(f"Epoch {epoch+1:2d} | {stage_name:8s} | Loss: {train_loss:.4f} / {val_loss:.4f} | Acc: {val_acc:.4f}")
if step_info.get("stage_changed"):
logs.append(f" β Advanced to {scheduler.current_stage.name}")
save_path = Path("/tmp/manifold_model.pt")
torch.save({"model_state_dict": model.state_dict(), "config": ModelConfig()}, save_path)
current_model = model.cpu()
logs.append("-" * 40)
logs.append(f"β
Training complete! Final val accuracy: {val_acc:.4f}")
return "β
Training complete!", "\n".join(logs)
@spaces.GPU(duration=60)
def test_inference(num_samples):
global current_model
device = "cuda" if torch.cuda.is_available() else "cpu"
if current_model is None:
model_path = Path("/tmp/manifold_model.pt")
if model_path.exists():
current_model = MANIFOLDLite.from_config(ModelConfig())
ckpt = torch.load(model_path, map_location="cpu")
current_model.load_state_dict(ckpt["model_state_dict"])
else:
return "β No model! Train first."
model = current_model.to(device)
model.eval()
generator = SyntheticDataGenerator(seed=99999)
results = []
for i in range(int(num_samples)):
is_cheater = i % 2 == 1
session = generator.generate_player(is_cheater=is_cheater)
features = torch.tensor(session.to_tensor(), dtype=torch.float32).unsqueeze(0).to(device)
with torch.no_grad():
outputs = model(features)
pred = outputs["predicted_class"].item()
conf = outputs["verdict_probs"][0].max().item()
unc = outputs["uncertainty"].item()
classes = ["Clean", "Suspicious", "Cheating"]
actual = "Cheater" if is_cheater else "Legit"
correct = "β" if (pred > 0) == is_cheater else "β"
results.append(f"| {i+1} | {actual} | {classes[pred]} | {conf:.1%} | {unc:.3f} | {correct} |")
current_model = model.cpu()
header = "| # | Actual | Predicted | Conf | Uncert | β/β |\n|---|--------|-----------|------|--------|-----|"
correct_count = sum(1 for r in results if "β" in r)
footer = f"\n\n**Accuracy: {correct_count}/{num_samples} ({100*correct_count/num_samples:.1f}%)**"
return header + "\n" + "\n".join(results) + footer
with gr.Blocks(title="MANIFOLD Training", theme=gr.themes.Soft()) as demo:
gr.Markdown("# π― MANIFOLD - CS2 Cheat Detection")
gr.Markdown(f"**{get_device_info()}** | ZeroGPU will allocate H200 on demand")
with gr.Tabs():
with gr.TabItem("1οΈβ£ Generate Data"):
gr.Markdown("Generate synthetic CS2 player data")
with gr.Row():
num_legit = gr.Slider(50, 10000, value=70, step=10, label="Legit Players")
num_cheaters = gr.Slider(20, 5000, value=30, step=10, label="Cheaters")
seed = gr.Number(value=42, label="Seed")
gr.Markdown("---")
contribute_checkbox = gr.Checkbox(
value=False,
label="π Contribute to Community Dataset",
info="I agree to contribute this synthetic data to the public MANIFOLD dataset on Hugging Face. This data is purely synthetic and contains no personal information."
)
gen_btn = gr.Button("π² Generate Data", variant="primary")
gen_output = gr.Textbox(label="Status", lines=5)
gen_btn.click(generate_data, [num_legit, num_cheaters, seed, contribute_checkbox], gen_output)
with gr.TabItem("2οΈβ£ Train Model"):
gr.Markdown("Train with 4-stage curriculum learning (ZeroGPU: 5 min limit)")
with gr.Row():
batch_size = gr.Slider(16, 128, value=64, step=16, label="Batch Size")
lr = gr.Number(value=3e-4, label="Learning Rate")
epochs = gr.Slider(5, 50, value=15, step=5, label="Epochs")
train_btn = gr.Button("π Start Training", variant="primary")
train_status = gr.Textbox(label="Status", lines=2)
train_logs = gr.Textbox(label="Training Logs", lines=15)
train_btn.click(train_model, [batch_size, lr, epochs], [train_status, train_logs])
with gr.TabItem("3οΈβ£ Test Model"):
gr.Markdown("Test on synthetic samples")
num_test = gr.Slider(5, 30, value=10, step=5, label="Test Samples")
test_btn = gr.Button("π Run Inference", variant="primary")
test_output = gr.Markdown()
test_btn.click(test_inference, [num_test], test_output)
gr.Markdown("---\n*MANIFOLD: Motor-Aware Neural Inference for Faithfulness Of Latent Dynamics*")
if __name__ == "__main__":
demo.launch()
|