-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathapi_server.py
More file actions
2321 lines (1878 loc) · 90 KB
/
api_server.py
File metadata and controls
2321 lines (1878 loc) · 90 KB
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
VerseCrafter Standalone API Server
A Flask-based REST API server that provides endpoints for the VerseCrafter
video generation pipeline. This can be used as an alternative to ComfyUI.
Usage:
# Multi-GPU mode (recommended) - model loads on GPUs 1-7 at startup, GPU 0 for other tasks
python api_server.py --port 8188 --num_gpus 8
# Single GPU mode - model loads after render, unloads after generation
python api_server.py --port 8188 --num_gpus 1
GPU Allocation:
Multi-GPU (num_gpus > 1):
- GPU 0: Reserved for preprocessing (Step 1-3) and rendering (Step 5)
- GPUs 1-N: Model server for video generation (Step 6)
- Model starts loading immediately at server startup (parallel)
Single GPU (num_gpus == 1):
- GPU 0: Shared for all tasks (sequential)
- Step 1-3 (preprocess) → Step 5 (render) → load model → Step 6 (generate) → unload model
- Model loads AFTER render completes, unloads AFTER generation to free GPU
Endpoints:
POST /api/preprocess - Run Steps 1-3 (depth, segmentation, gaussian fitting)
POST /api/render - Run Step 5 (render 4D control maps)
POST /api/generate - Run Step 6 (generate video)
POST /api/workflow - Run full postprocess workflow (Steps 5-6)
GET /api/status/<task_id> - Check task status
GET /api/download/<path> - Download output file
"""
import os
import sys
import json
import uuid
import time
import threading
import argparse
from pathlib import Path
from typing import Dict, Any, Optional
from dataclasses import dataclass, asdict
from enum import Enum
from flask import Flask, request, jsonify, send_file
from flask_cors import CORS
from werkzeug.utils import secure_filename
import logging
# Setup logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
# Add project paths
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
INFERENCE_DIR = os.path.join(PROJECT_ROOT, 'inference')
VIDEOX_FUN_PATH = os.path.join(PROJECT_ROOT, 'third_party/VideoX-Fun')
sys.path.insert(0, PROJECT_ROOT)
sys.path.insert(0, INFERENCE_DIR)
if VIDEOX_FUN_PATH not in sys.path:
sys.path.insert(0, VIDEOX_FUN_PATH)
# Conda environment configuration
# Set CONDA_ENV to specify which conda environment to use for inference scripts
# If not set, uses the current Python interpreter
CONDA_ENV = os.environ.get('VERSECRAFTER_CONDA_ENV', '') # e.g., 'videoxfun' or 'versecrafter'
CONDA_PREFIX = os.environ.get('CONDA_PREFIX', '')
def get_python_cmd():
"""Get the Python command to use for subprocess calls."""
if CONDA_ENV:
# Use conda run to execute in specific environment
return ['conda', 'run', '-n', CONDA_ENV, '--no-capture-output', 'python']
else:
# Use current Python interpreter
return [sys.executable]
class TaskStatus(Enum):
PENDING = "pending"
RUNNING = "running"
COMPLETED = "completed"
FAILED = "failed"
@dataclass
class Task:
id: str
type: str
status: TaskStatus
progress: float
message: str
result: Optional[Dict[str, Any]] = None
error: Optional[str] = None
created_at: float = 0
completed_at: Optional[float] = None
# Global task storage
tasks: Dict[str, Task] = {}
task_lock = threading.Lock()
# ============================================================================
# Global Model State (for preloaded model mode)
# ============================================================================
_pipeline = None
_vae = None
_device = None
_weight_dtype = None
_model_config = {}
_model_loaded = False
_model_loading = False # True when model is being loaded in background
_model_load_error = None # Error message if loading failed
_model_load_thread = None # Background loading thread
_loading_lock = threading.Lock()
# Startup configuration (stored for async loading)
_startup_config = {
'num_gpus': 1,
'model_path': 'model/VerseCrafter',
'base_model_path': 'model/Wan2.1-T2V-14B',
'config_path': 'config/wan2.1/wan_civitai.yaml',
'gpu_memory_mode': 'model_full_load',
}
# Model server configuration (for multi-GPU mode)
_model_server_url = None # Set when model server is started
_model_server_process = None # Subprocess running the model server
_model_server_port = 8189
app = Flask(__name__)
CORS(app, resources={r"/*": {"origins": "*"}})
# Add CORS headers to all responses
@app.after_request
def after_request(response):
response.headers.add('Access-Control-Allow-Origin', '*')
response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization,Accept,User-Agent')
response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
return response
def create_task(task_type: str) -> Task:
"""Create a new task."""
task = Task(
id=str(uuid.uuid4()),
type=task_type,
status=TaskStatus.PENDING,
progress=0.0,
message="Task created",
created_at=time.time()
)
with task_lock:
tasks[task.id] = task
return task
def update_task(task_id: str, **kwargs):
"""Update task status."""
with task_lock:
if task_id in tasks:
task = tasks[task_id]
for key, value in kwargs.items():
if hasattr(task, key):
setattr(task, key, value)
def run_preprocess(task_id: str, params: Dict[str, Any]):
"""Run preprocessing pipeline (Steps 1-3)."""
try:
update_task(task_id, status=TaskStatus.RUNNING, progress=0.0, message="Starting preprocessing...")
import os
# IMPORTANT: Use GPU 0 for preprocessing to avoid conflict with model server
# Model server uses GPUs 1-7, preprocessing uses GPU 0
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
logger.info(f"[Preprocess Task {task_id}] Using GPU 0 for preprocessing (CUDA_VISIBLE_DEVICES=0)")
import numpy as np
import torch
from PIL import Image
# Import inference modules
from moge.model import import_model_class_by_version
from moge.utils.vis import colorize_depth
from grounded_sam2_infer import ImageSegmenter
from fit_3D_gaussian import (
get_point_cloud_from_depth, fit_3d_gaussian, tensor_to_json_serializable
)
import cv2
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Extract parameters
image_path = params['image_path']
output_dir = params['output_dir']
text_prompt = params.get('text_prompt', 'person . car .')
model_version = params.get('model_version', 'v2')
use_fp16 = params.get('use_fp16', True)
resolution_level = params.get('resolution_level', 9)
output_path = Path(output_dir)
output_path.mkdir(parents=True, exist_ok=True)
# Step 1: Depth Estimation
update_task(task_id, progress=0.1, message="Step 1: Running depth estimation...")
DEFAULT_MODELS = {
"v1": "Ruicheng/moge-vitl",
"v2": "Ruicheng/moge-2-vitl-normal",
}
model_class = import_model_class_by_version(model_version)
depth_model = model_class.from_pretrained(DEFAULT_MODELS[model_version]).to(device).eval()
if use_fp16:
depth_model.half()
image = cv2.cvtColor(cv2.imread(image_path), cv2.COLOR_BGR2RGB)
height, width = image.shape[:2]
image_tensor = torch.tensor(image / 255, dtype=torch.float32, device=device).permute(2, 0, 1)
with torch.no_grad():
output = depth_model.infer(image_tensor, resolution_level=resolution_level, use_fp16=use_fp16)
depth = output['depth'].cpu().numpy()
intrinsics = output['intrinsics'].cpu().numpy()
# Replace infinities
valid_mask = np.isfinite(depth) & (depth > 0)
if np.any(valid_mask):
depth[~valid_mask] = float(np.max(depth[valid_mask])) + 10.0
# Save depth data
depth_dir = output_path / "estimated_depth"
depth_dir.mkdir(exist_ok=True)
np.savez_compressed(str(depth_dir / "depth_intrinsics.npz"),
depth=depth.astype(np.float16), intrinsic=intrinsics.astype(np.float16))
cv2.imwrite(str(depth_dir / "depth_vis.png"), cv2.cvtColor(colorize_depth(depth), cv2.COLOR_RGB2BGR))
update_task(task_id, progress=0.4, message="Step 2: Running segmentation...")
# Step 2: Segmentation
segmenter = ImageSegmenter(device=str(device))
image_source, detections, masks = segmenter.segment_image(
image_path=image_path,
text_prompt=text_prompt,
box_threshold=params.get('box_threshold', 0.4),
min_area_ratio=params.get('min_area_ratio', 0.003),
max_area_ratio=params.get('max_area_ratio', 0.2)
)
if not detections or len(detections.get('masks', [])) == 0:
update_task(task_id, status=TaskStatus.FAILED, error="No objects detected")
return
# Save masks
masks_dir = output_path / "object_mask" / "masks"
masks_dir.mkdir(parents=True, exist_ok=True)
for idx, (mask, label) in enumerate(zip(detections['masks'], detections['labels'])):
mask_path = masks_dir / f"mask_{idx+1:02d}_{label}.png"
Image.fromarray(mask).save(str(mask_path))
# Save visualization
vis_image = segmenter.visualize_results(image_source, detections)
Image.fromarray(vis_image).save(str(output_path / "object_mask" / "visualization.png"))
update_task(task_id, progress=0.7, message="Step 3: Fitting 3D Gaussians...")
# Step 3: 3D Gaussian Fitting
depth_tensor = torch.from_numpy(depth.astype(np.float32)).to(device)
intrinsic_tensor = torch.from_numpy(intrinsics.astype(np.float32)).to(device)
# Denormalize intrinsics
if intrinsic_tensor[0, 0].item() < 10:
intrinsic_tensor[0, 0] *= width
intrinsic_tensor[1, 1] *= height
intrinsic_tensor[0, 2] *= width
intrinsic_tensor[1, 2] *= height
extrinsic = torch.eye(4, device=device, dtype=torch.float32)
gaussian_params = {}
for idx, (mask, label) in enumerate(zip(detections['masks'], detections['labels'])):
obj_id = idx + 1
mask_binary = (mask > 127).astype(np.uint8)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
mask_eroded = cv2.erode(mask_binary * 255, kernel, iterations=1)
mask_tensor = torch.from_numpy(mask_eroded > 127).to(device)
if mask_tensor.shape != (height, width):
mask_resized = cv2.resize(mask_eroded, (width, height), interpolation=cv2.INTER_NEAREST)
mask_tensor = torch.from_numpy(mask_resized > 127).to(device)
points = get_point_cloud_from_depth(depth_tensor, intrinsic_tensor, extrinsic, mask_tensor)
if len(points) < 10:
continue
mean, cov = fit_3d_gaussian(points, device)
if mean is None:
continue
gaussian_params[obj_id] = {
"label": label,
"mean": tensor_to_json_serializable(mean),
"cov": tensor_to_json_serializable(cov),
"num_points": len(points),
}
# Save Gaussian parameters
gaussian_dir = output_path / "fitted_3D_gaussian"
gaussian_dir.mkdir(exist_ok=True)
output_data = {
"image_info": {"resolution": [width, height]},
"camera_info": {
"intrinsic": tensor_to_json_serializable(intrinsic_tensor),
"extrinsic": tensor_to_json_serializable(extrinsic)
},
"gaussian_params": gaussian_params,
"num_objects": len(gaussian_params),
}
with open(gaussian_dir / "gaussian_params.json", 'w') as f:
json.dump(output_data, f, indent=2)
# Save input image copy
Image.fromarray(image).save(str(output_path / "input_image.png"))
update_task(task_id,
status=TaskStatus.COMPLETED,
progress=1.0,
message="Preprocessing complete!",
result={
"output_dir": str(output_path),
"depth_npz": str(depth_dir / "depth_intrinsics.npz"),
"masks_dir": str(masks_dir),
"gaussian_json": str(gaussian_dir / "gaussian_params.json"),
"num_objects": len(gaussian_params)
},
completed_at=time.time())
# Note: Model loading now starts at server startup (async), not here.
# This allows model to load in parallel with preprocessing from the beginning.
logger.info("Preprocessing complete!")
except Exception as e:
import traceback
update_task(task_id, status=TaskStatus.FAILED, error=f"{str(e)}\n{traceback.format_exc()}")
def run_render(task_id: str, params: Dict[str, Any]):
"""Run 4D control map rendering (Step 5)."""
try:
update_task(task_id, status=TaskStatus.RUNNING, progress=0.0, message="Checking input files...")
import subprocess
logger.info(f"[Render Task {task_id}] Starting with params: {params}")
# Validate required files exist
required_files = [
('image_path', params.get('image_path')),
('depth_npz_path', params.get('depth_npz_path')),
('camera_trajectory_path', params.get('camera_trajectory_path')),
('gaussian_trajectory_path', params.get('gaussian_trajectory_path')),
]
for name, path in required_files:
if path and not os.path.exists(path):
error_msg = f"Required file not found: {name} = {path}"
logger.error(f"[Render Task {task_id}] {error_msg}")
update_task(task_id, status=TaskStatus.FAILED, error=error_msg)
return
# Check masks directory
masks_dir = params.get('masks_dir')
if masks_dir and not os.path.exists(masks_dir):
error_msg = f"Masks directory not found: {masks_dir}"
logger.error(f"[Render Task {task_id}] {error_msg}")
update_task(task_id, status=TaskStatus.FAILED, error=error_msg)
return
update_task(task_id, progress=0.05, message="Starting rendering...")
# Build command using appropriate Python environment
python_cmd = get_python_cmd()
cmd = python_cmd + [
os.path.join(INFERENCE_DIR, "rendering_4D_control_maps.py"),
"--png_path", params['image_path'],
"--npz_path", params['depth_npz_path'],
"--mask_dir", params['masks_dir'],
"--trajectory_npz", params['camera_trajectory_path'],
"--ellipsoid_json", params['gaussian_trajectory_path'],
"--output_dir", params['output_dir'],
]
if 'fps' in params:
cmd.extend(["--fps", str(params['fps'])])
# Note: video_length is NOT passed to rendering script - it's determined by trajectory file
# The trajectory file (custom_camera_trajectory.npz) contains the extrinsics for all frames
logger.info(f"[Render Task {task_id}] Running command: {' '.join(cmd)}")
logger.info(f"[Render Task {task_id}] Working directory: {PROJECT_ROOT}")
# Set environment variables to fix MKL threading issue
env = os.environ.copy()
env['MKL_THREADING_LAYER'] = 'GNU' # Fix MKL + libgomp compatibility
env['MKL_SERVICE_FORCE_INTEL'] = '1'
# IMPORTANT: Use GPU 0 for rendering to avoid conflict with model server
# Model server uses GPUs 1-7, rendering uses GPU 0
env['CUDA_VISIBLE_DEVICES'] = '0'
logger.info(f"[Render Task {task_id}] Using GPU 0 for rendering (CUDA_VISIBLE_DEVICES=0)")
# Run rendering with real-time output logging
# Important: Set cwd to PROJECT_ROOT so relative imports work correctly
process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, # Combine stderr with stdout
text=True,
bufsize=1, # Line buffered
cwd=PROJECT_ROOT, # Set working directory to project root
env=env # Use modified environment
)
# Read output line by line for progress tracking
output_lines = []
frame_count = params.get('video_length', 49)
for line in process.stdout:
line = line.strip()
output_lines.append(line)
logger.info(f"[Render Task {task_id}] {line}")
# Try to parse progress from output
if 'frame' in line.lower() or 'rendering' in line.lower():
# Try to extract frame number for progress estimation
import re
match = re.search(r'(\d+)\s*/\s*(\d+)', line)
if match:
current = int(match.group(1))
total = int(match.group(2))
progress = current / total
update_task(task_id, progress=progress, message=f"Rendering frame {current}/{total}")
else:
# Generic progress update
update_task(task_id, message=f"Rendering: {line[:50]}...")
process.wait()
if process.returncode != 0:
error_msg = '\n'.join(output_lines[-20:]) # Last 20 lines
logger.error(f"[Render Task {task_id}] Failed with code {process.returncode}: {error_msg}")
update_task(task_id, status=TaskStatus.FAILED, error=error_msg)
return
logger.info(f"[Render Task {task_id}] Completed successfully")
update_task(task_id,
status=TaskStatus.COMPLETED,
progress=1.0,
message="Rendering complete!",
result={"output_dir": params['output_dir']},
completed_at=time.time())
# For single GPU mode: Start loading model after render completes
# (GPU is now free since render finished)
num_gpus = _startup_config.get('num_gpus', 1)
if num_gpus == 1 and not _model_loaded and not _model_loading:
logger.info("=" * 60)
logger.info("[Single GPU] Render complete. Starting model loading...")
logger.info("=" * 60)
start_model_loading_async()
except Exception as e:
import traceback
update_task(task_id, status=TaskStatus.FAILED, error=f"{str(e)}\n{traceback.format_exc()}")
# ============================================================================
# Model Loading and In-Process Generation (for preload mode)
# ============================================================================
def load_model(
model_name: str = "model/Wan2.1-T2V-14B",
transformer_path: str = "model/VerseCrafter",
config_path: str = "config/wan2.1/wan_civitai.yaml",
num_gpus: int = 1,
gpu_memory_mode: str = "model_full_load",
enable_teacache: bool = True,
teacache_threshold: float = 0.10,
num_skip_start_steps: int = 5,
):
"""Load the VerseCrafter model into memory for fast repeated generation.
Args:
model_name: Path to the base Wan model
transformer_path: Path to VerseCrafter transformer weights
config_path: Path to config file
num_gpus: Number of GPUs to use (1 for single GPU, >1 for multi-GPU)
gpu_memory_mode: Memory optimization mode
enable_teacache: Whether to enable TeaCache acceleration
teacache_threshold: TeaCache threshold (higher = faster but less accurate)
num_skip_start_steps: Number of initial steps to skip TeaCache
"""
global _pipeline, _vae, _device, _weight_dtype, _model_config, _model_loaded
if _model_loaded:
logger.info("Model already loaded, skipping...")
return True
with _loading_lock:
if _model_loaded:
return True
try:
logger.info("=" * 60)
logger.info("Loading VerseCrafter model...")
logger.info(f" num_gpus: {num_gpus}")
logger.info(f" gpu_memory_mode: {gpu_memory_mode}")
logger.info("=" * 60)
import warnings
warnings.filterwarnings("ignore", category=FutureWarning)
import torch
import numpy as np
from diffusers import FlowMatchEulerDiscreteScheduler
from omegaconf import OmegaConf
from transformers import AutoTokenizer
from videox_fun.dist import set_multi_gpus_devices, shard_model
from videox_fun.models import AutoencoderKLWan, WanT5EncoderModel
from videox_fun.utils.fp8_optimization import (
convert_model_weight_to_float8,
convert_weight_dtype_wrapper,
replace_parameters_by_name
)
from videox_fun.utils.utils import filter_kwargs
from videox_fun.utils.fm_solvers import FlowDPMSolverMultistepScheduler
from videox_fun.utils.fm_solvers_unipc import FlowUniPCMultistepScheduler
from versecrafter.models import VerseCrafterWanTransformer3DModel
from versecrafter.pipeline import WanVerseCrafterPipeline
# Calculate ulysses_degree and ring_degree from num_gpus
# IMPORTANT: ulysses_degree × ring_degree MUST equal num_gpus
if num_gpus == 1:
ulysses_degree = 1
ring_degree = 1
elif num_gpus == 2:
ulysses_degree = 1
ring_degree = 2
elif num_gpus == 3:
ulysses_degree = 1
ring_degree = 3
elif num_gpus == 4:
ulysses_degree = 2
ring_degree = 2
elif num_gpus == 5:
ulysses_degree = 1
ring_degree = 5
elif num_gpus == 6:
ulysses_degree = 2
ring_degree = 3
elif num_gpus == 7:
ulysses_degree = 1
ring_degree = 7
elif num_gpus == 8:
ulysses_degree = 2
ring_degree = 4
else:
# Find optimal factorization: ulysses × ring = num_gpus
import math
sqrt_n = int(math.sqrt(num_gpus))
for i in range(sqrt_n, 0, -1):
if num_gpus % i == 0:
ulysses_degree = i
ring_degree = num_gpus // i
break
else:
ulysses_degree = 1
ring_degree = num_gpus
logger.info(f" ulysses_degree: {ulysses_degree}, ring_degree: {ring_degree}")
# Configuration
_weight_dtype = torch.bfloat16
geoada_context_scale = 1.00
geoada_in_dim = 128
sampler_name = "Flow_Unipc"
shift = 16
fsdp_dit = False
fsdp_text_encoder = True
compile_dit = False
teacache_offload = False
cfg_skip_ratio = 0
# Set up device for multi-GPU
_device = set_multi_gpus_devices(ulysses_degree, ring_degree)
logger.info(f"Using device: {_device}")
# Load config
config = OmegaConf.load(config_path)
transformer_additional_kwargs = OmegaConf.to_container(config['transformer_additional_kwargs'])
if geoada_in_dim is not None:
transformer_additional_kwargs['geoada_in_dim'] = geoada_in_dim
# Load transformer
logger.info(f"Loading transformer from: {transformer_path}")
if os.path.isdir(transformer_path):
transformer = VerseCrafterWanTransformer3DModel.from_pretrained(
transformer_path,
transformer_additional_kwargs=transformer_additional_kwargs,
low_cpu_mem_usage=True,
torch_dtype=_weight_dtype,
)
else:
transformer = VerseCrafterWanTransformer3DModel.from_pretrained(
os.path.join(model_name, config['transformer_additional_kwargs'].get('transformer_subpath', 'transformer')),
transformer_additional_kwargs=transformer_additional_kwargs,
low_cpu_mem_usage=True,
torch_dtype=_weight_dtype,
)
if transformer_path is not None:
logger.info(f"Loading weights from checkpoint: {transformer_path}")
if transformer_path.endswith("safetensors"):
from safetensors.torch import load_file
state_dict = load_file(transformer_path)
else:
state_dict = torch.load(transformer_path, map_location="cpu")
state_dict = state_dict["state_dict"] if "state_dict" in state_dict else state_dict
m, u = transformer.load_state_dict(state_dict, strict=False)
logger.info(f"Loaded weights: missing={len(m)}, unexpected={len(u)}")
# Load VAE
logger.info("Loading VAE...")
_vae = AutoencoderKLWan.from_pretrained(
os.path.join(model_name, config['vae_kwargs'].get('vae_subpath', 'vae')),
additional_kwargs=OmegaConf.to_container(config['vae_kwargs']),
).to(_weight_dtype)
# Load Tokenizer
logger.info("Loading tokenizer...")
tokenizer = AutoTokenizer.from_pretrained(
os.path.join(model_name, config['text_encoder_kwargs'].get('tokenizer_subpath', 'tokenizer')),
)
# Load Text encoder
logger.info("Loading text encoder...")
text_encoder = WanT5EncoderModel.from_pretrained(
os.path.join(model_name, config['text_encoder_kwargs'].get('text_encoder_subpath', 'text_encoder')),
additional_kwargs=OmegaConf.to_container(config['text_encoder_kwargs']),
low_cpu_mem_usage=True,
torch_dtype=_weight_dtype,
)
text_encoder = text_encoder.eval()
# Get Scheduler
logger.info("Loading scheduler...")
scheduler_dict = {
"Flow": FlowMatchEulerDiscreteScheduler,
"Flow_Unipc": FlowUniPCMultistepScheduler,
"Flow_DPM++": FlowDPMSolverMultistepScheduler,
}
Chosen_Scheduler = scheduler_dict[sampler_name]
if sampler_name in ["Flow_Unipc", "Flow_DPM++"]:
config['scheduler_kwargs']['shift'] = 1
scheduler = Chosen_Scheduler(
**filter_kwargs(Chosen_Scheduler, OmegaConf.to_container(config['scheduler_kwargs']))
)
# Create Pipeline
logger.info("Creating pipeline...")
_pipeline = WanVerseCrafterPipeline(
transformer=transformer,
vae=_vae,
tokenizer=tokenizer,
text_encoder=text_encoder,
scheduler=scheduler,
)
# Multi-GPU setup
if ulysses_degree > 1 or ring_degree > 1:
from functools import partial
transformer.enable_multi_gpus_inference()
if fsdp_dit:
shard_fn = partial(shard_model, device_id=_device, param_dtype=_weight_dtype)
_pipeline.transformer = shard_fn(_pipeline.transformer)
logger.info("Enabled FSDP for DIT")
if fsdp_text_encoder:
shard_fn = partial(shard_model, device_id=_device, param_dtype=_weight_dtype)
_pipeline.text_encoder = shard_fn(_pipeline.text_encoder)
logger.info("Enabled FSDP for text encoder")
if compile_dit:
for i in range(len(_pipeline.transformer.blocks)):
_pipeline.transformer.blocks[i] = torch.compile(_pipeline.transformer.blocks[i])
logger.info("Enabled torch.compile")
# GPU memory mode
if gpu_memory_mode == "sequential_cpu_offload":
replace_parameters_by_name(transformer, ["modulation",], device=_device)
transformer.freqs = transformer.freqs.to(device=_device)
_pipeline.enable_sequential_cpu_offload(device=_device)
elif gpu_memory_mode == "model_cpu_offload_and_qfloat8":
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=_device)
convert_weight_dtype_wrapper(transformer, _weight_dtype)
_pipeline.enable_model_cpu_offload(device=_device)
elif gpu_memory_mode == "model_cpu_offload":
_pipeline.enable_model_cpu_offload(device=_device)
elif gpu_memory_mode == "model_full_load_and_qfloat8":
convert_model_weight_to_float8(transformer, exclude_module_name=["modulation",], device=_device)
convert_weight_dtype_wrapper(transformer, _weight_dtype)
_pipeline.to(device=_device)
else:
_pipeline.to(device=_device)
# Store config for later use
_model_config = {
'shift': shift,
'geoada_context_scale': geoada_context_scale,
'enable_teacache': enable_teacache,
'teacache_threshold': teacache_threshold,
'num_skip_start_steps': num_skip_start_steps,
'teacache_offload': teacache_offload,
'cfg_skip_ratio': cfg_skip_ratio,
'ulysses_degree': ulysses_degree,
'ring_degree': ring_degree,
'num_gpus': num_gpus,
}
_model_loaded = True
logger.info("=" * 60)
logger.info("Model loaded successfully!")
logger.info("=" * 60)
return True
except Exception as e:
logger.error(f"Failed to load model: {e}")
import traceback
traceback.print_exc()
return False
def _async_load_model_worker():
"""Worker function for background model loading."""
global _model_loading, _model_loaded, _model_load_error
try:
logger.info("=" * 60)
logger.info("Background model loading started...")
logger.info("=" * 60)
success = load_model(
model_name=_startup_config['base_model_path'],
transformer_path=_startup_config['model_path'],
config_path=_startup_config['config_path'],
num_gpus=_startup_config['num_gpus'],
gpu_memory_mode=_startup_config['gpu_memory_mode'],
)
if success:
logger.info("=" * 60)
logger.info("Background model loading completed successfully!")
logger.info("=" * 60)
else:
_model_load_error = "Model loading returned False"
logger.error("=" * 60)
logger.error("Background model loading FAILED!")
logger.error("Video generation will fall back to subprocess mode (slower)")
logger.error("=" * 60)
except Exception as e:
import traceback
_model_load_error = f"{str(e)}\n{traceback.format_exc()}"
logger.error("=" * 60)
logger.error(f"Background model loading FAILED with exception: {e}")
logger.error("Video generation will fall back to subprocess mode (slower)")
logger.error("=" * 60)
finally:
_model_loading = False
def start_model_loading_async():
"""Start model loading in background (non-blocking).
This is called automatically after preprocessing completes.
The model loading happens in parallel with user's trajectory editing.
For single GPU: Loads model directly in a background thread.
For multi-GPU: Starts a model server via torchrun.
"""
global _model_loading, _model_load_thread
with _loading_lock:
# Skip if already loaded or loading
if _model_loaded:
logger.info("Model already loaded, skipping async load")
return
if _model_loading:
logger.info("Model already loading in background, skipping")
return
if _model_server_url is not None:
logger.info("Model server already started, skipping")
return
num_gpus = _startup_config.get('num_gpus', 1)
if num_gpus > 1:
# Multi-GPU: Start model server via torchrun
logger.info(f"Multi-GPU mode (num_gpus={num_gpus}), starting model server...")
start_model_server_async()
else:
# Single GPU: Load in background thread
_model_loading = True
_model_load_thread = threading.Thread(target=_async_load_model_worker, daemon=True)
_model_load_thread.start()
logger.info("Started background model loading thread (single GPU mode)")
def wait_for_model_loaded(timeout: float = None) -> bool:
"""Wait for background model loading to complete.
Args:
timeout: Maximum seconds to wait. None means wait forever.
Returns:
True if model is loaded successfully, False otherwise.
"""
global _model_load_thread
if _model_loaded:
return True
if _model_load_thread is not None and _model_load_thread.is_alive():
logger.info(f"Waiting for background model loading to complete (timeout={timeout})...")
_model_load_thread.join(timeout)
if _model_load_thread.is_alive():
logger.warning("Timeout waiting for model loading")
return False
if _model_loaded:
logger.info("Model loading completed, ready for generation")
return True
else:
if _model_load_error:
logger.error(f"Model loading failed: {_model_load_error}")
return False
def get_model_loading_status() -> dict:
"""Get current model loading status."""
return {
"loaded": _model_loaded,
"loading": _model_loading,
"error": _model_load_error,
"model_server_url": _model_server_url,
}
def unload_model():
"""Unload the model from GPU memory (for single GPU mode).
This frees GPU memory so other tasks (preprocessing, rendering) can use it.
"""
global _pipeline, _vae, _device, _weight_dtype, _model_config, _model_loaded
if not _model_loaded:
logger.info("Model not loaded, nothing to unload")
return
with _loading_lock:
if not _model_loaded:
return
try:
logger.info("=" * 60)
logger.info("Unloading model to free GPU memory...")
logger.info("=" * 60)
import torch
import gc
# Delete pipeline and VAE
if _pipeline is not None:
del _pipeline
_pipeline = None
if _vae is not None:
del _vae
_vae = None
# Clear CUDA cache
if torch.cuda.is_available():
torch.cuda.empty_cache()
# Force garbage collection
gc.collect()
_model_loaded = False
_model_config.clear()
logger.info("Model unloaded successfully, GPU memory freed")
except Exception as e:
logger.error(f"Error unloading model: {e}")
import traceback
traceback.print_exc()
# ============================================================================
# Model Server Management (for multi-GPU mode via torchrun)
# ============================================================================
def start_model_server_async():
"""Start the model server via torchrun in background (for multi-GPU).
This launches model_server.py with torchrun, which supports multi-GPU.
The model server provides an HTTP API for video generation.
GPU Allocation:
- GPU 0: Reserved for preprocessing and rendering
- GPUs 1-N: Used by model server for video generation
"""
global _model_server_url, _model_server_process
if _model_server_url is not None:
logger.info("Model server already started, skipping")
return
num_gpus = _startup_config.get('num_gpus', 1)
if num_gpus <= 1:
logger.info("Single GPU mode, no need for model server")
return
import subprocess
# Reserve GPU 0 for rendering, use remaining GPUs for model server
# e.g., num_gpus=8 → model_gpus=7 (GPUs 1-7), GPU 0 for rendering
model_gpus = num_gpus - 1
if model_gpus < 1:
model_gpus = 1
# Create CUDA_VISIBLE_DEVICES string: "1,2,3,4,5,6,7" (excluding GPU 0)
gpu_list = ','.join(str(i) for i in range(1, num_gpus))
logger.info("=" * 60)
logger.info(f"Starting model server with {model_gpus} GPUs via torchrun...")
logger.info(f" GPU allocation: GPU 0 reserved for rendering")
logger.info(f" Model server GPUs: {gpu_list}")
logger.info("=" * 60)
# Build torchrun command
model_server_script = os.path.join(PROJECT_ROOT, 'model_server.py')
cmd = [
'torchrun',
f'--nproc_per_node={model_gpus}',
model_server_script,
'--port', str(_model_server_port),
'--model_path', _startup_config['model_path'],
'--base_model_path', _startup_config['base_model_path'],
'--config_path', _startup_config['config_path'],
'--gpu_memory_mode', _startup_config['gpu_memory_mode'],
]
logger.info(f"Command: {' '.join(cmd)}")
# Set environment variables
env = os.environ.copy()
env['MKL_THREADING_LAYER'] = 'GNU'
env['CUDA_VISIBLE_DEVICES'] = gpu_list # Exclude GPU 0
try:
# Start the model server process
_model_server_process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1,
cwd=PROJECT_ROOT,
env=env
)
# Start a thread to log the output
def log_output():
for line in _model_server_process.stdout:
logger.info(f"[ModelServer] {line.strip()}")