"src/targets/vscode:/vscode.git/clone" did not exist on "953da9428cbb9e62d3e18f74ab10e07968dc3b94"
utils.py 18.8 KB
Newer Older
PengGao's avatar
PengGao committed
1
import glob
helloyongyang's avatar
helloyongyang committed
2
import os
PengGao's avatar
PengGao committed
3
4
import random
import subprocess
PengGao's avatar
PengGao committed
5
6
from typing import Optional

PengGao's avatar
PengGao committed
7
8
9
import imageio
import imageio_ffmpeg as ffmpeg
import numpy as np
10
import safetensors
helloyongyang's avatar
helloyongyang committed
11
import torch
12
import torch.distributed as dist
helloyongyang's avatar
helloyongyang committed
13
import torchvision
14
15
from einops import rearrange
from loguru import logger
helloyongyang's avatar
helloyongyang committed
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


def seed_all(seed):
    random.seed(seed)
    os.environ["PYTHONHASHSEED"] = str(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    torch.cuda.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)
    torch.backends.cudnn.benchmark = False
    torch.backends.cudnn.deterministic = True


def save_videos_grid(videos: torch.Tensor, path: str, rescale=False, n_rows=1, fps=24):
    """save videos by video tensor
       copy from https://github.com/guoyww/AnimateDiff/blob/e92bd5671ba62c0d774a32951453e328018b7c5b/animatediff/utils/util.py#L61

    Args:
        videos (torch.Tensor): video tensor predicted by the model
        path (str): path to save video
        rescale (bool, optional): rescale the video tensor from [-1, 1] to  . Defaults to False.
        n_rows (int, optional): Defaults to 1.
        fps (int, optional): video save fps. Defaults to 8.
    """
    videos = rearrange(videos, "b c t h w -> t b c h w")
    outputs = []
    for x in videos:
        x = torchvision.utils.make_grid(x, nrow=n_rows)
        x = x.transpose(0, 1).transpose(1, 2).squeeze(-1)
        if rescale:
            x = (x + 1.0) / 2.0  # -1,1 -> 0,1
        x = torch.clamp(x, 0, 1)
        x = (x * 255).numpy().astype(np.uint8)
        outputs.append(x)

    os.makedirs(os.path.dirname(path), exist_ok=True)
    imageio.mimsave(path, outputs, fps=fps)


def cache_video(
    tensor,
PengGao's avatar
PengGao committed
57
    save_file: str,
helloyongyang's avatar
helloyongyang committed
58
59
60
61
62
63
64
    fps=30,
    suffix=".mp4",
    nrow=8,
    normalize=True,
    value_range=(-1, 1),
    retry=5,
):
GoatWu's avatar
GoatWu committed
65
66
67
68
69
70
71
72
    save_dir = os.path.dirname(save_file)
    try:
        if not os.path.exists(save_dir):
            os.makedirs(save_dir, exist_ok=True)
    except Exception as e:
        logger.error(f"Failed to create directory: {save_dir}, error: {e}")
        return None

helloyongyang's avatar
helloyongyang committed
73
74
75
76
77
78
79
    cache_file = save_file

    # save to cache
    error = None
    for _ in range(retry):
        try:
            # preprocess
PengGao's avatar
PengGao committed
80
            tensor = tensor.clamp(min(value_range), max(value_range))  # type: ignore
helloyongyang's avatar
helloyongyang committed
81
            tensor = torch.stack(
Dongz's avatar
Dongz committed
82
                [torchvision.utils.make_grid(u, nrow=nrow, normalize=normalize, value_range=value_range) for u in tensor.unbind(2)],
helloyongyang's avatar
helloyongyang committed
83
84
85
86
87
88
89
90
91
                dim=1,
            ).permute(1, 2, 3, 0)
            tensor = (tensor * 255).type(torch.uint8).cpu()

            # write video
            writer = imageio.get_writer(cache_file, fps=fps, codec="libx264", quality=8)
            for frame in tensor.numpy():
                writer.append_data(frame)
            writer.close()
gushiqiao's avatar
gushiqiao committed
92
93
            del tensor
            torch.cuda.empty_cache()
helloyongyang's avatar
helloyongyang committed
94
95
96
97
98
            return cache_file
        except Exception as e:
            error = e
            continue
    else:
root's avatar
root committed
99
        logger.info(f"cache_video failed, error: {error}", flush=True)
helloyongyang's avatar
helloyongyang committed
100
        return None
PengGao's avatar
PengGao committed
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


def vae_to_comfyui_image(vae_output: torch.Tensor) -> torch.Tensor:
    """
    Convert VAE decoder output to ComfyUI Image format

    Args:
        vae_output: VAE decoder output tensor, typically in range [-1, 1]
                    Shape: [B, C, T, H, W] or [B, C, H, W]

    Returns:
        ComfyUI Image tensor in range [0, 1]
        Shape: [B, H, W, C] for single frame or [B*T, H, W, C] for video
    """
    # Handle video tensor (5D) vs image tensor (4D)
    if vae_output.dim() == 5:
        # Video tensor: [B, C, T, H, W]
        B, C, T, H, W = vae_output.shape
        # Reshape to [B*T, C, H, W] for processing
        vae_output = vae_output.permute(0, 2, 1, 3, 4).reshape(B * T, C, H, W)

    # Normalize from [-1, 1] to [0, 1]
    images = (vae_output + 1) / 2

    # Clamp values to [0, 1]
    images = torch.clamp(images, 0, 1)

    # Convert from [B, C, H, W] to [B, H, W, C]
    images = images.permute(0, 2, 3, 1).cpu()

    return images


LiangLiu's avatar
LiangLiu committed
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
def vae_to_comfyui_image_inplace(vae_output: torch.Tensor) -> torch.Tensor:
    """
    Convert VAE decoder output to ComfyUI Image format (inplace operation)

    Args:
        vae_output: VAE decoder output tensor, typically in range [-1, 1]
                    Shape: [B, C, T, H, W] or [B, C, H, W]
                    WARNING: This tensor will be modified in-place!

    Returns:
        ComfyUI Image tensor in range [0, 1]
        Shape: [B, H, W, C] for single frame or [B*T, H, W, C] for video
        Note: The returned tensor is the same object as input (modified in-place)
    """
    # Handle video tensor (5D) vs image tensor (4D)
    if vae_output.dim() == 5:
        # Video tensor: [B, C, T, H, W]
        B, C, T, H, W = vae_output.shape
        # Reshape to [B*T, C, H, W] for processing (inplace view)
        vae_output = vae_output.permute(0, 2, 1, 3, 4).contiguous().view(B * T, C, H, W)

    # Normalize from [-1, 1] to [0, 1] (inplace)
    vae_output.add_(1).div_(2)

    # Clamp values to [0, 1] (inplace)
    vae_output.clamp_(0, 1)

    # Convert from [B, C, H, W] to [B, H, W, C] and move to CPU
    vae_output = vae_output.permute(0, 2, 3, 1).cpu()

    return vae_output


PengGao's avatar
PengGao committed
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
def save_to_video(
    images: torch.Tensor,
    output_path: str,
    fps: float = 24.0,
    method: str = "imageio",
    lossless: bool = False,
    output_pix_fmt: Optional[str] = "yuv420p",
) -> None:
    """
    Save ComfyUI Image tensor to video file

    Args:
        images: ComfyUI Image tensor [N, H, W, C] in range [0, 1]
        output_path: Path to save the video
        fps: Frames per second
        method: Save method - "imageio" or "ffmpeg"
        lossless: Whether to use lossless encoding (ffmpeg method only)
        output_pix_fmt: Pixel format for output (ffmpeg method only)
    """
    assert images.dim() == 4 and images.shape[-1] == 3, "Input must be [N, H, W, C] with C=3"

    # Ensure output directory exists
    os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True)

    if method == "imageio":
        # Convert to uint8
193
194
        # frames = (images * 255).cpu().numpy().astype(np.uint8)
        frames = (images * 255).to(torch.uint8).cpu().numpy()
PengGao's avatar
PengGao committed
195
196
197
198
        imageio.mimsave(output_path, frames, fps=fps)  # type: ignore

    elif method == "ffmpeg":
        # Convert to numpy and scale to [0, 255]
199
200
        # frames = (images * 255).cpu().numpy().clip(0, 255).astype(np.uint8)
        frames = (images * 255).clamp(0, 255).to(torch.uint8).cpu().numpy()
PengGao's avatar
PengGao committed
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

        # Convert RGB to BGR for OpenCV/FFmpeg
        frames = frames[..., ::-1].copy()

        N, height, width, _ = frames.shape

        # Ensure even dimensions for x264
        width += width % 2
        height += height % 2

        # Get ffmpeg executable from imageio_ffmpeg
        ffmpeg_exe = ffmpeg.get_ffmpeg_exe()

        if lossless:
            command = [
                ffmpeg_exe,
                "-y",  # Overwrite output file if it exists
                "-f",
                "rawvideo",
                "-s",
                f"{int(width)}x{int(height)}",
                "-pix_fmt",
                "bgr24",
                "-r",
                f"{fps}",
                "-loglevel",
                "error",
                "-threads",
                "4",
                "-i",
                "-",  # Input from pipe
                "-vcodec",
                "libx264rgb",
                "-crf",
                "0",
                "-an",  # No audio
                output_path,
            ]
        else:
            command = [
                ffmpeg_exe,
                "-y",  # Overwrite output file if it exists
                "-f",
                "rawvideo",
                "-s",
                f"{int(width)}x{int(height)}",
                "-pix_fmt",
                "bgr24",
                "-r",
                f"{fps}",
                "-loglevel",
                "error",
                "-threads",
                "4",
                "-i",
                "-",  # Input from pipe
                "-vcodec",
                "libx264",
                "-pix_fmt",
                output_pix_fmt,
                "-an",  # No audio
                output_path,
            ]

        # Run FFmpeg
        process = subprocess.Popen(
            command,
            stdin=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )

        if process.stdin is None:
            raise BrokenPipeError("No stdin buffer received.")

        # Write frames to FFmpeg
        for frame in frames:
            # Pad frame if needed
            if frame.shape[0] < height or frame.shape[1] < width:
                padded = np.zeros((height, width, 3), dtype=np.uint8)
                padded[: frame.shape[0], : frame.shape[1]] = frame
                frame = padded
            process.stdin.write(frame.tobytes())

        process.stdin.close()
        process.wait()

        if process.returncode != 0:
            error_output = process.stderr.read().decode() if process.stderr else "Unknown error"
            raise RuntimeError(f"FFmpeg failed with error: {error_output}")

    else:
        raise ValueError(f"Unknown save method: {method}")
293
294


295
296
297
298
299
300
301
def remove_substrings_from_keys(original_dict, substr):
    new_dict = {}
    for key, value in original_dict.items():
        new_dict[key.replace(substr, "")] = value
    return new_dict


302
def find_torch_model_path(config, ckpt_config_key=None, filename=None, subdir=["original", "fp8", "int8", "distill_models", "distill_fp8", "distill_int8"]):
303
304
305
306
307
308
    if ckpt_config_key and config.get(ckpt_config_key, None) is not None:
        return config.get(ckpt_config_key)

    paths_to_check = [
        os.path.join(config.model_path, filename),
    ]
gushiqiao's avatar
gushiqiao committed
309
310
    if isinstance(subdir, list):
        for sub in subdir:
311
            paths_to_check.insert(0, os.path.join(config.model_path, sub, filename))
gushiqiao's avatar
gushiqiao committed
312
    else:
313
        paths_to_check.insert(0, os.path.join(config.model_path, subdir, filename))
gushiqiao's avatar
gushiqiao committed
314

315
316
317
318
319
320
    for path in paths_to_check:
        if os.path.exists(path):
            return path
    raise FileNotFoundError(f"PyTorch model file '{filename}' not found.\nPlease download the model from https://huggingface.co/lightx2v/ or specify the model path in the configuration file.")


321
def find_hf_model_path(config, model_path, ckpt_config_key=None, subdir=["original", "fp8", "int8", "distill_models", "distill_fp8", "distill_int8"]):
322
323
324
    if ckpt_config_key and config.get(ckpt_config_key, None) is not None:
        return config.get(ckpt_config_key)

helloyongyang's avatar
helloyongyang committed
325
    paths_to_check = [model_path]
gushiqiao's avatar
gushiqiao committed
326
327
    if isinstance(subdir, list):
        for sub in subdir:
328
            paths_to_check.insert(0, os.path.join(model_path, sub))
gushiqiao's avatar
gushiqiao committed
329
    else:
330
        paths_to_check.insert(0, os.path.join(model_path, subdir))
331
332
333
334
335
336
    for path in paths_to_check:
        safetensors_pattern = os.path.join(path, "*.safetensors")
        safetensors_files = glob.glob(safetensors_pattern)
        if safetensors_files:
            return path
    raise FileNotFoundError(f"No Hugging Face model files (.safetensors) found.\nPlease download the model from: https://huggingface.co/lightx2v/ or specify the model path in the configuration file.")
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
def find_gguf_model_path(config, ckpt_config_key=None, subdir=None):
    gguf_path = config.get(ckpt_config_key, None)
    if gguf_path is None:
        raise ValueError(f"GGUF path not found in config with key '{ckpt_config_key}'")
    if not isinstance(gguf_path, str) or not gguf_path.endswith(".gguf"):
        raise ValueError(f"GGUF path must be a string ending with '.gguf', got: {gguf_path}")
    if os.sep in gguf_path or (os.altsep and os.altsep in gguf_path):
        if os.path.exists(gguf_path):
            logger.info(f"Found GGUF model file in: {gguf_path}")
            return os.path.abspath(gguf_path)
        else:
            raise FileNotFoundError(f"GGUF file not found at path: {gguf_path}")
    else:
        # It's just a filename, search in predefined paths
        paths_to_check = [config.model_path]
        if subdir:
            paths_to_check.append(os.path.join(config.model_path, subdir))

        for path in paths_to_check:
            gguf_file_path = os.path.join(path, gguf_path)
            gguf_file = glob.glob(gguf_file_path)
            if gguf_file:
                logger.info(f"Found GGUF model file in: {gguf_file_path}")
                return gguf_file_path

    raise FileNotFoundError(f"No GGUF model files (.gguf) found.\nPlease download the model from: https://huggingface.co/lightx2v/ or specify the model path in the configuration file.")


367
368
369
def load_safetensors(in_path, remove_key=None, include_keys=None):
    """加载safetensors文件或目录,支持按key包含筛选或排除"""
    include_keys = include_keys or []
370
    if os.path.isdir(in_path):
371
        return load_safetensors_from_dir(in_path, remove_key, include_keys)
372
    elif os.path.isfile(in_path):
373
        return load_safetensors_from_path(in_path, remove_key, include_keys)
374
375
376
377
    else:
        raise ValueError(f"{in_path} does not exist")


378
379
380
def load_safetensors_from_path(in_path, remove_key=None, include_keys=None):
    """从单个safetensors文件加载权重,支持按key筛选"""
    include_keys = include_keys or []
381
382
383
    tensors = {}
    with safetensors.safe_open(in_path, framework="pt", device="cpu") as f:
        for key in f.keys():
384
385
386
387
388
389
390
391
            # 优先处理include_keys:如果非空,只保留包含任意指定key的条目
            if include_keys:
                if any(inc_key in key for inc_key in include_keys):
                    tensors[key] = f.get_tensor(key)
            # 否则使用remove_key排除
            else:
                if not (remove_key and remove_key in key):
                    tensors[key] = f.get_tensor(key)
392
393
394
    return tensors


395
396
397
def load_safetensors_from_dir(in_dir, remove_key=None, include_keys=None):
    """从目录加载所有safetensors文件,支持按key筛选"""
    include_keys = include_keys or []
398
    tensors = {}
399
400
401
402
    safetensors_files = os.listdir(in_dir)
    safetensors_files = [f for f in safetensors_files if f.endswith(".safetensors")]
    for f in safetensors_files:
        tensors.update(load_safetensors_from_path(os.path.join(in_dir, f), remove_key, include_keys))
403
404
405
    return tensors


406
407
408
def load_pt_safetensors(in_path, remove_key=None, include_keys=None):
    """加载pt/pth或safetensors权重,支持按key筛选"""
    include_keys = include_keys or []
409
410
411
    ext = os.path.splitext(in_path)[-1]
    if ext in (".pt", ".pth", ".tar"):
        state_dict = torch.load(in_path, map_location="cpu", weights_only=True)
412
413
414
415
416
417
418
419
420
421
422
        # 处理筛选逻辑
        keys_to_keep = []
        for key in state_dict.keys():
            if include_keys:
                if any(inc_key in key for inc_key in include_keys):
                    keys_to_keep.append(key)
            else:
                if not (remove_key and remove_key in key):
                    keys_to_keep.append(key)
        # 只保留符合条件的key
        state_dict = {k: state_dict[k] for k in keys_to_keep}
423
    else:
424
        state_dict = load_safetensors(in_path, remove_key, include_keys)
425
426
427
    return state_dict


428
def load_weights(checkpoint_path, cpu_offload=False, remove_key=None, load_from_rank0=False, include_keys=None):
gushiqiao's avatar
gushiqiao committed
429
    if not dist.is_initialized() or not load_from_rank0:
gushiqiao's avatar
gushiqiao committed
430
        # Single GPU mode
431
        logger.info(f"Loading weights from {checkpoint_path}")
432
        cpu_weight_dict = load_pt_safetensors(checkpoint_path, remove_key, include_keys)
gushiqiao's avatar
Fix  
gushiqiao committed
433
        return cpu_weight_dict
434

gushiqiao's avatar
gushiqiao committed
435
    # Multi-GPU mode
gushiqiao's avatar
gushiqiao committed
436
    is_weight_loader = False
437
    current_rank = dist.get_rank()
gushiqiao's avatar
gushiqiao committed
438
439
    if current_rank == 0:
        is_weight_loader = True
440
441

    cpu_weight_dict = {}
gushiqiao's avatar
Fix  
gushiqiao committed
442
    if is_weight_loader:
443
        logger.info(f"Loading weights from {checkpoint_path}")
LiangLiu's avatar
LiangLiu committed
444
        cpu_weight_dict = load_pt_safetensors(checkpoint_path, remove_key)
445
446

    meta_dict = {}
gushiqiao's avatar
gushiqiao committed
447
    if is_weight_loader:
448
449
450
        for key, tensor in cpu_weight_dict.items():
            meta_dict[key] = {"shape": tensor.shape, "dtype": tensor.dtype}

gushiqiao's avatar
gushiqiao committed
451
    obj_list = [meta_dict] if is_weight_loader else [None]
452

453
454
    src_global_rank = 0
    dist.broadcast_object_list(obj_list, src=src_global_rank)
455
456
    synced_meta_dict = obj_list[0]

gushiqiao's avatar
gushiqiao committed
457
458
459
460
461
462
463
464
    if cpu_offload:
        target_device = "cpu"
        distributed_weight_dict = {key: torch.empty(meta["shape"], dtype=meta["dtype"], device=target_device) for key, meta in synced_meta_dict.items()}
        dist.barrier()
    else:
        target_device = torch.device(f"cuda:{current_rank}")
        distributed_weight_dict = {key: torch.empty(meta["shape"], dtype=meta["dtype"], device=target_device) for key, meta in synced_meta_dict.items()}
        dist.barrier(device_ids=[torch.cuda.current_device()])
465
466

    for key in sorted(synced_meta_dict.keys()):
gushiqiao's avatar
gushiqiao committed
467
468
        tensor_to_broadcast = distributed_weight_dict[key]
        if is_weight_loader:
gushiqiao's avatar
gushiqiao committed
469
            tensor_to_broadcast.copy_(cpu_weight_dict[key], non_blocking=True)
gushiqiao's avatar
gushiqiao committed
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485

        if cpu_offload:
            if is_weight_loader:
                gpu_tensor = tensor_to_broadcast.cuda()
                dist.broadcast(gpu_tensor, src=src_global_rank)
                tensor_to_broadcast.copy_(gpu_tensor.cpu(), non_blocking=True)
                del gpu_tensor
                torch.cuda.empty_cache()
            else:
                gpu_tensor = torch.empty_like(tensor_to_broadcast, device="cuda")
                dist.broadcast(gpu_tensor, src=src_global_rank)
                tensor_to_broadcast.copy_(gpu_tensor.cpu(), non_blocking=True)
                del gpu_tensor
                torch.cuda.empty_cache()
        else:
            dist.broadcast(tensor_to_broadcast, src=src_global_rank)
486

gushiqiao's avatar
gushiqiao committed
487
    if is_weight_loader:
488
489
        del cpu_weight_dict

gushiqiao's avatar
gushiqiao committed
490
491
492
    if cpu_offload:
        torch.cuda.empty_cache()

gushiqiao's avatar
gushiqiao committed
493
494
    logger.info(f"Weights distributed across {dist.get_world_size()} devices on {target_device}")
    return distributed_weight_dict
495
496


sandy's avatar
sandy committed
497
def masks_like(tensor, zero=False, generator=None, p=0.2, prev_len=1):
498
499
500
501
502
503
    assert isinstance(tensor, torch.Tensor)
    out = torch.ones_like(tensor)
    if zero:
        if generator is not None:
            random_num = torch.rand(1, generator=generator, device=generator.device).item()
            if random_num < p:
sandy's avatar
sandy committed
504
                out[:, :prev_len] = torch.zeros_like(out[:, :prev_len])
505
        else:
sandy's avatar
sandy committed
506
            out[:, :prev_len] = torch.zeros_like(out[:, :prev_len])
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
    return out


def best_output_size(w, h, dw, dh, expected_area):
    # float output size
    ratio = w / h
    ow = (expected_area * ratio) ** 0.5
    oh = expected_area / ow

    # process width first
    ow1 = int(ow // dw * dw)
    oh1 = int(expected_area / ow1 // dh * dh)
    assert ow1 % dw == 0 and oh1 % dh == 0 and ow1 * oh1 <= expected_area
    ratio1 = ow1 / oh1

    # process height first
    oh2 = int(oh // dh * dh)
    ow2 = int(expected_area / oh2 // dw * dw)
    assert oh2 % dh == 0 and ow2 % dw == 0 and ow2 * oh2 <= expected_area
    ratio2 = ow2 / oh2

    # compare ratios
    if max(ratio / ratio1, ratio1 / ratio) < max(ratio / ratio2, ratio2 / ratio):
        return ow1, oh1
    else:
        return ow2, oh2