Julian Bilcke
commited on
Commit
·
5c50d1d
1
Parent(s):
fbf741d
wip
Browse files- CLAUDE.md +97 -0
- api_engine.py +262 -249
- api_server.py +59 -18
- client/client.js +61 -7
- client/index.html +17 -13
- requirements.txt +2 -0
- run_hf_space.py +41 -8
CLAUDE.md
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Matrix-Game 2.0 WebSocket Server
|
| 2 |
+
|
| 3 |
+
## Project Overview
|
| 4 |
+
|
| 5 |
+
Matrix-Game 2.0 is a real-time interactive game world generation system that uses advanced generative video models to create explorable environments. This repository contains a WebSocket server wrapper that enables web-based interaction with the Matrix-Game 2.0 models.
|
| 6 |
+
|
| 7 |
+
## Architecture
|
| 8 |
+
|
| 9 |
+
### Core Components
|
| 10 |
+
|
| 11 |
+
1. **api_server.py** - WebSocket server handling client connections and game sessions
|
| 12 |
+
2. **api_engine.py** - Matrix-Game 2.0 model inference engine
|
| 13 |
+
3. **api_utils.py** - Utility functions for image processing and visualization
|
| 14 |
+
4. **client/** - Web-based client interface for testing
|
| 15 |
+
|
| 16 |
+
### Model Components
|
| 17 |
+
|
| 18 |
+
- **WAN Diffusion Model** - Core generative model (14B parameters)
|
| 19 |
+
- **VAE Encoder/Decoder** - For latent space encoding/decoding
|
| 20 |
+
- **Streaming Pipeline** - Real-time frame generation
|
| 21 |
+
- **Condition Processing** - Keyboard and mouse input handling
|
| 22 |
+
|
| 23 |
+
## Key Features
|
| 24 |
+
|
| 25 |
+
- Real-time video generation based on user inputs
|
| 26 |
+
- Multiple game modes: Universal, GTA Drive, Temple Run
|
| 27 |
+
- WebSocket-based streaming for low-latency interaction
|
| 28 |
+
- Fallback mode for demo without GPU
|
| 29 |
+
- Support for multiple concurrent sessions
|
| 30 |
+
|
| 31 |
+
## Resolution and Performance
|
| 32 |
+
|
| 33 |
+
- Standard resolution: 352x640
|
| 34 |
+
- Target FPS: 16
|
| 35 |
+
- Streaming generation: 5 frames per batch
|
| 36 |
+
- Reduced latency through latent-space operations
|
| 37 |
+
|
| 38 |
+
## Game Modes
|
| 39 |
+
|
| 40 |
+
1. **Universal** - General exploration with full camera and movement control
|
| 41 |
+
2. **GTA Drive** - Driving simulation mode
|
| 42 |
+
3. **Temple Run** - Runner game mode with limited controls
|
| 43 |
+
|
| 44 |
+
## Input Controls
|
| 45 |
+
|
| 46 |
+
### Keyboard Controls
|
| 47 |
+
- W/S/A/D - Movement (forward/back/left/right)
|
| 48 |
+
- Space - Jump
|
| 49 |
+
- Shift/Ctrl - Attack/Action
|
| 50 |
+
|
| 51 |
+
### Mouse Controls
|
| 52 |
+
- X/Y coordinates normalized to [-1, 1]
|
| 53 |
+
- Camera rotation and view control
|
| 54 |
+
|
| 55 |
+
## Model Loading
|
| 56 |
+
|
| 57 |
+
The system automatically downloads models from Hugging Face (Skywork/Matrix-Game-2.0) if not present locally. Models include:
|
| 58 |
+
- Wan2.1_VAE.pth - VAE model weights
|
| 59 |
+
- Generator checkpoint files
|
| 60 |
+
- Configuration files for different modes
|
| 61 |
+
|
| 62 |
+
## Deployment
|
| 63 |
+
|
| 64 |
+
### Docker Deployment
|
| 65 |
+
```bash
|
| 66 |
+
docker build -t matrix-game-2 .
|
| 67 |
+
docker run -p 8080:8080 --gpus all matrix-game-2
|
| 68 |
+
```
|
| 69 |
+
|
| 70 |
+
### Local Development
|
| 71 |
+
```bash
|
| 72 |
+
pip install -r requirements.txt
|
| 73 |
+
python api_server.py --host 0.0.0.0 --port 8080
|
| 74 |
+
```
|
| 75 |
+
|
| 76 |
+
## Environment Variables
|
| 77 |
+
|
| 78 |
+
- `PORT` - Server port (default: 8080)
|
| 79 |
+
- `SPACE_ID` - Hugging Face Space ID (for HF deployment)
|
| 80 |
+
- `CUDA_VISIBLE_DEVICES` - GPU selection
|
| 81 |
+
|
| 82 |
+
## Testing
|
| 83 |
+
|
| 84 |
+
Access the web client at `http://localhost:8080/` after starting the server.
|
| 85 |
+
|
| 86 |
+
## Known Limitations
|
| 87 |
+
|
| 88 |
+
- Requires NVIDIA GPU with 24GB+ VRAM for full model
|
| 89 |
+
- Initial model loading takes 2-3 minutes
|
| 90 |
+
|
| 91 |
+
## Updates from V1
|
| 92 |
+
|
| 93 |
+
- New model architecture (WAN-based instead of DIT-based)
|
| 94 |
+
- Streaming pipeline for better real-time performance
|
| 95 |
+
- Improved condition handling for different game modes
|
| 96 |
+
- Better memory efficiency through tiling
|
| 97 |
+
- Simplified API structure
|
api_engine.py
CHANGED
|
@@ -2,9 +2,9 @@
|
|
| 2 |
# -*- coding: utf-8 -*-
|
| 3 |
|
| 4 |
"""
|
| 5 |
-
MatrixGame Engine
|
| 6 |
|
| 7 |
-
This module handles the core rendering and model inference for the
|
| 8 |
"""
|
| 9 |
|
| 10 |
import os
|
|
@@ -15,20 +15,20 @@ import torch
|
|
| 15 |
import numpy as np
|
| 16 |
from PIL import Image
|
| 17 |
import cv2
|
| 18 |
-
from
|
|
|
|
| 19 |
from diffusers.utils import load_image
|
| 20 |
-
from diffusers.video_processor import VideoProcessor
|
| 21 |
from typing import Dict, List, Tuple, Any, Optional, Union
|
| 22 |
from huggingface_hub import snapshot_download
|
|
|
|
| 23 |
|
| 24 |
-
#
|
| 25 |
-
from
|
| 26 |
-
from
|
| 27 |
-
from
|
| 28 |
-
from
|
| 29 |
-
from
|
| 30 |
-
from
|
| 31 |
-
from teacache_forward import teacache_forward
|
| 32 |
|
| 33 |
# Import utility functions
|
| 34 |
from api_utils import (
|
|
@@ -40,39 +40,37 @@ from api_utils import (
|
|
| 40 |
|
| 41 |
class MatrixGameEngine:
|
| 42 |
"""
|
| 43 |
-
Core engine for
|
| 44 |
"""
|
| 45 |
def __init__(self, args: Optional[argparse.Namespace] = None):
|
| 46 |
"""
|
| 47 |
-
Initialize the
|
| 48 |
|
| 49 |
Args:
|
| 50 |
args: Optional parsed command line arguments for model configuration
|
| 51 |
"""
|
| 52 |
# Set default parameters if args not provided
|
| 53 |
-
#
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
default_height = getattr(args, 'frame_height', 368) # Changed from 360 to 368 (368/16=23)
|
| 57 |
-
|
| 58 |
-
# Ensure compatibility with VAE and patch size
|
| 59 |
-
vae_patch_factor = 16 # vae_scale_factor (8) * patch_size (2) for both H and W
|
| 60 |
-
self.frame_width = (default_width // vae_patch_factor) * vae_patch_factor
|
| 61 |
-
self.frame_height = (default_height // vae_patch_factor) * vae_patch_factor
|
| 62 |
self.fps = getattr(args, 'fps', 16)
|
| 63 |
-
self.
|
| 64 |
-
self.
|
| 65 |
-
self.
|
|
|
|
|
|
|
| 66 |
|
| 67 |
# Initialize state
|
| 68 |
self.frame_count = 0
|
| 69 |
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 70 |
self.weight_dtype = torch.bfloat16 if torch.cuda.is_available() else torch.float32
|
| 71 |
|
| 72 |
-
#
|
| 73 |
-
self.
|
| 74 |
-
|
| 75 |
-
|
|
|
|
|
|
|
| 76 |
|
| 77 |
# Cache scene initial frames
|
| 78 |
self.scenes = {
|
|
@@ -86,137 +84,165 @@ class MatrixGameEngine:
|
|
| 86 |
'plain': load_scene_frames('plain', self.frame_width, self.frame_height)
|
| 87 |
}
|
| 88 |
|
| 89 |
-
#
|
| 90 |
-
self.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
|
| 92 |
-
# Initialize
|
| 93 |
self.model_loaded = False
|
| 94 |
-
if torch.cuda.is_available():
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
logger.info("MatrixGame models loaded successfully")
|
| 99 |
-
except Exception as e:
|
| 100 |
-
logger.error(f"Failed to initialize MatrixGame models: {str(e)}")
|
| 101 |
-
logger.info("Falling back to frame cycling mode")
|
| 102 |
-
else:
|
| 103 |
-
logger.warning("CUDA not available. Using frame cycling mode only.")
|
| 104 |
-
|
| 105 |
-
def _init_models(self):
|
| 106 |
-
"""Initialize MatrixGame models (VAE, text encoder, transformer)"""
|
| 107 |
-
# Initialize flow matching scheduler
|
| 108 |
-
self.scheduler = FlowMatchDiscreteScheduler(
|
| 109 |
-
shift=15.0,
|
| 110 |
-
reverse=True,
|
| 111 |
-
solver="euler"
|
| 112 |
-
)
|
| 113 |
|
| 114 |
-
# Initialize VAE
|
| 115 |
try:
|
| 116 |
-
self.
|
| 117 |
-
self.
|
| 118 |
-
|
| 119 |
-
self.vae.enable_tiling()
|
| 120 |
-
logger.info("VAE model loaded successfully")
|
| 121 |
except Exception as e:
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
|
|
|
|
|
|
| 126 |
try:
|
| 127 |
-
#
|
| 128 |
-
|
| 129 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
try:
|
| 131 |
-
# Download
|
| 132 |
downloaded_path = snapshot_download(
|
| 133 |
repo_id="Skywork/Matrix-Game-2.0",
|
| 134 |
-
|
| 135 |
-
local_dir=os.path.dirname(self.dit_path) if os.path.dirname(self.dit_path) else "./models/matrixgame"
|
| 136 |
)
|
| 137 |
-
|
| 138 |
-
self.dit_path = os.path.join(downloaded_path, "dit")
|
| 139 |
-
logger.info(f"Successfully downloaded DIT model to {self.dit_path}")
|
| 140 |
except Exception as e:
|
| 141 |
-
logger.error(f"Failed to download
|
| 142 |
raise
|
| 143 |
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
self.pipeline =
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
except Exception as e:
|
| 170 |
-
logger.error(f"Error
|
| 171 |
raise
|
| 172 |
-
|
| 173 |
-
# Configure teacache for the transformer
|
| 174 |
-
self.pipeline.transformer.__class__.enable_teacache = True
|
| 175 |
-
self.pipeline.transformer.__class__.cnt = 0
|
| 176 |
-
self.pipeline.transformer.__class__.num_steps = self.inference_steps
|
| 177 |
-
self.pipeline.transformer.__class__.accumulated_rel_l1_distance = 0
|
| 178 |
-
self.pipeline.transformer.__class__.rel_l1_thresh = 0.075
|
| 179 |
-
self.pipeline.transformer.__class__.previous_modulated_input = None
|
| 180 |
-
self.pipeline.transformer.__class__.previous_residual = None
|
| 181 |
-
self.pipeline.transformer.__class__.forward = teacache_forward
|
| 182 |
-
|
| 183 |
-
# Preprocess initial images for all scenes
|
| 184 |
-
for scene_name, frames in self.scenes.items():
|
| 185 |
-
if frames:
|
| 186 |
-
# Use first frame as initial image
|
| 187 |
-
self.scene_initial_images[scene_name] = self._preprocess_image(frames[0])
|
| 188 |
|
| 189 |
-
def
|
| 190 |
-
"""
|
| 191 |
-
|
|
|
|
| 192 |
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
torch.Tensor: Preprocessed image tensor
|
| 198 |
-
"""
|
| 199 |
-
# Convert numpy array to PIL Image if needed
|
| 200 |
-
if isinstance(image_array, np.ndarray):
|
| 201 |
-
image = Image.fromarray(image_array)
|
| 202 |
else:
|
| 203 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 204 |
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 215 |
|
| 216 |
def generate_frame(self, scene_name: str, keyboard_condition: Optional[List] = None,
|
| 217 |
mouse_condition: Optional[List] = None) -> bytes:
|
| 218 |
"""
|
| 219 |
-
Generate the next frame based on current conditions using
|
| 220 |
|
| 221 |
Args:
|
| 222 |
scene_name: Name of the current scene
|
|
@@ -227,122 +253,108 @@ class MatrixGameEngine:
|
|
| 227 |
bytes: JPEG bytes of the frame
|
| 228 |
"""
|
| 229 |
# Check if model is loaded
|
| 230 |
-
if not self.model_loaded
|
| 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 |
-
args = SimpleNamespace()
|
| 279 |
-
args.num_pre_frames = self.num_pre_frames
|
| 280 |
|
| 281 |
-
#
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
initial_image=initial_image,
|
| 290 |
-
num_inference_steps=self.inference_steps,
|
| 291 |
-
guidance_scale=self.guidance_scale,
|
| 292 |
-
embedded_guidance_scale=None,
|
| 293 |
-
data_type="video",
|
| 294 |
-
vae_ver='884-16c-hy',
|
| 295 |
-
enable_tiling=True,
|
| 296 |
-
generator=torch.Generator(device=self.device).manual_seed(42),
|
| 297 |
-
i2v_type='refiner',
|
| 298 |
-
semantic_images=semantic_image,
|
| 299 |
-
args=args
|
| 300 |
-
).videos[0]
|
| 301 |
-
|
| 302 |
-
# Convert video tensor to numpy array (use first frame)
|
| 303 |
-
video_frame = video[0].permute(1, 2, 0).cpu().numpy()
|
| 304 |
-
video_frame = (video_frame * 255).astype(np.uint8)
|
| 305 |
-
frame = video_frame
|
| 306 |
-
|
| 307 |
-
# Increment frame counter
|
| 308 |
-
self.frame_count += 1
|
| 309 |
|
| 310 |
-
|
| 311 |
-
logger.error(f"Error generating frame with MatrixGame model: {str(e)}")
|
| 312 |
-
# Fall back to cycling demo frames if model generation fails
|
| 313 |
-
return self._fallback_frame(scene_name, keyboard_condition, mouse_condition)
|
| 314 |
-
|
| 315 |
-
# Add visualization of input controls
|
| 316 |
-
frame = visualize_controls(
|
| 317 |
-
frame, keyboard_condition, mouse_condition,
|
| 318 |
-
self.frame_width, self.frame_height
|
| 319 |
-
)
|
| 320 |
-
|
| 321 |
-
# Convert frame to JPEG
|
| 322 |
-
return frame_to_jpeg(frame, self.frame_height, self.frame_width)
|
| 323 |
-
|
| 324 |
-
def _fallback_frame(self, scene_name: str, keyboard_condition: Optional[List] = None,
|
| 325 |
-
mouse_condition: Optional[List] = None) -> bytes:
|
| 326 |
-
"""
|
| 327 |
-
Generate a fallback frame when model generation fails.
|
| 328 |
-
|
| 329 |
-
Args:
|
| 330 |
-
scene_name: Name of the current scene
|
| 331 |
-
keyboard_condition: Keyboard input state
|
| 332 |
-
mouse_condition: Mouse input state
|
| 333 |
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
frame_idx = self.frame_count % len(scene_frames)
|
| 339 |
-
frame = scene_frames[frame_idx].copy()
|
| 340 |
-
self.frame_count += 1
|
| 341 |
-
|
| 342 |
-
# Add fallback mode indicator
|
| 343 |
-
cv2.putText(frame, "Fallback mode",
|
| 344 |
-
(10, self.frame_height - 20),
|
| 345 |
-
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1)
|
| 346 |
|
| 347 |
# Add visualization of input controls
|
| 348 |
frame = visualize_controls(
|
|
@@ -353,6 +365,7 @@ class MatrixGameEngine:
|
|
| 353 |
# Convert frame to JPEG
|
| 354 |
return frame_to_jpeg(frame, self.frame_height, self.frame_width)
|
| 355 |
|
|
|
|
| 356 |
def get_valid_scenes(self) -> List[str]:
|
| 357 |
"""
|
| 358 |
Get a list of valid scene names.
|
|
|
|
| 2 |
# -*- coding: utf-8 -*-
|
| 3 |
|
| 4 |
"""
|
| 5 |
+
MatrixGame V2 Engine
|
| 6 |
|
| 7 |
+
This module handles the core rendering and model inference for the Matrix-Game V2 project.
|
| 8 |
"""
|
| 9 |
|
| 10 |
import os
|
|
|
|
| 15 |
import numpy as np
|
| 16 |
from PIL import Image
|
| 17 |
import cv2
|
| 18 |
+
from omegaconf import OmegaConf
|
| 19 |
+
from torchvision.transforms import v2
|
| 20 |
from diffusers.utils import load_image
|
|
|
|
| 21 |
from typing import Dict, List, Tuple, Any, Optional, Union
|
| 22 |
from huggingface_hub import snapshot_download
|
| 23 |
+
from safetensors.torch import load_file
|
| 24 |
|
| 25 |
+
# Matrix-Game V2 specific imports
|
| 26 |
+
from pipeline import CausalInferenceStreamingPipeline
|
| 27 |
+
from wan.vae.wanx_vae import get_wanx_vae_wrapper
|
| 28 |
+
from demo_utils.vae_block3 import VAEDecoderWrapper
|
| 29 |
+
from utils.misc import set_seed
|
| 30 |
+
from utils.conditions import *
|
| 31 |
+
from utils.wan_wrapper import WanDiffusionWrapper
|
|
|
|
| 32 |
|
| 33 |
# Import utility functions
|
| 34 |
from api_utils import (
|
|
|
|
| 40 |
|
| 41 |
class MatrixGameEngine:
|
| 42 |
"""
|
| 43 |
+
Core engine for Matrix-Game V2 model inference and frame generation.
|
| 44 |
"""
|
| 45 |
def __init__(self, args: Optional[argparse.Namespace] = None):
|
| 46 |
"""
|
| 47 |
+
Initialize the Matrix-Game V2 engine with configuration parameters.
|
| 48 |
|
| 49 |
Args:
|
| 50 |
args: Optional parsed command line arguments for model configuration
|
| 51 |
"""
|
| 52 |
# Set default parameters if args not provided
|
| 53 |
+
# V2 uses 352x640 as standard resolution
|
| 54 |
+
self.frame_width = getattr(args, 'frame_width', 640)
|
| 55 |
+
self.frame_height = getattr(args, 'frame_height', 352)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
self.fps = getattr(args, 'fps', 16)
|
| 57 |
+
self.max_num_output_frames = getattr(args, 'max_num_output_frames', 90) # Reduced for real-time
|
| 58 |
+
self.seed = getattr(args, 'seed', 0)
|
| 59 |
+
self.config_path = getattr(args, 'config_path', 'configs/inference_yaml/inference_universal.yaml')
|
| 60 |
+
self.checkpoint_path = getattr(args, 'checkpoint_path', '')
|
| 61 |
+
self.pretrained_model_path = getattr(args, 'pretrained_model_path', 'Matrix-Game-2.0')
|
| 62 |
|
| 63 |
# Initialize state
|
| 64 |
self.frame_count = 0
|
| 65 |
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 66 |
self.weight_dtype = torch.bfloat16 if torch.cuda.is_available() else torch.float32
|
| 67 |
|
| 68 |
+
# Frame processing pipeline
|
| 69 |
+
self.frame_process = v2.Compose([
|
| 70 |
+
v2.Resize(size=(self.frame_height, self.frame_width), antialias=True),
|
| 71 |
+
v2.ToTensor(),
|
| 72 |
+
v2.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
|
| 73 |
+
])
|
| 74 |
|
| 75 |
# Cache scene initial frames
|
| 76 |
self.scenes = {
|
|
|
|
| 84 |
'plain': load_scene_frames('plain', self.frame_width, self.frame_height)
|
| 85 |
}
|
| 86 |
|
| 87 |
+
# Add universal scene for V2
|
| 88 |
+
self.scenes['universal'] = load_scene_frames('universal', self.frame_width, self.frame_height)
|
| 89 |
+
self.scenes['gta_drive'] = load_scene_frames('gta_drive', self.frame_width, self.frame_height)
|
| 90 |
+
self.scenes['temple_run'] = load_scene_frames('temple_run', self.frame_width, self.frame_height)
|
| 91 |
+
|
| 92 |
+
# Cache for preprocessed images and latents
|
| 93 |
+
self.scene_latents = {}
|
| 94 |
+
self.current_latent = None
|
| 95 |
+
self.current_frame_idx = 0
|
| 96 |
|
| 97 |
+
# Initialize Matrix-Game V2 pipeline
|
| 98 |
self.model_loaded = False
|
| 99 |
+
if not torch.cuda.is_available():
|
| 100 |
+
error_msg = "CUDA is not available. Matrix-Game V2 requires an NVIDIA GPU with CUDA support."
|
| 101 |
+
logger.error(error_msg)
|
| 102 |
+
raise RuntimeError(error_msg)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
|
|
|
|
| 104 |
try:
|
| 105 |
+
self._init_models()
|
| 106 |
+
self.model_loaded = True
|
| 107 |
+
logger.info("Matrix-Game V2 models loaded successfully")
|
|
|
|
|
|
|
| 108 |
except Exception as e:
|
| 109 |
+
error_msg = f"Failed to initialize Matrix-Game V2 models: {str(e)}"
|
| 110 |
+
logger.error(error_msg)
|
| 111 |
+
raise RuntimeError(error_msg)
|
| 112 |
+
|
| 113 |
+
def _init_models(self):
|
| 114 |
+
"""Initialize Matrix-Game V2 models"""
|
| 115 |
try:
|
| 116 |
+
# Load configuration
|
| 117 |
+
self.config = OmegaConf.load(self.config_path)
|
| 118 |
+
|
| 119 |
+
# Initialize generator
|
| 120 |
+
generator = WanDiffusionWrapper(
|
| 121 |
+
**getattr(self.config, "model_kwargs", {}), is_causal=True)
|
| 122 |
+
|
| 123 |
+
# Initialize VAE decoder
|
| 124 |
+
current_vae_decoder = VAEDecoderWrapper()
|
| 125 |
+
|
| 126 |
+
# Check if model exists locally, if not download from Hugging Face
|
| 127 |
+
if not os.path.exists(self.pretrained_model_path) or not os.path.exists(os.path.join(self.pretrained_model_path, "Wan2.1_VAE.pth")):
|
| 128 |
+
logger.info(f"Model not found at {self.pretrained_model_path}, downloading from Hugging Face...")
|
| 129 |
try:
|
| 130 |
+
# Download from Skywork/Matrix-Game-2.0
|
| 131 |
downloaded_path = snapshot_download(
|
| 132 |
repo_id="Skywork/Matrix-Game-2.0",
|
| 133 |
+
local_dir=self.pretrained_model_path
|
|
|
|
| 134 |
)
|
| 135 |
+
logger.info(f"Successfully downloaded model to {downloaded_path}")
|
|
|
|
|
|
|
| 136 |
except Exception as e:
|
| 137 |
+
logger.error(f"Failed to download model from Hugging Face: {str(e)}")
|
| 138 |
raise
|
| 139 |
|
| 140 |
+
# Load VAE state dict
|
| 141 |
+
vae_state_dict = torch.load(os.path.join(self.pretrained_model_path, "Wan2.1_VAE.pth"), map_location="cpu")
|
| 142 |
+
decoder_state_dict = {}
|
| 143 |
+
for key, value in vae_state_dict.items():
|
| 144 |
+
if 'decoder.' in key or 'conv2' in key:
|
| 145 |
+
decoder_state_dict[key] = value
|
| 146 |
+
current_vae_decoder.load_state_dict(decoder_state_dict)
|
| 147 |
+
current_vae_decoder.to(self.device, torch.float16)
|
| 148 |
+
current_vae_decoder.requires_grad_(False)
|
| 149 |
+
current_vae_decoder.eval()
|
| 150 |
+
|
| 151 |
+
# Use standard compilation mode for server deployment
|
| 152 |
+
try:
|
| 153 |
+
current_vae_decoder.compile(mode="reduce-overhead")
|
| 154 |
+
except:
|
| 155 |
+
logger.warning("VAE decoder compilation failed, continuing without compilation")
|
| 156 |
+
|
| 157 |
+
# Initialize streaming pipeline for real-time generation
|
| 158 |
+
self.pipeline = CausalInferenceStreamingPipeline(self.config, generator=generator, vae_decoder=current_vae_decoder)
|
| 159 |
+
|
| 160 |
+
# Load checkpoint if provided
|
| 161 |
+
if self.checkpoint_path and os.path.exists(self.checkpoint_path):
|
| 162 |
+
logger.info("Loading checkpoint...")
|
| 163 |
+
state_dict = load_file(self.checkpoint_path)
|
| 164 |
+
self.pipeline.generator.load_state_dict(state_dict)
|
| 165 |
+
|
| 166 |
+
self.pipeline = self.pipeline.to(device=self.device, dtype=self.weight_dtype)
|
| 167 |
+
self.pipeline.vae_decoder.to(torch.float16)
|
| 168 |
+
|
| 169 |
+
# Initialize VAE encoder
|
| 170 |
+
vae = get_wanx_vae_wrapper(self.pretrained_model_path, torch.float16)
|
| 171 |
+
vae.requires_grad_(False)
|
| 172 |
+
vae.eval()
|
| 173 |
+
self.vae = vae.to(self.device, self.weight_dtype)
|
| 174 |
+
|
| 175 |
+
logger.info("Models loaded successfully")
|
| 176 |
+
|
| 177 |
+
# Preprocess initial images for all scenes
|
| 178 |
+
for scene_name, frames in self.scenes.items():
|
| 179 |
+
if frames and len(frames) > 0:
|
| 180 |
+
# Prepare the first frame as initial latent
|
| 181 |
+
self._prepare_scene_latent(scene_name, frames[0])
|
| 182 |
+
|
| 183 |
except Exception as e:
|
| 184 |
+
logger.error(f"Error loading models: {str(e)}")
|
| 185 |
raise
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 186 |
|
| 187 |
+
def _resizecrop(self, image, th, tw):
|
| 188 |
+
"""Resize and crop image to target dimensions"""
|
| 189 |
+
if isinstance(image, np.ndarray):
|
| 190 |
+
image = Image.fromarray(image)
|
| 191 |
|
| 192 |
+
w, h = image.size
|
| 193 |
+
if h / w > th / tw:
|
| 194 |
+
new_w = int(w)
|
| 195 |
+
new_h = int(new_w * th / tw)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
else:
|
| 197 |
+
new_h = int(h)
|
| 198 |
+
new_w = int(new_h * tw / th)
|
| 199 |
+
left = (w - new_w) / 2
|
| 200 |
+
top = (h - new_h) / 2
|
| 201 |
+
right = (w + new_w) / 2
|
| 202 |
+
bottom = (h + new_h) / 2
|
| 203 |
+
image = image.crop((left, top, right, bottom))
|
| 204 |
+
return image
|
| 205 |
+
|
| 206 |
+
def _prepare_scene_latent(self, scene_name: str, frame: np.ndarray):
|
| 207 |
+
"""Prepare and cache latent for a scene"""
|
| 208 |
+
try:
|
| 209 |
+
# Convert to PIL if needed
|
| 210 |
+
if isinstance(frame, np.ndarray):
|
| 211 |
+
image = Image.fromarray(frame)
|
| 212 |
+
else:
|
| 213 |
+
image = frame
|
| 214 |
|
| 215 |
+
# Resize and process
|
| 216 |
+
image = self._resizecrop(image, self.frame_height, self.frame_width)
|
| 217 |
+
processed = self.frame_process(image)[None, :, None, :, :].to(dtype=self.weight_dtype, device=self.device)
|
| 218 |
+
|
| 219 |
+
# Encode to latent space
|
| 220 |
+
padding_video = torch.zeros_like(processed).repeat(1, 1, 4 * (self.max_num_output_frames - 1), 1, 1)
|
| 221 |
+
img_cond = torch.concat([processed, padding_video], dim=2)
|
| 222 |
+
|
| 223 |
+
# Use tiling for memory efficiency
|
| 224 |
+
tiler_kwargs = {"tiled": True, "tile_size": [44, 80], "tile_stride": [23, 38]}
|
| 225 |
+
img_latent = self.vae.encode(img_cond, device=self.device, **tiler_kwargs).to(self.device)
|
| 226 |
+
|
| 227 |
+
# Create mask
|
| 228 |
+
mask_cond = torch.ones_like(img_latent)
|
| 229 |
+
mask_cond[:, :, 1:] = 0
|
| 230 |
+
|
| 231 |
+
# Store preprocessed data
|
| 232 |
+
self.scene_latents[scene_name] = {
|
| 233 |
+
'image': processed,
|
| 234 |
+
'latent': img_latent,
|
| 235 |
+
'mask': mask_cond,
|
| 236 |
+
'visual_context': self.vae.clip.encode_video(processed)
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
except Exception as e:
|
| 240 |
+
logger.error(f"Error preparing latent for scene {scene_name}: {str(e)}")
|
| 241 |
|
| 242 |
def generate_frame(self, scene_name: str, keyboard_condition: Optional[List] = None,
|
| 243 |
mouse_condition: Optional[List] = None) -> bytes:
|
| 244 |
"""
|
| 245 |
+
Generate the next frame based on current conditions using Matrix-Game V2 model.
|
| 246 |
|
| 247 |
Args:
|
| 248 |
scene_name: Name of the current scene
|
|
|
|
| 253 |
bytes: JPEG bytes of the frame
|
| 254 |
"""
|
| 255 |
# Check if model is loaded
|
| 256 |
+
if not self.model_loaded:
|
| 257 |
+
error_msg = "Model not loaded. Cannot generate frames."
|
| 258 |
+
logger.error(error_msg)
|
| 259 |
+
raise RuntimeError(error_msg)
|
| 260 |
+
|
| 261 |
+
if not torch.cuda.is_available():
|
| 262 |
+
error_msg = "CUDA is no longer available. Cannot generate frames."
|
| 263 |
+
logger.error(error_msg)
|
| 264 |
+
raise RuntimeError(error_msg)
|
| 265 |
+
|
| 266 |
+
try:
|
| 267 |
+
# Map scene name to mode
|
| 268 |
+
mode_map = {
|
| 269 |
+
'universal': 'universal',
|
| 270 |
+
'gta_drive': 'gta_drive',
|
| 271 |
+
'temple_run': 'templerun',
|
| 272 |
+
'templerun': 'templerun'
|
| 273 |
+
}
|
| 274 |
+
mode = mode_map.get(scene_name, 'universal')
|
| 275 |
+
|
| 276 |
+
# Get cached latent or prepare new one
|
| 277 |
+
if scene_name not in self.scene_latents:
|
| 278 |
+
scene_frames = self.scenes.get(scene_name, self.scenes.get('universal', []))
|
| 279 |
+
if scene_frames:
|
| 280 |
+
self._prepare_scene_latent(scene_name, scene_frames[0])
|
| 281 |
+
else:
|
| 282 |
+
error_msg = f"No initial frames available for scene: {scene_name}"
|
| 283 |
+
logger.error(error_msg)
|
| 284 |
+
raise ValueError(error_msg)
|
| 285 |
+
|
| 286 |
+
scene_data = self.scene_latents.get(scene_name)
|
| 287 |
+
if not scene_data:
|
| 288 |
+
error_msg = f"Failed to prepare latent for scene: {scene_name}"
|
| 289 |
+
logger.error(error_msg)
|
| 290 |
+
raise ValueError(error_msg)
|
| 291 |
+
|
| 292 |
+
# Prepare conditions
|
| 293 |
+
if keyboard_condition is None:
|
| 294 |
+
keyboard_condition = [[0, 0, 0, 0, 0, 0]]
|
| 295 |
+
if mouse_condition is None:
|
| 296 |
+
mouse_condition = [[0, 0]]
|
| 297 |
+
|
| 298 |
+
# Generate conditions for multiple frames (for streaming)
|
| 299 |
+
num_frames = 5 # Generate 5 frames at a time for smoother playback
|
| 300 |
+
|
| 301 |
+
# Create condition tensors
|
| 302 |
+
keyboard_tensor = torch.tensor(keyboard_condition * num_frames, dtype=self.weight_dtype).unsqueeze(0).to(self.device)
|
| 303 |
+
mouse_tensor = torch.tensor(mouse_condition * num_frames, dtype=self.weight_dtype).unsqueeze(0).to(self.device)
|
| 304 |
+
|
| 305 |
+
# Build conditional dict
|
| 306 |
+
cond_concat = torch.cat([scene_data['mask'][:, :4], scene_data['latent']], dim=1)
|
| 307 |
+
conditional_dict = {
|
| 308 |
+
"cond_concat": cond_concat.to(device=self.device, dtype=self.weight_dtype),
|
| 309 |
+
"visual_context": scene_data['visual_context'].to(device=self.device, dtype=self.weight_dtype),
|
| 310 |
+
"keyboard_cond": keyboard_tensor
|
| 311 |
+
}
|
| 312 |
+
|
| 313 |
+
# Add mouse condition for modes that support it
|
| 314 |
+
if mode in ['universal', 'gta_drive']:
|
| 315 |
+
conditional_dict['mouse_cond'] = mouse_tensor
|
| 316 |
+
|
| 317 |
+
# Generate noise for the frames
|
| 318 |
+
sampled_noise = torch.randn(
|
| 319 |
+
[1, 16, num_frames, 44, 80], device=self.device, dtype=self.weight_dtype
|
| 320 |
+
)
|
| 321 |
+
|
| 322 |
+
# Generate frames with streaming pipeline
|
| 323 |
+
with torch.no_grad():
|
| 324 |
+
# Set seed for reproducibility
|
| 325 |
+
set_seed(self.seed + self.frame_count)
|
| 326 |
|
| 327 |
+
# Use inference method for single batch generation
|
| 328 |
+
outputs = self.pipeline.inference(
|
| 329 |
+
noise=sampled_noise,
|
| 330 |
+
conditional_dict=conditional_dict,
|
| 331 |
+
return_latents=True, # Return latents for faster decoding
|
| 332 |
+
output_folder=None, # Don't save to disk
|
| 333 |
+
name=None,
|
| 334 |
+
mode=mode
|
| 335 |
+
)
|
| 336 |
|
| 337 |
+
# Decode first frame from latent
|
| 338 |
+
if outputs is not None and len(outputs) > 0:
|
| 339 |
+
# Extract first frame
|
| 340 |
+
frame_latent = outputs[0:1, :, 0:1] # Get first frame
|
| 341 |
+
decoded = self.pipeline.vae_decoder.decode(frame_latent)
|
|
|
|
|
|
|
| 342 |
|
| 343 |
+
# Convert to numpy
|
| 344 |
+
frame = decoded[0, :, 0].permute(1, 2, 0).cpu().numpy()
|
| 345 |
+
frame = ((frame + 1) * 127.5).clip(0, 255).astype(np.uint8)
|
| 346 |
+
else:
|
| 347 |
+
# Generation failed
|
| 348 |
+
error_msg = "Failed to generate frame: No output from model"
|
| 349 |
+
logger.error(error_msg)
|
| 350 |
+
raise RuntimeError(error_msg)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 351 |
|
| 352 |
+
self.frame_count += 1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 353 |
|
| 354 |
+
except Exception as e:
|
| 355 |
+
error_msg = f"Error generating frame with Matrix-Game V2 model: {str(e)}"
|
| 356 |
+
logger.error(error_msg)
|
| 357 |
+
raise RuntimeError(error_msg)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 358 |
|
| 359 |
# Add visualization of input controls
|
| 360 |
frame = visualize_controls(
|
|
|
|
| 365 |
# Convert frame to JPEG
|
| 366 |
return frame_to_jpeg(frame, self.frame_height, self.frame_width)
|
| 367 |
|
| 368 |
+
|
| 369 |
def get_valid_scenes(self) -> List[str]:
|
| 370 |
"""
|
| 371 |
Get a list of valid scene names.
|
api_server.py
CHANGED
|
@@ -249,10 +249,30 @@ class GameSession:
|
|
| 249 |
keyboard_condition = [self.keyboard_state]
|
| 250 |
mouse_condition = [self.mouse_state]
|
| 251 |
|
| 252 |
-
#
|
| 253 |
-
|
| 254 |
-
self.
|
| 255 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 256 |
|
| 257 |
# Encode as base64 for sending in JSON
|
| 258 |
frame_base64 = base64.b64encode(frame_bytes).decode('utf-8')
|
|
@@ -296,12 +316,20 @@ class GameManager:
|
|
| 296 |
def __init__(self, args: argparse.Namespace):
|
| 297 |
self.sessions = {}
|
| 298 |
self.session_lock = asyncio.Lock()
|
|
|
|
|
|
|
| 299 |
|
| 300 |
-
#
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 305 |
|
| 306 |
async def create_session(self, user_id: str, ws: web.WebSocketResponse) -> GameSession:
|
| 307 |
"""Create a new game session"""
|
|
@@ -363,12 +391,18 @@ async def status_handler(request: web.Request) -> web.Response:
|
|
| 363 |
# Get session statistics
|
| 364 |
session_stats = game_manager.get_session_stats()
|
| 365 |
|
| 366 |
-
|
| 367 |
-
'product': '
|
| 368 |
-
'version': '
|
| 369 |
'active_sessions': session_stats,
|
| 370 |
-
'available_scenes': game_manager.valid_scenes
|
| 371 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 372 |
|
| 373 |
async def root_handler(request: web.Request) -> web.Response:
|
| 374 |
"""Handler for serving the client at the root path"""
|
|
@@ -442,12 +476,19 @@ async def websocket_handler(request: web.Request) -> web.WebSocketResponse:
|
|
| 442 |
|
| 443 |
# Send initial welcome message
|
| 444 |
try:
|
| 445 |
-
|
| 446 |
'action': 'welcome',
|
| 447 |
'userId': user_id,
|
| 448 |
-
'message': 'Welcome to the
|
| 449 |
-
'scenes': game_manager.valid_scenes
|
| 450 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 451 |
logger.info(f"Sent welcome message to user {user_id}")
|
| 452 |
except Exception as welcome_error:
|
| 453 |
logger.error(f"Error sending welcome message: {str(welcome_error)}")
|
|
|
|
| 249 |
keyboard_condition = [self.keyboard_state]
|
| 250 |
mouse_condition = [self.mouse_state]
|
| 251 |
|
| 252 |
+
# Check if engine is available
|
| 253 |
+
if not self.game_manager.engine:
|
| 254 |
+
error_msg = f"Engine not available: {self.game_manager.engine_error}"
|
| 255 |
+
await self.ws.send_json({
|
| 256 |
+
'action': 'frame_error',
|
| 257 |
+
'error': error_msg
|
| 258 |
+
})
|
| 259 |
+
self.is_streaming = False
|
| 260 |
+
return
|
| 261 |
+
|
| 262 |
+
try:
|
| 263 |
+
# Use the engine to generate the next frame
|
| 264 |
+
frame_bytes = self.game_manager.engine.generate_frame(
|
| 265 |
+
self.current_scene, keyboard_condition, mouse_condition
|
| 266 |
+
)
|
| 267 |
+
except Exception as e:
|
| 268 |
+
error_msg = f"Failed to generate frame: {str(e)}"
|
| 269 |
+
logger.error(error_msg)
|
| 270 |
+
await self.ws.send_json({
|
| 271 |
+
'action': 'frame_error',
|
| 272 |
+
'error': error_msg
|
| 273 |
+
})
|
| 274 |
+
self.is_streaming = False
|
| 275 |
+
return
|
| 276 |
|
| 277 |
# Encode as base64 for sending in JSON
|
| 278 |
frame_base64 = base64.b64encode(frame_bytes).decode('utf-8')
|
|
|
|
| 316 |
def __init__(self, args: argparse.Namespace):
|
| 317 |
self.sessions = {}
|
| 318 |
self.session_lock = asyncio.Lock()
|
| 319 |
+
self.engine = None
|
| 320 |
+
self.engine_error = None
|
| 321 |
|
| 322 |
+
# Try to initialize game engine
|
| 323 |
+
try:
|
| 324 |
+
self.engine = MatrixGameEngine(args)
|
| 325 |
+
# Load valid scenes from engine
|
| 326 |
+
self.valid_scenes = self.engine.get_valid_scenes()
|
| 327 |
+
logger.info("Game engine initialized successfully")
|
| 328 |
+
except Exception as e:
|
| 329 |
+
self.engine_error = str(e)
|
| 330 |
+
logger.error(f"Failed to initialize game engine: {self.engine_error}")
|
| 331 |
+
# Set default scenes even if engine fails
|
| 332 |
+
self.valid_scenes = ['universal', 'gta_drive', 'temple_run']
|
| 333 |
|
| 334 |
async def create_session(self, user_id: str, ws: web.WebSocketResponse) -> GameSession:
|
| 335 |
"""Create a new game session"""
|
|
|
|
| 391 |
# Get session statistics
|
| 392 |
session_stats = game_manager.get_session_stats()
|
| 393 |
|
| 394 |
+
status_data = {
|
| 395 |
+
'product': 'Matrix-Game V2 WebSocket Server',
|
| 396 |
+
'version': '2.0.0',
|
| 397 |
'active_sessions': session_stats,
|
| 398 |
+
'available_scenes': game_manager.valid_scenes,
|
| 399 |
+
'engine_status': 'ready' if game_manager.engine else 'failed'
|
| 400 |
+
}
|
| 401 |
+
|
| 402 |
+
if game_manager.engine_error:
|
| 403 |
+
status_data['engine_error'] = game_manager.engine_error
|
| 404 |
+
|
| 405 |
+
return web.json_response(status_data)
|
| 406 |
|
| 407 |
async def root_handler(request: web.Request) -> web.Response:
|
| 408 |
"""Handler for serving the client at the root path"""
|
|
|
|
| 476 |
|
| 477 |
# Send initial welcome message
|
| 478 |
try:
|
| 479 |
+
welcome_msg = {
|
| 480 |
'action': 'welcome',
|
| 481 |
'userId': user_id,
|
| 482 |
+
'message': 'Welcome to the Matrix-Game V2 WebSocket server!',
|
| 483 |
+
'scenes': game_manager.valid_scenes,
|
| 484 |
+
'engine_status': 'ready' if game_manager.engine else 'failed'
|
| 485 |
+
}
|
| 486 |
+
|
| 487 |
+
if game_manager.engine_error:
|
| 488 |
+
welcome_msg['engine_error'] = game_manager.engine_error
|
| 489 |
+
welcome_msg['message'] = f"Warning: Engine initialization failed - {game_manager.engine_error}"
|
| 490 |
+
|
| 491 |
+
await ws.send_json(welcome_msg)
|
| 492 |
logger.info(f"Sent welcome message to user {user_id}")
|
| 493 |
except Exception as welcome_error:
|
| 494 |
logger.error(f"Error sending welcome message: {str(welcome_error)}")
|
client/client.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
//
|
| 2 |
|
| 3 |
// WebSocket connection
|
| 4 |
let socket = null;
|
|
@@ -86,7 +86,16 @@ async function testServerConnectivity() {
|
|
| 86 |
}
|
| 87 |
|
| 88 |
const debugInfo = await response.json();
|
| 89 |
-
logMessage(`
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
// Log available routes from server
|
| 92 |
if (debugInfo.all_routes && debugInfo.all_routes.length > 0) {
|
|
@@ -167,17 +176,44 @@ function setupWebSocketHandlers() {
|
|
| 167 |
switch (message.action) {
|
| 168 |
case 'welcome':
|
| 169 |
userId = message.userId;
|
| 170 |
-
logMessage(`
|
| 171 |
|
| 172 |
// Update scene options if server provides them
|
| 173 |
if (message.scenes && Array.isArray(message.scenes)) {
|
| 174 |
sceneSelect.innerHTML = '';
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 175 |
message.scenes.forEach(scene => {
|
| 176 |
const option = document.createElement('option');
|
| 177 |
option.value = scene;
|
| 178 |
-
|
| 179 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 181 |
}
|
| 182 |
break;
|
| 183 |
|
|
@@ -220,9 +256,27 @@ function setupWebSocketHandlers() {
|
|
| 220 |
|
| 221 |
case 'change_scene':
|
| 222 |
if (message.success) {
|
| 223 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 224 |
} else {
|
| 225 |
-
logMessage(`Error changing
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 226 |
}
|
| 227 |
break;
|
| 228 |
|
|
|
|
| 1 |
+
// Matrix-Game V2 WebSocket Client
|
| 2 |
|
| 3 |
// WebSocket connection
|
| 4 |
let socket = null;
|
|
|
|
| 86 |
}
|
| 87 |
|
| 88 |
const debugInfo = await response.json();
|
| 89 |
+
logMessage(`Matrix-Game V2 server connected! Server time: ${new Date(debugInfo.server_time * 1000).toLocaleTimeString()}`);
|
| 90 |
+
|
| 91 |
+
// Check engine status in debug info
|
| 92 |
+
if (debugInfo.server_info && debugInfo.server_info.engine_status) {
|
| 93 |
+
if (debugInfo.server_info.engine_status === 'failed') {
|
| 94 |
+
logMessage(`⚠️ Warning: Engine status is '${debugInfo.server_info.engine_status}'`);
|
| 95 |
+
} else {
|
| 96 |
+
logMessage(`✅ Engine status: ${debugInfo.server_info.engine_status}`);
|
| 97 |
+
}
|
| 98 |
+
}
|
| 99 |
|
| 100 |
// Log available routes from server
|
| 101 |
if (debugInfo.all_routes && debugInfo.all_routes.length > 0) {
|
|
|
|
| 176 |
switch (message.action) {
|
| 177 |
case 'welcome':
|
| 178 |
userId = message.userId;
|
| 179 |
+
logMessage(`Welcome to Matrix-Game V2! User ID: ${userId}`);
|
| 180 |
|
| 181 |
// Update scene options if server provides them
|
| 182 |
if (message.scenes && Array.isArray(message.scenes)) {
|
| 183 |
sceneSelect.innerHTML = '';
|
| 184 |
+
|
| 185 |
+
// Add V2 modes first
|
| 186 |
+
const v2Modes = ['universal', 'gta_drive', 'temple_run'];
|
| 187 |
+
const modeNames = {
|
| 188 |
+
'universal': 'Universal Mode',
|
| 189 |
+
'gta_drive': 'GTA Drive Mode',
|
| 190 |
+
'temple_run': 'Temple Run Mode'
|
| 191 |
+
};
|
| 192 |
+
|
| 193 |
message.scenes.forEach(scene => {
|
| 194 |
const option = document.createElement('option');
|
| 195 |
option.value = scene;
|
| 196 |
+
|
| 197 |
+
// Use friendly names for V2 modes
|
| 198 |
+
if (modeNames[scene]) {
|
| 199 |
+
option.textContent = modeNames[scene];
|
| 200 |
+
} else {
|
| 201 |
+
// Legacy scenes marked as demo
|
| 202 |
+
option.textContent = scene.charAt(0).toUpperCase() + scene.slice(1) + ' (Demo)';
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
// Group V2 modes at the top
|
| 206 |
+
if (v2Modes.includes(scene)) {
|
| 207 |
+
sceneSelect.insertBefore(option, sceneSelect.firstChild);
|
| 208 |
+
} else {
|
| 209 |
+
sceneSelect.appendChild(option);
|
| 210 |
+
}
|
| 211 |
});
|
| 212 |
+
|
| 213 |
+
// Default to universal mode if available
|
| 214 |
+
if (message.scenes.includes('universal')) {
|
| 215 |
+
sceneSelect.value = 'universal';
|
| 216 |
+
}
|
| 217 |
}
|
| 218 |
break;
|
| 219 |
|
|
|
|
| 256 |
|
| 257 |
case 'change_scene':
|
| 258 |
if (message.success) {
|
| 259 |
+
const modeNames = {
|
| 260 |
+
'universal': 'Universal Mode',
|
| 261 |
+
'gta_drive': 'GTA Drive Mode',
|
| 262 |
+
'temple_run': 'Temple Run Mode'
|
| 263 |
+
};
|
| 264 |
+
const displayName = modeNames[message.scene] || message.scene;
|
| 265 |
+
logMessage(`Mode changed to: ${displayName}`);
|
| 266 |
} else {
|
| 267 |
+
logMessage(`Error changing mode: ${message.error}`);
|
| 268 |
+
}
|
| 269 |
+
break;
|
| 270 |
+
|
| 271 |
+
case 'frame_error':
|
| 272 |
+
logMessage(`❌ Frame Generation Error: ${message.error}`);
|
| 273 |
+
// Stop streaming if there's a frame error
|
| 274 |
+
if (isStreaming) {
|
| 275 |
+
isStreaming = false;
|
| 276 |
+
startStreamBtn.disabled = false;
|
| 277 |
+
stopStreamBtn.disabled = true;
|
| 278 |
+
startStreamBtn.textContent = 'Start Stream';
|
| 279 |
+
stopFpsCounter();
|
| 280 |
}
|
| 281 |
break;
|
| 282 |
|
client/index.html
CHANGED
|
@@ -3,7 +3,7 @@
|
|
| 3 |
<head>
|
| 4 |
<meta charset="UTF-8">
|
| 5 |
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 6 |
-
<title>
|
| 7 |
<style>
|
| 8 |
body {
|
| 9 |
font-family: Arial, sans-serif;
|
|
@@ -264,14 +264,17 @@
|
|
| 264 |
<button id="start-stream-btn" disabled>Start Stream</button>
|
| 265 |
<button id="stop-stream-btn" disabled>Stop Stream</button>
|
| 266 |
<select id="scene-select" disabled>
|
| 267 |
-
<option value="
|
| 268 |
-
<option value="
|
| 269 |
-
<option value="
|
| 270 |
-
<option value="
|
| 271 |
-
<option value="
|
| 272 |
-
<option value="
|
| 273 |
-
<option value="
|
| 274 |
-
<option value="
|
|
|
|
|
|
|
|
|
|
| 275 |
</select>
|
| 276 |
</div>
|
| 277 |
</div>
|
|
@@ -301,10 +304,11 @@
|
|
| 301 |
</div>
|
| 302 |
</div>
|
| 303 |
<p class="status">
|
| 304 |
-
W
|
| 305 |
-
Space = Jump, Shift = Attack<br>
|
| 306 |
-
Click
|
| 307 |
-
|
|
|
|
| 308 |
</p>
|
| 309 |
</div>
|
| 310 |
</div>
|
|
|
|
| 3 |
<head>
|
| 4 |
<meta charset="UTF-8">
|
| 5 |
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 6 |
+
<title>Matrix-Game V2 Client</title>
|
| 7 |
<style>
|
| 8 |
body {
|
| 9 |
font-family: Arial, sans-serif;
|
|
|
|
| 264 |
<button id="start-stream-btn" disabled>Start Stream</button>
|
| 265 |
<button id="stop-stream-btn" disabled>Stop Stream</button>
|
| 266 |
<select id="scene-select" disabled>
|
| 267 |
+
<option value="universal">Universal Mode</option>
|
| 268 |
+
<option value="gta_drive">GTA Drive Mode</option>
|
| 269 |
+
<option value="temple_run">Temple Run Mode</option>
|
| 270 |
+
<option value="forest">Forest (Demo)</option>
|
| 271 |
+
<option value="desert">Desert (Demo)</option>
|
| 272 |
+
<option value="beach">Beach (Demo)</option>
|
| 273 |
+
<option value="hills">Hills (Demo)</option>
|
| 274 |
+
<option value="river">River (Demo)</option>
|
| 275 |
+
<option value="icy">Icy (Demo)</option>
|
| 276 |
+
<option value="mushroom">Mushroom (Demo)</option>
|
| 277 |
+
<option value="plain">Plain (Demo)</option>
|
| 278 |
</select>
|
| 279 |
</div>
|
| 280 |
</div>
|
|
|
|
| 304 |
</div>
|
| 305 |
</div>
|
| 306 |
<p class="status">
|
| 307 |
+
<strong>Movement:</strong> W/↑ = Forward, S/↓ = Back, A/← = Left, D/→ = Right<br>
|
| 308 |
+
<strong>Actions:</strong> Space = Jump, Shift = Attack/Action<br>
|
| 309 |
+
<strong>Camera:</strong> Click game view to capture mouse (ESC to release)<br>
|
| 310 |
+
<strong>Modes:</strong> Universal (full control), GTA Drive (driving), Temple Run (runner)<br>
|
| 311 |
+
<strong>Requirements:</strong> NVIDIA GPU with 24GB+ VRAM required for model inference
|
| 312 |
</p>
|
| 313 |
</div>
|
| 314 |
</div>
|
requirements.txt
CHANGED
|
@@ -41,3 +41,5 @@ onnxconverter_common
|
|
| 41 |
flask
|
| 42 |
flask-socketio
|
| 43 |
torchao
|
|
|
|
|
|
|
|
|
| 41 |
flask
|
| 42 |
flask-socketio
|
| 43 |
torchao
|
| 44 |
+
aiohttp
|
| 45 |
+
Pillow
|
run_hf_space.py
CHANGED
|
@@ -2,7 +2,7 @@
|
|
| 2 |
# -*- coding: utf-8 -*-
|
| 3 |
|
| 4 |
"""
|
| 5 |
-
Hugging Face Space launcher for
|
| 6 |
This script launches the server with the appropriate configuration for Hugging Face Spaces.
|
| 7 |
"""
|
| 8 |
|
|
@@ -20,10 +20,35 @@ logging.basicConfig(
|
|
| 20 |
)
|
| 21 |
logger = logging.getLogger(__name__)
|
| 22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
def install_apex():
|
| 24 |
-
"""Install NVIDIA Apex at runtime with CUDA support"""
|
| 25 |
try:
|
| 26 |
-
logger.info("Installing NVIDIA Apex...")
|
| 27 |
|
| 28 |
# Clone the Apex repository
|
| 29 |
subprocess.check_call([
|
|
@@ -57,14 +82,22 @@ def install_apex():
|
|
| 57 |
|
| 58 |
except subprocess.CalledProcessError as e:
|
| 59 |
logger.error(f"Failed to install Apex. Error: {e}")
|
| 60 |
-
|
| 61 |
-
|
| 62 |
except Exception as e:
|
| 63 |
logger.error(f"Unexpected error during Apex installation: {e}")
|
| 64 |
-
|
| 65 |
finally:
|
| 66 |
# Change back to original directory
|
| 67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
install_apex()
|
| 70 |
|
|
@@ -133,7 +166,7 @@ def main():
|
|
| 133 |
path_arg = "" # or f"--path /{os.environ.get('SPACE_ID', '')}" if needed
|
| 134 |
|
| 135 |
# Construct and run the command
|
| 136 |
-
cmd = f"{sys.executable}
|
| 137 |
print(f"Running command: {cmd}")
|
| 138 |
subprocess.run(cmd, shell=True)
|
| 139 |
|
|
|
|
| 2 |
# -*- coding: utf-8 -*-
|
| 3 |
|
| 4 |
"""
|
| 5 |
+
Hugging Face Space launcher for Matrix-Game V2 WebSocket Server
|
| 6 |
This script launches the server with the appropriate configuration for Hugging Face Spaces.
|
| 7 |
"""
|
| 8 |
|
|
|
|
| 20 |
)
|
| 21 |
logger = logging.getLogger(__name__)
|
| 22 |
|
| 23 |
+
def check_gpu_availability():
|
| 24 |
+
"""Check if CUDA GPU is available for Matrix-Game V2"""
|
| 25 |
+
try:
|
| 26 |
+
import torch
|
| 27 |
+
if torch.cuda.is_available():
|
| 28 |
+
gpu_count = torch.cuda.device_count()
|
| 29 |
+
for i in range(gpu_count):
|
| 30 |
+
gpu_props = torch.cuda.get_device_properties(i)
|
| 31 |
+
gpu_memory_gb = gpu_props.total_memory / (1024**3)
|
| 32 |
+
logger.info(f"GPU {i}: {gpu_props.name} - {gpu_memory_gb:.1f}GB VRAM")
|
| 33 |
+
if gpu_memory_gb >= 20: # Minimum for V2
|
| 34 |
+
logger.info(f"GPU {i} has sufficient VRAM for Matrix-Game V2")
|
| 35 |
+
else:
|
| 36 |
+
logger.warning(f"GPU {i} may not have sufficient VRAM (24GB+ recommended)")
|
| 37 |
+
return True
|
| 38 |
+
else:
|
| 39 |
+
logger.error("No CUDA GPUs detected. Matrix-Game V2 requires NVIDIA GPU with CUDA support.")
|
| 40 |
+
return False
|
| 41 |
+
except ImportError:
|
| 42 |
+
logger.error("PyTorch not available - cannot check GPU status")
|
| 43 |
+
return False
|
| 44 |
+
except Exception as e:
|
| 45 |
+
logger.error(f"Error checking GPU availability: {e}")
|
| 46 |
+
return False
|
| 47 |
+
|
| 48 |
def install_apex():
|
| 49 |
+
"""Install NVIDIA Apex at runtime with CUDA support for Matrix-Game V2"""
|
| 50 |
try:
|
| 51 |
+
logger.info("Installing NVIDIA Apex (required for Matrix-Game V2)...")
|
| 52 |
|
| 53 |
# Clone the Apex repository
|
| 54 |
subprocess.check_call([
|
|
|
|
| 82 |
|
| 83 |
except subprocess.CalledProcessError as e:
|
| 84 |
logger.error(f"Failed to install Apex. Error: {e}")
|
| 85 |
+
logger.error("Matrix-Game V2 requires Apex for optimal performance")
|
| 86 |
+
raise RuntimeError(f"Apex installation failed: {e}")
|
| 87 |
except Exception as e:
|
| 88 |
logger.error(f"Unexpected error during Apex installation: {e}")
|
| 89 |
+
raise RuntimeError(f"Apex installation failed: {e}")
|
| 90 |
finally:
|
| 91 |
# Change back to original directory
|
| 92 |
+
try:
|
| 93 |
+
os.chdir("..")
|
| 94 |
+
except:
|
| 95 |
+
pass
|
| 96 |
+
|
| 97 |
+
# Check GPU availability and install dependencies
|
| 98 |
+
if not check_gpu_availability():
|
| 99 |
+
logger.error("Cannot start server: Matrix-Game V2 requires NVIDIA GPU with CUDA support")
|
| 100 |
+
sys.exit(1)
|
| 101 |
|
| 102 |
install_apex()
|
| 103 |
|
|
|
|
| 166 |
path_arg = "" # or f"--path /{os.environ.get('SPACE_ID', '')}" if needed
|
| 167 |
|
| 168 |
# Construct and run the command
|
| 169 |
+
cmd = f"{sys.executable} api_server.py --host 0.0.0.0 --port {port} {path_arg}"
|
| 170 |
print(f"Running command: {cmd}")
|
| 171 |
subprocess.run(cmd, shell=True)
|
| 172 |
|