Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- FlowCache/FlowCache4MAGI-1-dev-V1/downloads/_hf_raw/ckpt/t5/t5-v1_1-xxl/tokenizer_config.json +1 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/__pycache__/__init__.cpython-310.pyc +0 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/__pycache__/__init__.cpython-312.pyc +0 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/common/__init__.py +37 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/common/__pycache__/__init__.cpython-310.pyc +0 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/common/__pycache__/__init__.cpython-312.pyc +0 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/common/__pycache__/common_utils.cpython-310.pyc +0 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/common/__pycache__/common_utils.cpython-312.pyc +0 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/common/__pycache__/config.cpython-310.pyc +0 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/common/__pycache__/config.cpython-312.pyc +0 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/common/__pycache__/dataclass.cpython-310.pyc +0 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/common/__pycache__/dataclass.cpython-312.pyc +0 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/common/__pycache__/logger.cpython-310.pyc +0 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/common/__pycache__/logger.cpython-312.pyc +0 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/common/__pycache__/timer.cpython-310.pyc +0 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/common/__pycache__/timer.cpython-312.pyc +0 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/common/common_utils.py +42 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/common/config.py +180 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/common/dataclass.py +97 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/common/logger.py +51 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/common/timer.py +85 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/checkpoint/__init__.py +17 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/checkpoint/__pycache__/__init__.cpython-310.pyc +0 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/checkpoint/__pycache__/__init__.cpython-312.pyc +0 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/checkpoint/__pycache__/checkpointing.cpython-310.pyc +0 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/checkpoint/__pycache__/checkpointing.cpython-312.pyc +0 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/checkpoint/checkpointing.py +180 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/distributed/__init__.py +73 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/distributed/__pycache__/__init__.cpython-310.pyc +0 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/distributed/__pycache__/__init__.cpython-312.pyc +0 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/distributed/__pycache__/dist_utils.cpython-310.pyc +0 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/distributed/__pycache__/dist_utils.cpython-312.pyc +0 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/distributed/__pycache__/parallel_state.cpython-310.pyc +0 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/distributed/__pycache__/parallel_state.cpython-312.pyc +0 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/distributed/dist_utils.py +92 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/distributed/parallel_state.py +672 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/parallelism/__init__.py +27 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/parallelism/__pycache__/__init__.cpython-310.pyc +0 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/parallelism/__pycache__/__init__.cpython-312.pyc +0 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/parallelism/__pycache__/context_parallel.cpython-310.pyc +0 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/parallelism/__pycache__/context_parallel.cpython-312.pyc +0 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/parallelism/__pycache__/pipeline_parallel.cpython-310.pyc +0 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/parallelism/__pycache__/pipeline_parallel.cpython-312.pyc +0 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/parallelism/__pycache__/tile_parallel.cpython-310.pyc +0 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/parallelism/__pycache__/tile_parallel.cpython-312.pyc +0 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/parallelism/context_parallel.py +673 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/parallelism/pipeline_parallel.py +123 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/parallelism/tile_parallel.py +448 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/model/dit/__init__.py +18 -0
- FlowCache/FlowCache4MAGI-1-dev-V1/inference/model/dit/__pycache__/__init__.cpython-310.pyc +0 -0
FlowCache/FlowCache4MAGI-1-dev-V1/downloads/_hf_raw/ckpt/t5/t5-v1_1-xxl/tokenizer_config.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"eos_token": "</s>", "unk_token": "<unk>", "pad_token": "<pad>", "extra_ids": 100, "additional_special_tokens": ["<extra_id_0>", "<extra_id_1>", "<extra_id_2>", "<extra_id_3>", "<extra_id_4>", "<extra_id_5>", "<extra_id_6>", "<extra_id_7>", "<extra_id_8>", "<extra_id_9>", "<extra_id_10>", "<extra_id_11>", "<extra_id_12>", "<extra_id_13>", "<extra_id_14>", "<extra_id_15>", "<extra_id_16>", "<extra_id_17>", "<extra_id_18>", "<extra_id_19>", "<extra_id_20>", "<extra_id_21>", "<extra_id_22>", "<extra_id_23>", "<extra_id_24>", "<extra_id_25>", "<extra_id_26>", "<extra_id_27>", "<extra_id_28>", "<extra_id_29>", "<extra_id_30>", "<extra_id_31>", "<extra_id_32>", "<extra_id_33>", "<extra_id_34>", "<extra_id_35>", "<extra_id_36>", "<extra_id_37>", "<extra_id_38>", "<extra_id_39>", "<extra_id_40>", "<extra_id_41>", "<extra_id_42>", "<extra_id_43>", "<extra_id_44>", "<extra_id_45>", "<extra_id_46>", "<extra_id_47>", "<extra_id_48>", "<extra_id_49>", "<extra_id_50>", "<extra_id_51>", "<extra_id_52>", "<extra_id_53>", "<extra_id_54>", "<extra_id_55>", "<extra_id_56>", "<extra_id_57>", "<extra_id_58>", "<extra_id_59>", "<extra_id_60>", "<extra_id_61>", "<extra_id_62>", "<extra_id_63>", "<extra_id_64>", "<extra_id_65>", "<extra_id_66>", "<extra_id_67>", "<extra_id_68>", "<extra_id_69>", "<extra_id_70>", "<extra_id_71>", "<extra_id_72>", "<extra_id_73>", "<extra_id_74>", "<extra_id_75>", "<extra_id_76>", "<extra_id_77>", "<extra_id_78>", "<extra_id_79>", "<extra_id_80>", "<extra_id_81>", "<extra_id_82>", "<extra_id_83>", "<extra_id_84>", "<extra_id_85>", "<extra_id_86>", "<extra_id_87>", "<extra_id_88>", "<extra_id_89>", "<extra_id_90>", "<extra_id_91>", "<extra_id_92>", "<extra_id_93>", "<extra_id_94>", "<extra_id_95>", "<extra_id_96>", "<extra_id_97>", "<extra_id_98>", "<extra_id_99>"], "model_max_length": 512, "name_or_path": "t5-small"}
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (188 Bytes). View file
|
|
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (188 Bytes). View file
|
|
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/common/__init__.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2025 SandAI. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from .common_utils import divide, env_is_true, set_random_seed
|
| 16 |
+
from .config import EngineConfig, MagiConfig, ModelConfig, RuntimeConfig
|
| 17 |
+
from .dataclass import InferenceParams, ModelMetaArgs, PackedCoreAttnParams, PackedCrossAttnParams
|
| 18 |
+
from .logger import magi_logger, print_per_rank, print_rank_0
|
| 19 |
+
from .timer import event_path_timer
|
| 20 |
+
|
| 21 |
+
__all__ = [
|
| 22 |
+
"MagiConfig",
|
| 23 |
+
"ModelConfig",
|
| 24 |
+
"EngineConfig",
|
| 25 |
+
"RuntimeConfig",
|
| 26 |
+
"magi_logger",
|
| 27 |
+
"print_per_rank",
|
| 28 |
+
"print_rank_0",
|
| 29 |
+
"event_path_timer",
|
| 30 |
+
"divide",
|
| 31 |
+
"env_is_true",
|
| 32 |
+
"set_random_seed",
|
| 33 |
+
"PackedCoreAttnParams",
|
| 34 |
+
"PackedCrossAttnParams",
|
| 35 |
+
"ModelMetaArgs",
|
| 36 |
+
"InferenceParams",
|
| 37 |
+
]
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/common/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (764 Bytes). View file
|
|
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/common/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (790 Bytes). View file
|
|
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/common/__pycache__/common_utils.cpython-310.pyc
ADDED
|
Binary file (1.04 kB). View file
|
|
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/common/__pycache__/common_utils.cpython-312.pyc
ADDED
|
Binary file (1.52 kB). View file
|
|
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/common/__pycache__/config.cpython-310.pyc
ADDED
|
Binary file (6.42 kB). View file
|
|
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/common/__pycache__/config.cpython-312.pyc
ADDED
|
Binary file (9.41 kB). View file
|
|
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/common/__pycache__/dataclass.cpython-310.pyc
ADDED
|
Binary file (3.06 kB). View file
|
|
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/common/__pycache__/dataclass.cpython-312.pyc
ADDED
|
Binary file (4.1 kB). View file
|
|
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/common/__pycache__/logger.cpython-310.pyc
ADDED
|
Binary file (1.26 kB). View file
|
|
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/common/__pycache__/logger.cpython-312.pyc
ADDED
|
Binary file (2.14 kB). View file
|
|
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/common/__pycache__/timer.cpython-310.pyc
ADDED
|
Binary file (2.58 kB). View file
|
|
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/common/__pycache__/timer.cpython-312.pyc
ADDED
|
Binary file (3.07 kB). View file
|
|
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/common/common_utils.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2025 SandAI. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import os
|
| 16 |
+
import random
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
import torch
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def env_is_true(env_name: str) -> bool:
|
| 23 |
+
return str(os.environ.get(env_name, "0")).lower() in {"1", "true", "yes", "y", "on", "enabled"}
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def divide(numerator, denominator):
|
| 27 |
+
assert numerator % denominator == 0, "{} is not divisible by {}".format(numerator, denominator)
|
| 28 |
+
return numerator // denominator
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def set_random_seed(seed):
|
| 32 |
+
"""Set random seed.
|
| 33 |
+
|
| 34 |
+
Args:
|
| 35 |
+
seed (int): Seed to be used.
|
| 36 |
+
"""
|
| 37 |
+
assert seed is not None, "Please provide a seed in config.json"
|
| 38 |
+
random.seed(seed)
|
| 39 |
+
np.random.seed(seed)
|
| 40 |
+
torch.manual_seed(seed)
|
| 41 |
+
torch.cuda.manual_seed_all(seed)
|
| 42 |
+
return seed
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/common/config.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2025 SandAI. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import dataclasses
|
| 16 |
+
import json
|
| 17 |
+
import os
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@dataclasses.dataclass
|
| 23 |
+
class ModelConfig:
|
| 24 |
+
model_name: str
|
| 25 |
+
|
| 26 |
+
# Transformer
|
| 27 |
+
num_layers: int = None # Number of transformer layers.
|
| 28 |
+
hidden_size: int = None # Transformer hidden size.
|
| 29 |
+
ffn_hidden_size: int = None # Transformer Feed-Forward Network hidden size
|
| 30 |
+
num_attention_heads: int = None # Number of transformer attention heads.
|
| 31 |
+
num_query_groups: int = 1 # Number of query groups, which used for GQA
|
| 32 |
+
kv_channels: int = None # Projection weights dimension in multi-head attention
|
| 33 |
+
layernorm_epsilon: float = 1e-6 # Epsilon for layer norm and RMS norm.
|
| 34 |
+
apply_layernorm_1p: bool = False # Adjust LayerNorm weights which improves numerical stability.
|
| 35 |
+
x_rescale_factor: float = 1.0
|
| 36 |
+
half_channel_vae: bool = False
|
| 37 |
+
params_dtype: torch.dtype = None
|
| 38 |
+
|
| 39 |
+
# Embedding
|
| 40 |
+
patch_size: int = 2 # (latent) patch size for DiT patch embedding layer
|
| 41 |
+
t_patch_size: int = 1 # (latent) patch size for t dim patch embedding layer
|
| 42 |
+
in_channels: int = 4 # latent input channel for DiT
|
| 43 |
+
out_channels: int = 4 # latent output channel for DiT
|
| 44 |
+
cond_hidden_ratio: float = 0.25
|
| 45 |
+
caption_channels: int = 4096
|
| 46 |
+
caption_max_length: int = 800
|
| 47 |
+
xattn_cond_hidden_ratio: float = 1.0
|
| 48 |
+
cond_gating_ratio: float = 1.0
|
| 49 |
+
gated_linear_unit: bool = False
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@dataclasses.dataclass
|
| 53 |
+
class RuntimeConfig:
|
| 54 |
+
# Inference settings such as cfg, kv range, clean t, etc.
|
| 55 |
+
cfg_number: int = None # Number of CFG
|
| 56 |
+
cfg_t_range: list = dataclasses.field(
|
| 57 |
+
default_factory=lambda: [0, 0.0217, 0.1000, 0.3, 0.999]
|
| 58 |
+
) # CFG t-range of each scales
|
| 59 |
+
prev_chunk_scales: list = dataclasses.field(
|
| 60 |
+
default_factory=lambda: [1.5, 1.5, 1.5, 1.5, 1.5]
|
| 61 |
+
) # CFG scales of previous chunks
|
| 62 |
+
text_scales: list = dataclasses.field(default_factory=lambda: [7.5, 7.5, 7.5, 7.5, 7.5]) # CFG scales of text
|
| 63 |
+
|
| 64 |
+
noise2clean_kvrange: list = dataclasses.field(default_factory=list) # Range of kv for noise2clean chunks
|
| 65 |
+
clean_chunk_kvrange: int = -1 # Range of kv for clean chunks
|
| 66 |
+
clean_t: float = 1.0 # timestep for clean chunks
|
| 67 |
+
|
| 68 |
+
# Video settings
|
| 69 |
+
seed: int = 1234 # Random seed used for python, numpy, pytorch, and cuda.
|
| 70 |
+
num_frames: int = 128
|
| 71 |
+
video_size_h: int = None
|
| 72 |
+
video_size_w: int = None
|
| 73 |
+
num_steps: int = 64 # Number of steps for the diffusion model
|
| 74 |
+
window_size: int = 4 # Window size for the diffusion model
|
| 75 |
+
fps: int = 24 # Frames per second
|
| 76 |
+
chunk_width: int = 6 # Clip width for the diffusion model
|
| 77 |
+
|
| 78 |
+
# Checkpoint, includes t5, vae, dit, etc.
|
| 79 |
+
t5_pretrained: str = None # Path to load pretrained T5 model.
|
| 80 |
+
t5_device: str = "cuda" # Device for T5 model to run on.
|
| 81 |
+
vae_pretrained: str = None # Path to load pretrained VAE model.
|
| 82 |
+
scale_factor: float = 0.18215 # Scale factor for the vae
|
| 83 |
+
temporal_downsample_factor: int = 4 # Temporal downsample factor for the vae
|
| 84 |
+
load: str = None # Directory containing a model checkpoint.
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
@dataclasses.dataclass
|
| 88 |
+
class EngineConfig:
|
| 89 |
+
# Parallism strategy
|
| 90 |
+
distributed_backend: str = "nccl" # Choices: ["nccl", "gloo"]
|
| 91 |
+
distributed_timeout_minutes: int = 10 # Timeout minutes for torch.distributed.
|
| 92 |
+
pp_size: int = 1 # Degree of pipeline model parallelism.
|
| 93 |
+
cp_size: int = 1 # Degree of context parallelism.
|
| 94 |
+
cp_strategy: str = "none" # Choices: ["none", "cp_ulysses", "cp_shuffle_overlap"]
|
| 95 |
+
ulysses_overlap_degree: int = 1 # Overlap degree for Ulysses
|
| 96 |
+
|
| 97 |
+
# Quantization
|
| 98 |
+
fp8_quant: bool = False # Enable 8-bit floating point quantization for model weights.
|
| 99 |
+
|
| 100 |
+
# Distillation
|
| 101 |
+
distill_nearly_clean_chunk_threshold: float = 0.3 # Threshold for distilling nearly clean chunks
|
| 102 |
+
shortcut_mode: str = "8,16,16" # Parameters for shortcut mode
|
| 103 |
+
distill: bool = False # Use distill mode
|
| 104 |
+
|
| 105 |
+
# Optimization
|
| 106 |
+
kv_offload: bool = False # Use kv-offload algorithm
|
| 107 |
+
enable_cuda_graph: bool = False # Enable CUDA graph for video generation
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
@dataclasses.dataclass
|
| 111 |
+
class MagiConfig:
|
| 112 |
+
model_config: ModelConfig
|
| 113 |
+
runtime_config: RuntimeConfig
|
| 114 |
+
engine_config: EngineConfig
|
| 115 |
+
|
| 116 |
+
@classmethod
|
| 117 |
+
def _check_missing_fields(cls, config_dict: dict, required_fields: list):
|
| 118 |
+
actual_fields = set(config_dict.keys())
|
| 119 |
+
missing_fields = set(required_fields) - actual_fields
|
| 120 |
+
if missing_fields:
|
| 121 |
+
raise ValueError(f"Missing fields in the configuration file: {', '.join(missing_fields)}")
|
| 122 |
+
|
| 123 |
+
@classmethod
|
| 124 |
+
def _create_nested_config(cls, config_dict: dict, config_name: str, config_cls):
|
| 125 |
+
nested_config_dict = config_dict.get(config_name, {})
|
| 126 |
+
cls._check_missing_fields(nested_config_dict, config_cls.__dataclass_fields__.keys())
|
| 127 |
+
return config_cls(**nested_config_dict)
|
| 128 |
+
|
| 129 |
+
@classmethod
|
| 130 |
+
def _create_config_from_dict(cls, config_dict: dict):
|
| 131 |
+
cls._check_missing_fields(config_dict, cls.__dataclass_fields__.keys())
|
| 132 |
+
|
| 133 |
+
# Create nested configs
|
| 134 |
+
model_config = cls._create_nested_config(config_dict, "model_config", ModelConfig)
|
| 135 |
+
runtime_config = cls._create_nested_config(config_dict, "runtime_config", RuntimeConfig)
|
| 136 |
+
engine_config = cls._create_nested_config(config_dict, "engine_config", EngineConfig)
|
| 137 |
+
|
| 138 |
+
return cls(model_config=model_config, runtime_config=runtime_config, engine_config=engine_config)
|
| 139 |
+
|
| 140 |
+
@classmethod
|
| 141 |
+
def from_json(cls, json_path: str):
|
| 142 |
+
def simple_json_decoder(dct):
|
| 143 |
+
dtype_map = {"torch.bfloat16": torch.bfloat16, "torch.float16": torch.float16, "torch.float32": torch.float32}
|
| 144 |
+
if 'params_dtype' in dct:
|
| 145 |
+
dct['params_dtype'] = dtype_map[dct['params_dtype']]
|
| 146 |
+
return dct
|
| 147 |
+
|
| 148 |
+
with open(json_path, "r") as f:
|
| 149 |
+
config_dict = json.load(f, object_hook=simple_json_decoder)
|
| 150 |
+
magi_config = cls._create_config_from_dict(config_dict)
|
| 151 |
+
|
| 152 |
+
def post_validation(magi_config):
|
| 153 |
+
if magi_config.engine_config.fp8_quant or magi_config.engine_config.distill:
|
| 154 |
+
assert (
|
| 155 |
+
magi_config.runtime_config.cfg_number == 1
|
| 156 |
+
), "Please set `cfg_number: 1` in config.json for distill or quant model"
|
| 157 |
+
else:
|
| 158 |
+
assert magi_config.runtime_config.cfg_number == 3, "Please set `cfg_number: 3` in config.json for base model"
|
| 159 |
+
|
| 160 |
+
post_validation(magi_config)
|
| 161 |
+
|
| 162 |
+
return magi_config
|
| 163 |
+
|
| 164 |
+
def to_json(self, json_path: str):
|
| 165 |
+
class SimpleJSONEncoder(json.JSONEncoder):
|
| 166 |
+
def default(self, obj):
|
| 167 |
+
if isinstance(obj, torch.dtype):
|
| 168 |
+
return str(obj)
|
| 169 |
+
return super().default(obj)
|
| 170 |
+
|
| 171 |
+
# Ensure the directory exists
|
| 172 |
+
os.makedirs(os.path.dirname(json_path), exist_ok=True)
|
| 173 |
+
|
| 174 |
+
config_dict = {
|
| 175 |
+
"model_config": dataclasses.asdict(self.model_config),
|
| 176 |
+
"runtime_config": dataclasses.asdict(self.runtime_config),
|
| 177 |
+
"engine_config": dataclasses.asdict(self.engine_config),
|
| 178 |
+
}
|
| 179 |
+
with open(json_path, "w") as f:
|
| 180 |
+
json.dump(config_dict, f, indent=4, cls=SimpleJSONEncoder)
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/common/dataclass.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2025 SandAI. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from dataclasses import dataclass
|
| 16 |
+
from typing import List
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
import torch
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@dataclass(frozen=True)
|
| 23 |
+
class PackedCoreAttnParams:
|
| 24 |
+
# Packed sequence parameters for core_attn
|
| 25 |
+
q_range: torch.Tensor
|
| 26 |
+
k_range: torch.Tensor
|
| 27 |
+
np_q_range: np.ndarray
|
| 28 |
+
np_k_range: np.ndarray
|
| 29 |
+
max_seqlen_q: int
|
| 30 |
+
max_seqlen_k: int
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@dataclass(frozen=True)
|
| 34 |
+
class PackedCrossAttnParams:
|
| 35 |
+
# Packed sequence parameters for cross_attn
|
| 36 |
+
q_ranges: torch.Tensor = None
|
| 37 |
+
kv_ranges: torch.Tensor = None
|
| 38 |
+
cu_seqlens_q: torch.Tensor = None
|
| 39 |
+
cu_seqlens_kv: torch.Tensor = None
|
| 40 |
+
max_seqlen_q: int = None
|
| 41 |
+
max_seqlen_kv: int = None
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@dataclass(frozen=True)
|
| 45 |
+
class ModelMetaArgs:
|
| 46 |
+
H: int
|
| 47 |
+
W: int
|
| 48 |
+
cp_pad_size: int
|
| 49 |
+
cp_split_sizes: List[int]
|
| 50 |
+
slice_point: int
|
| 51 |
+
denoising_range_num: int
|
| 52 |
+
range_num: int
|
| 53 |
+
extract_prefix_video_feature: bool
|
| 54 |
+
fwd_extra_1st_chunk: bool
|
| 55 |
+
distill_nearly_clean_chunk: bool
|
| 56 |
+
clip_token_nums: int
|
| 57 |
+
enable_cuda_graph: bool
|
| 58 |
+
core_attn_params: PackedCoreAttnParams
|
| 59 |
+
cross_attn_params: PackedCrossAttnParams
|
| 60 |
+
timestep: torch.Tensor
|
| 61 |
+
get_attn_weights_layer_num: int
|
| 62 |
+
save_kvcache_every_forward: bool
|
| 63 |
+
cur_denoise_step: int
|
| 64 |
+
# Includes all chunks of the current sequence
|
| 65 |
+
start_chunk_id: int
|
| 66 |
+
end_chunk_id: int
|
| 67 |
+
compress_kv: bool # use kv cache compression or not
|
| 68 |
+
total_cache_len: int
|
| 69 |
+
budget_cache_len: int
|
| 70 |
+
chunk_num: int
|
| 71 |
+
debug: bool
|
| 72 |
+
near_clean_chunk_idx: int
|
| 73 |
+
|
| 74 |
+
class InferenceParams:
|
| 75 |
+
"""Inference parameters that are passed to the main model in order
|
| 76 |
+
to efficienly calculate and store the context during inference."""
|
| 77 |
+
|
| 78 |
+
def __init__(self, max_batch_size, max_sequence_length):
|
| 79 |
+
self.max_sequence_length = max_sequence_length
|
| 80 |
+
self.max_batch_size = max_batch_size
|
| 81 |
+
self.sequence_len_offset = 0
|
| 82 |
+
self.key_value_memory_dict = {}
|
| 83 |
+
self.update_kv_cache = False
|
| 84 |
+
|
| 85 |
+
self.kv_compressed = False
|
| 86 |
+
|
| 87 |
+
def swap_key_value_dict(self, batch_idx):
|
| 88 |
+
"swap between batches"
|
| 89 |
+
if len(self.key_value_memory_dict) == 0:
|
| 90 |
+
raise ValueError("should not swap when dict in empty")
|
| 91 |
+
|
| 92 |
+
for layer_number in self.key_value_memory_dict.keys():
|
| 93 |
+
inference_key_memory, inference_value_memory = self.key_value_memory_dict[layer_number]
|
| 94 |
+
assert len(batch_idx) == inference_key_memory.shape[1] # make sure batch size is the same
|
| 95 |
+
new_inference_key_memory = inference_key_memory[:, batch_idx]
|
| 96 |
+
new_inference_value_memory = inference_value_memory[:, batch_idx]
|
| 97 |
+
self.key_value_memory_dict[layer_number] = (new_inference_key_memory, new_inference_value_memory)
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/common/logger.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2025 SandAI. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import logging
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class GlobalLogger:
|
| 21 |
+
_logger = None
|
| 22 |
+
|
| 23 |
+
@classmethod
|
| 24 |
+
def get_logger(cls, name=__name__, level=logging.INFO):
|
| 25 |
+
if cls._logger is None:
|
| 26 |
+
cls._logger = logging.getLogger("magi_logger")
|
| 27 |
+
cls._logger.setLevel(logging.INFO)
|
| 28 |
+
|
| 29 |
+
cls._logger.propagate = False
|
| 30 |
+
cls._logger.handlers.clear()
|
| 31 |
+
formatter = logging.Formatter("[%(asctime)s - %(levelname)s] %(message)s")
|
| 32 |
+
handler = logging.StreamHandler()
|
| 33 |
+
handler.setFormatter(formatter)
|
| 34 |
+
cls._logger.addHandler(handler)
|
| 35 |
+
|
| 36 |
+
return cls._logger
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
magi_logger = GlobalLogger.get_logger()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def print_per_rank(message):
|
| 43 |
+
magi_logger.info(message)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def print_rank_0(message):
|
| 47 |
+
if torch.distributed.is_initialized():
|
| 48 |
+
if torch.distributed.get_rank() == 0:
|
| 49 |
+
magi_logger.info(message)
|
| 50 |
+
else:
|
| 51 |
+
magi_logger.info(message)
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/common/timer.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2025 SandAI. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from datetime import datetime
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
|
| 19 |
+
from .logger import print_rank_0
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class EventPathTimer:
|
| 23 |
+
"""
|
| 24 |
+
A lightweight class for recording time without any distributed barrier.
|
| 25 |
+
|
| 26 |
+
This class allows for recording elapsed time between events without requiring
|
| 27 |
+
synchronization across distributed processes. It maintains the previous message
|
| 28 |
+
and time to calculate the duration between consecutive records.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
def __init__(self):
|
| 32 |
+
"""
|
| 33 |
+
Initialize the EventPathTimer.
|
| 34 |
+
|
| 35 |
+
This constructor sets the previous message and time to None, preparing
|
| 36 |
+
the instance for recording events.
|
| 37 |
+
"""
|
| 38 |
+
self.prev_message: str = None
|
| 39 |
+
self.prev_time: datetime = None
|
| 40 |
+
|
| 41 |
+
def reset(self):
|
| 42 |
+
"""
|
| 43 |
+
Reset the recorded message and time.
|
| 44 |
+
|
| 45 |
+
This method clears the previous message and time, allowing for a fresh
|
| 46 |
+
start in recording new events.
|
| 47 |
+
"""
|
| 48 |
+
self.prev_message = None
|
| 49 |
+
self.prev_time = None
|
| 50 |
+
|
| 51 |
+
def synced_record(self, message):
|
| 52 |
+
"""
|
| 53 |
+
Record the current time with a message.
|
| 54 |
+
|
| 55 |
+
Args:
|
| 56 |
+
message (str): A message to log along with the current time.
|
| 57 |
+
|
| 58 |
+
This method synchronizes the CUDA operations, records the current time,
|
| 59 |
+
and calculates the elapsed time since the last recorded message, if any.
|
| 60 |
+
It then logs the elapsed time along with the previous and current messages.
|
| 61 |
+
"""
|
| 62 |
+
torch.cuda.synchronize()
|
| 63 |
+
current_time = datetime.now()
|
| 64 |
+
if self.prev_message is not None:
|
| 65 |
+
print_rank_0(
|
| 66 |
+
f"\nTime Elapsed: [{current_time - self.prev_time}] From [{self.prev_message} ({self.prev_time})] To [{message} ({current_time})]"
|
| 67 |
+
)
|
| 68 |
+
self.prev_message = message
|
| 69 |
+
self.prev_time = current_time
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
_GLOBAL_LIGHT_TIMER = EventPathTimer()
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def event_path_timer() -> EventPathTimer:
|
| 76 |
+
"""Get the current EventPathTimer instance.
|
| 77 |
+
|
| 78 |
+
Returns:
|
| 79 |
+
EventPathTimer: The current EventPathTimer instance.
|
| 80 |
+
|
| 81 |
+
Raises:
|
| 82 |
+
AssertionError: If the EventPathTimer has not been initialized.
|
| 83 |
+
"""
|
| 84 |
+
assert _GLOBAL_LIGHT_TIMER is not None, "light time recorder is not initialized"
|
| 85 |
+
return _GLOBAL_LIGHT_TIMER
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/checkpoint/__init__.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2025 SandAI. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from .checkpointing import load_checkpoint
|
| 16 |
+
|
| 17 |
+
__all__ = ["load_checkpoint"]
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/checkpoint/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (280 Bytes). View file
|
|
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/checkpoint/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (291 Bytes). View file
|
|
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/checkpoint/__pycache__/checkpointing.cpython-310.pyc
ADDED
|
Binary file (5.37 kB). View file
|
|
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/checkpoint/__pycache__/checkpointing.cpython-312.pyc
ADDED
|
Binary file (8.88 kB). View file
|
|
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/checkpoint/checkpointing.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2025 SandAI. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import io
|
| 16 |
+
import json
|
| 17 |
+
import os
|
| 18 |
+
import re
|
| 19 |
+
import subprocess
|
| 20 |
+
from collections import OrderedDict
|
| 21 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 22 |
+
from datetime import datetime
|
| 23 |
+
|
| 24 |
+
import numpy as np
|
| 25 |
+
import torch
|
| 26 |
+
import torch.distributed
|
| 27 |
+
from safetensors.torch import load as load_from_bytes
|
| 28 |
+
from safetensors.torch import load_file
|
| 29 |
+
from tqdm.auto import tqdm
|
| 30 |
+
|
| 31 |
+
import inference.infra.distributed.parallel_state as mpu
|
| 32 |
+
from inference.common import EngineConfig, ModelConfig, RuntimeConfig, print_per_rank, print_rank_0
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _load_shard(shard_path, param_names, num_threads=None):
|
| 36 |
+
zstd_path = shard_path + ".zst"
|
| 37 |
+
if os.path.exists(zstd_path):
|
| 38 |
+
start_time = datetime.now()
|
| 39 |
+
print_per_rank(f"Decompressing {zstd_path} with {num_threads} threads")
|
| 40 |
+
cmd = ["zstd", "-d"]
|
| 41 |
+
if num_threads:
|
| 42 |
+
cmd.extend(["-T", str(num_threads)])
|
| 43 |
+
|
| 44 |
+
process = subprocess.Popen(cmd + ["-c", zstd_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=-1)
|
| 45 |
+
|
| 46 |
+
decompressed_data = process.stdout.read()
|
| 47 |
+
process.stdout.close()
|
| 48 |
+
|
| 49 |
+
retcode = process.wait()
|
| 50 |
+
if retcode != 0:
|
| 51 |
+
raise RuntimeError(f"Decompression failed: {process.stderr.read().decode()}")
|
| 52 |
+
print_per_rank(
|
| 53 |
+
f"Decompressed {zstd_path} with {num_threads} threads, duration: {(datetime.now() - start_time).total_seconds()}s"
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
buffer = io.BytesIO(decompressed_data)
|
| 57 |
+
start_time = datetime.now()
|
| 58 |
+
print_per_rank(f"Loading {shard_path} from zstd file, start time: {start_time}")
|
| 59 |
+
weights = load_from_bytes(buffer.getvalue())
|
| 60 |
+
print_per_rank(f"Loaded {shard_path} from zstd file, duration: {(datetime.now() - start_time).total_seconds()}s")
|
| 61 |
+
buffer.close()
|
| 62 |
+
else:
|
| 63 |
+
weights = load_file(shard_path)
|
| 64 |
+
|
| 65 |
+
return {name: weights[name] for name in param_names}
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def load_sharded_safetensors_parallel_with_progress(checkpoint_dir):
|
| 69 |
+
index_path = os.path.join(checkpoint_dir, "model.safetensors.index.json")
|
| 70 |
+
if not os.path.exists(index_path):
|
| 71 |
+
model_file_path = os.path.join(checkpoint_dir, "model.safetensors")
|
| 72 |
+
state_dict = load_file(model_file_path)
|
| 73 |
+
return state_dict
|
| 74 |
+
|
| 75 |
+
with open(index_path, "r") as f:
|
| 76 |
+
index = json.load(f)
|
| 77 |
+
|
| 78 |
+
state_dict = {}
|
| 79 |
+
shard_map = {}
|
| 80 |
+
|
| 81 |
+
# Group parameters by shard file
|
| 82 |
+
for param_name, shard_file in index["weight_map"].items():
|
| 83 |
+
shard_path = os.path.join(checkpoint_dir, shard_file)
|
| 84 |
+
if shard_path not in shard_map:
|
| 85 |
+
shard_map[shard_path] = []
|
| 86 |
+
shard_map[shard_path].append(param_name)
|
| 87 |
+
|
| 88 |
+
# Load shards in parallel with a progress bar
|
| 89 |
+
with ThreadPoolExecutor() as executor:
|
| 90 |
+
futures = {
|
| 91 |
+
executor.submit(_load_shard, shard_path, param_names): shard_path for shard_path, param_names in shard_map.items()
|
| 92 |
+
}
|
| 93 |
+
pbar = tqdm(futures, desc="Loading shards", total=len(futures))
|
| 94 |
+
for future in pbar:
|
| 95 |
+
result = future.result()
|
| 96 |
+
state_dict.update(result)
|
| 97 |
+
|
| 98 |
+
return state_dict
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def unwrap_model(model):
|
| 102 |
+
return_list = True
|
| 103 |
+
if not isinstance(model, list):
|
| 104 |
+
model = [model]
|
| 105 |
+
return_list = False
|
| 106 |
+
unwrapped_model = []
|
| 107 |
+
for model_module in model:
|
| 108 |
+
while hasattr(model_module, "module"):
|
| 109 |
+
model_module = model_module.module
|
| 110 |
+
unwrapped_model.append(model_module)
|
| 111 |
+
if not return_list:
|
| 112 |
+
return unwrapped_model[0]
|
| 113 |
+
return unwrapped_model
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def _split_state_dict_for_pp(weight_dict: OrderedDict, model_config: ModelConfig):
|
| 117 |
+
num_layers = model_config.num_layers
|
| 118 |
+
partition = mpu.get_pp_world_size()
|
| 119 |
+
|
| 120 |
+
## use partition and num_layers to get current rank layer order
|
| 121 |
+
layers_for_each_stage = np.array_split(range(num_layers), partition)
|
| 122 |
+
current_stage = mpu.get_pp_rank()
|
| 123 |
+
allow_layer_num = layers_for_each_stage[current_stage]
|
| 124 |
+
layer_offset = allow_layer_num[0]
|
| 125 |
+
new_weight_dict = {}
|
| 126 |
+
for k, v in weight_dict.items():
|
| 127 |
+
if "videodit_blocks.layers" in k:
|
| 128 |
+
layer_num = int(re.search(r"videodit_blocks\.layers\.(\d+)", k).group(1))
|
| 129 |
+
if layer_num not in allow_layer_num:
|
| 130 |
+
continue
|
| 131 |
+
## replace the old key name by new layer number
|
| 132 |
+
new_layer_num = layer_num - layer_offset
|
| 133 |
+
new_k = k.replace(f"videodit_blocks.layers.{layer_num}", f"videodit_blocks.layers.{new_layer_num}")
|
| 134 |
+
new_weight_dict[new_k] = v
|
| 135 |
+
else:
|
| 136 |
+
new_weight_dict[k] = v
|
| 137 |
+
return new_weight_dict
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def load_state_dict(runtime_config: RuntimeConfig, engine_config: EngineConfig):
|
| 141 |
+
load_dir = runtime_config.load
|
| 142 |
+
|
| 143 |
+
default_subdir = "inference_weight"
|
| 144 |
+
if engine_config.fp8_quant:
|
| 145 |
+
default_subdir = f"{default_subdir}.fp8"
|
| 146 |
+
if engine_config.distill:
|
| 147 |
+
default_subdir = f"{default_subdir}.distill"
|
| 148 |
+
inference_weight_dir = os.path.join(load_dir, default_subdir)
|
| 149 |
+
|
| 150 |
+
print_rank_0(f"load {default_subdir} weight from {inference_weight_dir}")
|
| 151 |
+
assert (
|
| 152 |
+
os.path.exists(inference_weight_dir) and len(os.listdir(inference_weight_dir)) > 0
|
| 153 |
+
), f"Ckpt directory {inference_weight_dir} does not exist or empty. If you are using fp8_quant, please run calibration first."
|
| 154 |
+
state_dict = load_sharded_safetensors_parallel_with_progress(inference_weight_dir)
|
| 155 |
+
return state_dict
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def load_checkpoint(model):
|
| 159 |
+
state_dict = load_state_dict(model.runtime_config, model.engine_config)
|
| 160 |
+
|
| 161 |
+
model = unwrap_model(model)
|
| 162 |
+
# if we use pipeline parallelism, we need to load the state dict for each stage
|
| 163 |
+
# as it always record layer from 0 -> num_layers//pipeline_parallel_size
|
| 164 |
+
# so we need to choose correct layer weight when load_state_dict
|
| 165 |
+
if mpu.get_pp_world_size() > 1:
|
| 166 |
+
state_dict = _split_state_dict_for_pp(state_dict, model.model_config)
|
| 167 |
+
|
| 168 |
+
missing_keys, unexpected_keys = model.load_state_dict(state_dict, strict=False, assign=True)
|
| 169 |
+
model.cuda(torch.cuda.current_device()) # bottleneck for loading
|
| 170 |
+
|
| 171 |
+
if mpu.get_pp_world_size() > 1:
|
| 172 |
+
rank_msg = f"CP_rank={mpu.get_cp_rank()} PP_rank={mpu.get_pp_rank()}"
|
| 173 |
+
print_per_rank(
|
| 174 |
+
f"""[{rank_msg}] Load Weight Missing Keys: {missing_keys} Load Weight Unexpected Keys: {unexpected_keys} You should see message [missing fianl layer norm weight] except the final pipeline stage"""
|
| 175 |
+
)
|
| 176 |
+
else:
|
| 177 |
+
print_rank_0(f"Load Weight Missing Keys: {missing_keys}")
|
| 178 |
+
print_rank_0(f"Load Weight Unexpected Keys: {unexpected_keys}")
|
| 179 |
+
|
| 180 |
+
return model
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/distributed/__init__.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2025 SandAI. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from .dist_utils import dist_init, get_device, get_world_size, is_last_rank, is_last_tp_cp_rank
|
| 16 |
+
from .parallel_state import (
|
| 17 |
+
destroy_model_parallel,
|
| 18 |
+
get_cp_group,
|
| 19 |
+
get_cp_rank,
|
| 20 |
+
get_cp_world_size,
|
| 21 |
+
get_dp_group,
|
| 22 |
+
get_dp_group_gloo,
|
| 23 |
+
get_dp_rank,
|
| 24 |
+
get_dp_world_size,
|
| 25 |
+
get_pipeline_model_parallel_first_rank,
|
| 26 |
+
get_pipeline_model_parallel_last_rank,
|
| 27 |
+
get_pipeline_model_parallel_next_rank,
|
| 28 |
+
get_pipeline_model_parallel_prev_rank,
|
| 29 |
+
get_pp_group,
|
| 30 |
+
get_pp_rank,
|
| 31 |
+
get_pp_world_size,
|
| 32 |
+
get_tensor_model_parallel_last_rank,
|
| 33 |
+
get_tensor_model_parallel_ranks,
|
| 34 |
+
get_tensor_model_parallel_src_rank,
|
| 35 |
+
get_tp_group,
|
| 36 |
+
get_tp_rank,
|
| 37 |
+
get_tp_world_size,
|
| 38 |
+
is_initialized,
|
| 39 |
+
is_pipeline_first_stage,
|
| 40 |
+
is_pipeline_last_stage,
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
__all__ = [
|
| 44 |
+
"dist_init",
|
| 45 |
+
"is_initialized",
|
| 46 |
+
"get_tp_group",
|
| 47 |
+
"get_pp_group",
|
| 48 |
+
"get_dp_group",
|
| 49 |
+
"get_dp_group_gloo",
|
| 50 |
+
"get_cp_group",
|
| 51 |
+
"get_tp_world_size",
|
| 52 |
+
"get_pp_world_size",
|
| 53 |
+
"get_dp_world_size",
|
| 54 |
+
"get_cp_world_size",
|
| 55 |
+
"get_tp_rank",
|
| 56 |
+
"get_pp_rank",
|
| 57 |
+
"get_dp_rank",
|
| 58 |
+
"get_cp_rank",
|
| 59 |
+
"is_pipeline_first_stage",
|
| 60 |
+
"is_pipeline_last_stage",
|
| 61 |
+
"get_tensor_model_parallel_src_rank",
|
| 62 |
+
"get_tensor_model_parallel_ranks",
|
| 63 |
+
"get_tensor_model_parallel_last_rank",
|
| 64 |
+
"get_pipeline_model_parallel_first_rank",
|
| 65 |
+
"get_pipeline_model_parallel_last_rank",
|
| 66 |
+
"get_pipeline_model_parallel_next_rank",
|
| 67 |
+
"get_pipeline_model_parallel_prev_rank",
|
| 68 |
+
"destroy_model_parallel",
|
| 69 |
+
"is_last_rank",
|
| 70 |
+
"is_last_tp_cp_rank",
|
| 71 |
+
"get_world_size",
|
| 72 |
+
"get_device",
|
| 73 |
+
]
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/distributed/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1.31 kB). View file
|
|
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/distributed/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (1.36 kB). View file
|
|
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/distributed/__pycache__/dist_utils.cpython-310.pyc
ADDED
|
Binary file (2.51 kB). View file
|
|
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/distributed/__pycache__/dist_utils.cpython-312.pyc
ADDED
|
Binary file (4.43 kB). View file
|
|
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/distributed/__pycache__/parallel_state.cpython-310.pyc
ADDED
|
Binary file (21.5 kB). View file
|
|
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/distributed/__pycache__/parallel_state.cpython-312.pyc
ADDED
|
Binary file (28.6 kB). View file
|
|
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/distributed/dist_utils.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2025 SandAI. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import os
|
| 16 |
+
from datetime import timedelta
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
|
| 20 |
+
import inference.infra.distributed.parallel_state as mpu
|
| 21 |
+
from inference.common import print_rank_0
|
| 22 |
+
from inference.infra.parallelism.pipeline_parallel import init_pp_scheduler
|
| 23 |
+
|
| 24 |
+
from . import parallel_state as mpu
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def dist_init(config):
|
| 28 |
+
"""Initialize torch.distributed and core model parallel."""
|
| 29 |
+
|
| 30 |
+
assert torch.cuda.is_available()
|
| 31 |
+
device_count = torch.cuda.device_count()
|
| 32 |
+
if torch.distributed.is_initialized():
|
| 33 |
+
print_rank_0("Torch distribution already initialized, skipping initialization ...")
|
| 34 |
+
else:
|
| 35 |
+
rank = int(os.getenv("RANK", "0"))
|
| 36 |
+
world_size = int(os.getenv("WORLD_SIZE", "1"))
|
| 37 |
+
# Manually set the device ids.
|
| 38 |
+
if device_count > 0:
|
| 39 |
+
device = rank % device_count
|
| 40 |
+
torch.cuda.set_device(device)
|
| 41 |
+
# Call the init process
|
| 42 |
+
torch.distributed.init_process_group(
|
| 43 |
+
backend=config.engine_config.distributed_backend,
|
| 44 |
+
world_size=world_size,
|
| 45 |
+
rank=rank,
|
| 46 |
+
timeout=timedelta(minutes=config.engine_config.distributed_timeout_minutes),
|
| 47 |
+
)
|
| 48 |
+
assert config.engine_config.cp_size * config.engine_config.pp_size == torch.distributed.get_world_size()
|
| 49 |
+
if device_count > 0:
|
| 50 |
+
if mpu.model_parallel_is_initialized():
|
| 51 |
+
print_rank_0("Model parallel is already initialized")
|
| 52 |
+
else:
|
| 53 |
+
mpu.initialize_model_parallel(
|
| 54 |
+
cp_size=config.engine_config.cp_size,
|
| 55 |
+
pp_size=config.engine_config.pp_size,
|
| 56 |
+
nccl_communicator_config_path=None,
|
| 57 |
+
distributed_timeout_minutes=config.engine_config.distributed_timeout_minutes,
|
| 58 |
+
order="tp-cp-pp-dp",
|
| 59 |
+
)
|
| 60 |
+
if mpu.get_pp_world_size() > 1:
|
| 61 |
+
init_pp_scheduler()
|
| 62 |
+
print_rank_0("Initialize torch distribution and model parallel successfully")
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def is_last_rank():
|
| 66 |
+
return torch.distributed.get_rank() == (torch.distributed.get_world_size() - 1)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def is_last_tp_cp_rank():
|
| 70 |
+
return mpu.get_tp_rank(with_context_parallel=True) == mpu.get_tp_world_size(with_context_parallel=True) - 1
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def get_world_size():
|
| 74 |
+
if torch.distributed.is_available() and torch.distributed.is_initialized():
|
| 75 |
+
world_size = torch.distributed.get_world_size()
|
| 76 |
+
else:
|
| 77 |
+
world_size = 1
|
| 78 |
+
return world_size
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def get_device(local_rank=None):
|
| 82 |
+
backend = torch.distributed.get_backend()
|
| 83 |
+
if backend == "nccl":
|
| 84 |
+
if local_rank is None:
|
| 85 |
+
device = torch.device("cuda")
|
| 86 |
+
else:
|
| 87 |
+
device = torch.device(f"cuda:{local_rank}")
|
| 88 |
+
elif backend == "gloo":
|
| 89 |
+
device = torch.device("cpu")
|
| 90 |
+
else:
|
| 91 |
+
raise RuntimeError
|
| 92 |
+
return device
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/distributed/parallel_state.py
ADDED
|
@@ -0,0 +1,672 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
|
| 2 |
+
# Copyright (c) 2025 SandAI. All Rights Reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
"""Model and data parallel groups."""
|
| 17 |
+
|
| 18 |
+
import warnings
|
| 19 |
+
from datetime import timedelta
|
| 20 |
+
from typing import List, Optional
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
|
| 24 |
+
# Intra-layer model parallel group that the current rank belongs to.
|
| 25 |
+
_TENSOR_MODEL_PARALLEL_GROUP = None
|
| 26 |
+
# Tensor parallel group information with context parallel combined.
|
| 27 |
+
_TENSOR_MODEL_PARALLEL_GROUP_WITH_CP = None
|
| 28 |
+
_TENSOR_MODEL_PARALLEL_GLOBAL_RANKS_WITH_CP = None
|
| 29 |
+
# Inter-layer model parallel group that the current rank belongs to.
|
| 30 |
+
_PIPELINE_MODEL_PARALLEL_GROUP = None
|
| 31 |
+
# Model parallel group (both intra- and pipeline) that the current rank belongs to.
|
| 32 |
+
_MODEL_PARALLEL_GROUP = None
|
| 33 |
+
# Data parallel group that the current rank belongs to.
|
| 34 |
+
_DATA_PARALLEL_GROUP = None
|
| 35 |
+
_DATA_PARALLEL_GROUP_GLOO = None
|
| 36 |
+
# tensor model parallel group and data parallel group combined
|
| 37 |
+
# used for fp8 and moe training
|
| 38 |
+
_TENSOR_AND_DATA_PARALLEL_GROUP = None
|
| 39 |
+
|
| 40 |
+
# A list of global ranks for each pipeline group to ease calculation of the source
|
| 41 |
+
# rank when broadcasting from the first or last pipeline stage.
|
| 42 |
+
_PIPELINE_GLOBAL_RANKS = None
|
| 43 |
+
|
| 44 |
+
# A list of global ranks for each data parallel group to ease calculation of the source
|
| 45 |
+
# rank when broadcasting weights from src to all other data parallel ranks
|
| 46 |
+
_DATA_PARALLEL_GLOBAL_RANKS = None
|
| 47 |
+
|
| 48 |
+
# A list of global ranks for each tensor model parallel group to ease calculation of
|
| 49 |
+
# the first local rank in the tensor model parallel group
|
| 50 |
+
_TENSOR_MODEL_PARALLEL_GLOBAL_RANKS = None
|
| 51 |
+
|
| 52 |
+
# Context parallel group that the current rank belongs to
|
| 53 |
+
_CONTEXT_PARALLEL_GROUP = None
|
| 54 |
+
# A list of global ranks for each context parallel group to ease calculation of the
|
| 55 |
+
# destination rank when exchanging KV/dKV between context parallel_ranks
|
| 56 |
+
_CONTEXT_PARALLEL_GLOBAL_RANKS = None
|
| 57 |
+
|
| 58 |
+
# Data parallel group information with context parallel combined.
|
| 59 |
+
_DATA_PARALLEL_GROUP_WITH_CP = None
|
| 60 |
+
_DATA_PARALLEL_GROUP_WITH_CP_GLOO = None
|
| 61 |
+
_DATA_PARALLEL_GLOBAL_RANKS_WITH_CP = None
|
| 62 |
+
|
| 63 |
+
# combined parallel group of TP, DP, and CP used for fp8
|
| 64 |
+
_TENSOR_AND_DATA_PARALLEL_GROUP_WITH_CP = None
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def get_nccl_options(pg_name, nccl_comm_cfgs):
|
| 68 |
+
"""Set the NCCL process group options.
|
| 69 |
+
|
| 70 |
+
Args:
|
| 71 |
+
pg_name (str): process group name
|
| 72 |
+
nccl_comm_cfgs (dict): nccl communicator configurations
|
| 73 |
+
|
| 74 |
+
When an option (e.g., max_ctas) is not found in the config, use the NCCL default setting.
|
| 75 |
+
"""
|
| 76 |
+
if pg_name in nccl_comm_cfgs:
|
| 77 |
+
nccl_options = torch.distributed.ProcessGroupNCCL.Options()
|
| 78 |
+
nccl_options.config.cga_cluster_size = nccl_comm_cfgs[pg_name].get("cga_cluster_size", 4)
|
| 79 |
+
nccl_options.config.max_ctas = nccl_comm_cfgs[pg_name].get("max_ctas", 32)
|
| 80 |
+
nccl_options.config.min_ctas = nccl_comm_cfgs[pg_name].get("min_ctas", 1)
|
| 81 |
+
return nccl_options
|
| 82 |
+
else:
|
| 83 |
+
return None
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def generate_masked_orthogonal_rank_groups(world_size: int, parallel_size: List[int], mask: List[bool]) -> List[List[int]]:
|
| 87 |
+
"""Generate orthogonal parallel groups based on the parallel size and mask.
|
| 88 |
+
|
| 89 |
+
Arguments:
|
| 90 |
+
world_size (int): world size
|
| 91 |
+
|
| 92 |
+
parallel_size (List[int]):
|
| 93 |
+
The parallel size of each orthogonal parallel type. For example, if
|
| 94 |
+
tensor_parallel_size = 2, pipeline_model_parallel_group = 3, data_parallel_size = 4,
|
| 95 |
+
and the parallel mapping order is tp-pp-dp, then the parallel_size = [2, 3, 4].
|
| 96 |
+
|
| 97 |
+
mask (List[bool]):
|
| 98 |
+
The mask controls which parallel methods the generated groups represent. If mask[i] is
|
| 99 |
+
True, it means the generated group contains the i-th parallelism method. For example,
|
| 100 |
+
if parallel_size = [tp_size, pp_size, dp_size], and mask = [True, False , True], then
|
| 101 |
+
the generated group is the `tp-dp` group, if the mask = [False, True, False], then the
|
| 102 |
+
generated group is the `pp` group.
|
| 103 |
+
|
| 104 |
+
Algorithm:
|
| 105 |
+
For orthogonal parallelism, such as tp/dp/pp/cp, the global_rank and
|
| 106 |
+
local_rank satisfy the following equation:
|
| 107 |
+
global_rank = tp_rank + dp_rank * tp_size + pp_rank * tp_size * dp_size (1)
|
| 108 |
+
tp_rank \in [0, tp_size)
|
| 109 |
+
dp_rank \in [0, dp_size)
|
| 110 |
+
pp_rank \in [0, pp_size)
|
| 111 |
+
|
| 112 |
+
If we want to get the `dp_group` (tp_size * pp_size groups of dp_size ranks each.
|
| 113 |
+
For example, if the gpu size is 8 and order is 'tp-pp-dp', size is '2-2-2', and the
|
| 114 |
+
dp_group here is [[0, 4], [1, 5], [2, 6], [3, 7]].)
|
| 115 |
+
The tp_rank and pp_rank will be combined to form the `dp_group_index`.
|
| 116 |
+
dp_group_index = tp_rank + pp_rank * tp_size (2)
|
| 117 |
+
|
| 118 |
+
So, Given that tp_rank and pp_rank satisfy equation (2), and dp_rank in
|
| 119 |
+
range(0, dp_size), the ranks in dp_group[dp_group_index] satisfies the
|
| 120 |
+
equation (1).
|
| 121 |
+
|
| 122 |
+
This function solve this math problem.
|
| 123 |
+
|
| 124 |
+
For example, if the parallel_size = [tp_size, dp_size, pp_size] = [2, 3, 4],
|
| 125 |
+
and the mask = [False, True, False]. Then,
|
| 126 |
+
dp_group_index(0) = tp_rank(0) + pp_rank(0) * 2
|
| 127 |
+
dp_group_index(1) = tp_rank(1) + pp_rank(0) * 2
|
| 128 |
+
...
|
| 129 |
+
dp_group_index(7) = tp_rank(1) + pp_rank(3) * 2
|
| 130 |
+
|
| 131 |
+
dp_group[0] = 0 + range(0, 3) * 2 + 0 = [0, 2, 4]
|
| 132 |
+
dp_group[1] = 1 + range(0, 3) * 2 + 0 = [1, 3, 5]
|
| 133 |
+
...
|
| 134 |
+
dp_group[7] = 1 + range(0, 3) * 2 + 3 * 2 * 3 = [19, 21, 23]
|
| 135 |
+
"""
|
| 136 |
+
|
| 137 |
+
def prefix_product(a: List[int], init=1) -> List[int]:
|
| 138 |
+
r = [init]
|
| 139 |
+
for v in a:
|
| 140 |
+
init = init * v
|
| 141 |
+
r.append(init)
|
| 142 |
+
return r
|
| 143 |
+
|
| 144 |
+
def inner_product(a: List[int], b: List[int]) -> int:
|
| 145 |
+
return sum([x * y for x, y in zip(a, b)])
|
| 146 |
+
|
| 147 |
+
def decompose(index, shape, stride=None):
|
| 148 |
+
"""
|
| 149 |
+
This function solve the math problem below:
|
| 150 |
+
There is an equation:
|
| 151 |
+
index = sum(idx[i] * stride[i])
|
| 152 |
+
And given the value of index, stride.
|
| 153 |
+
Return the idx.
|
| 154 |
+
This function will used to get the pp/dp/pp_rank
|
| 155 |
+
from group_index and rank_in_group.
|
| 156 |
+
"""
|
| 157 |
+
if stride is None:
|
| 158 |
+
stride = prefix_product(shape)
|
| 159 |
+
idx = [(index // d) % s for s, d in zip(shape, stride)]
|
| 160 |
+
# stride is a prefix_product result. And the value of stride[-1]
|
| 161 |
+
# is not used.
|
| 162 |
+
assert (
|
| 163 |
+
sum([x * y for x, y in zip(idx, stride[:-1])]) == index
|
| 164 |
+
), "idx {} with shape {} mismatch the return idx {}".format(index, shape, idx)
|
| 165 |
+
return idx
|
| 166 |
+
|
| 167 |
+
masked_shape = [s for s, m in zip(parallel_size, mask) if m]
|
| 168 |
+
unmasked_shape = [s for s, m in zip(parallel_size, mask) if not m]
|
| 169 |
+
|
| 170 |
+
global_stride = prefix_product(parallel_size)
|
| 171 |
+
masked_stride = [d for d, m in zip(global_stride, mask) if m]
|
| 172 |
+
unmasked_stride = [d for d, m in zip(global_stride, mask) if not m]
|
| 173 |
+
|
| 174 |
+
group_size = prefix_product(masked_shape)[-1]
|
| 175 |
+
num_of_group = world_size // group_size
|
| 176 |
+
|
| 177 |
+
ranks = []
|
| 178 |
+
for group_index in range(num_of_group):
|
| 179 |
+
# get indices from unmaksed for group_index.
|
| 180 |
+
decomposed_group_idx = decompose(group_index, unmasked_shape)
|
| 181 |
+
rank = []
|
| 182 |
+
for rank_in_group in range(group_size):
|
| 183 |
+
# get indices from masked for rank_in_group.
|
| 184 |
+
decomposed_rank_idx = decompose(rank_in_group, masked_shape)
|
| 185 |
+
rank.append(
|
| 186 |
+
inner_product(decomposed_rank_idx, masked_stride) + inner_product(decomposed_group_idx, unmasked_stride)
|
| 187 |
+
)
|
| 188 |
+
ranks.append(rank)
|
| 189 |
+
return ranks
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
class RankGenerator(object):
|
| 193 |
+
def __init__(self, tp: int, dp: int, pp: int, cp: int, order: str) -> None:
|
| 194 |
+
self.tp = tp
|
| 195 |
+
self.dp = dp
|
| 196 |
+
self.pp = pp
|
| 197 |
+
self.cp = cp
|
| 198 |
+
self.world_size = tp * dp * pp * cp
|
| 199 |
+
|
| 200 |
+
self.name_to_size = {"tp": self.tp, "pp": self.pp, "dp": self.dp, "cp": self.cp}
|
| 201 |
+
order = order.lower()
|
| 202 |
+
for name in self.name_to_size.keys():
|
| 203 |
+
if name not in order and self.name_to_size[name] != 1:
|
| 204 |
+
raise RuntimeError(
|
| 205 |
+
f"The size of ({name}) is ({self.name_to_size[name]}), but you haven't specified the order ({self.order})."
|
| 206 |
+
)
|
| 207 |
+
elif name not in order:
|
| 208 |
+
order = order + "-" + name
|
| 209 |
+
|
| 210 |
+
self.order = order
|
| 211 |
+
self.ordered_size = [self.name_to_size[token] for token in order.split("-")]
|
| 212 |
+
|
| 213 |
+
def get_mask(self, order: str, token: str):
|
| 214 |
+
ordered_token = order.split("-")
|
| 215 |
+
token = token.split("-")
|
| 216 |
+
mask = [False] * len(ordered_token)
|
| 217 |
+
for t in token:
|
| 218 |
+
mask[ordered_token.index(t)] = True
|
| 219 |
+
return mask
|
| 220 |
+
|
| 221 |
+
def get_ranks(self, token):
|
| 222 |
+
"""Get rank group by input token.
|
| 223 |
+
|
| 224 |
+
Arguments:
|
| 225 |
+
token (str):
|
| 226 |
+
Specify the ranks type that want to get. If we want
|
| 227 |
+
to obtain multiple parallel types, we can use a hyphen
|
| 228 |
+
'-' to separate them. For example, if we want to obtain
|
| 229 |
+
the TP_DP group, the token should be 'tp-dp'.
|
| 230 |
+
"""
|
| 231 |
+
mask = self.get_mask(self.order, token)
|
| 232 |
+
ranks = generate_masked_orthogonal_rank_groups(self.world_size, self.ordered_size, mask)
|
| 233 |
+
return ranks
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def initialize_model_parallel(
|
| 237 |
+
tp_size: int = 1,
|
| 238 |
+
pp_size: int = 1,
|
| 239 |
+
cp_size: int = 1,
|
| 240 |
+
nccl_communicator_config_path: Optional[str] = None,
|
| 241 |
+
distributed_timeout_minutes: int = 30,
|
| 242 |
+
order: str = "tp-cp-pp-dp",
|
| 243 |
+
) -> None:
|
| 244 |
+
"""Initialize model data parallel groups.
|
| 245 |
+
Borrow from: https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/core/parallel_state.py
|
| 246 |
+
|
| 247 |
+
Args:
|
| 248 |
+
tp_size (int, default = 1):
|
| 249 |
+
The number of GPUs to split individual tensors across.
|
| 250 |
+
|
| 251 |
+
pp_size (int, default = 1):
|
| 252 |
+
The number of tensor parallel GPU groups to split the
|
| 253 |
+
Transformer layers across. For example, if tp_size is 4 and
|
| 254 |
+
pp_size is 2, the model will be split into 2 groups of 4 GPUs.
|
| 255 |
+
|
| 256 |
+
cp_size (int, default = 1):
|
| 257 |
+
The number of tensor parallel GPU groups to split the
|
| 258 |
+
network input sequence length across. Compute of attention
|
| 259 |
+
module requires tokens of full sequence length, so GPUs
|
| 260 |
+
in a context parallel group need to communicate with each
|
| 261 |
+
other to exchange information of other sequence chunks.
|
| 262 |
+
Each GPU and its counterparts in other tensor parallel
|
| 263 |
+
groups compose a context parallel group.
|
| 264 |
+
|
| 265 |
+
For example, assume we have 8 GPUs, if tensor model parallel
|
| 266 |
+
size is 4 and context parallel size is 2, the network input
|
| 267 |
+
will be split into two sequence chunks, which are processed
|
| 268 |
+
by 2 different groups of 4 GPUs. One chunk is processed by
|
| 269 |
+
GPU0-3, the other chunk is processed by GPU4-7. Four groups
|
| 270 |
+
are build to do context parallel communications: [GPU0, GPU4],
|
| 271 |
+
[GPU1, GPU5], [GPU2, GPU6], and [GPU3, GPU7].
|
| 272 |
+
|
| 273 |
+
Context parallelism partitions sequence length, so it has no
|
| 274 |
+
impact on weights, which means weights are duplicated among
|
| 275 |
+
GPUs in a context parallel group. Hence, weight gradients
|
| 276 |
+
all-reduce is required in backward. For simplicity, we piggyback
|
| 277 |
+
GPUs of context parallelism on data parallel group for
|
| 278 |
+
weight gradient all-reduce.
|
| 279 |
+
|
| 280 |
+
nccl_communicator_config_path (str, default = None):
|
| 281 |
+
Path to the yaml file of NCCL communicator configurations.
|
| 282 |
+
`min_ctas`, `max_ctas`, and `cga_cluster_size` can be set
|
| 283 |
+
for each communicator.
|
| 284 |
+
|
| 285 |
+
distributed_timeout_minutes (int, default = 30): Timeout, in
|
| 286 |
+
minutes,for operations executed against distributed
|
| 287 |
+
process groups. See PyTorch documentation at
|
| 288 |
+
https://pytorch.org/docs/stable/distributed.html for
|
| 289 |
+
caveats.
|
| 290 |
+
|
| 291 |
+
order (str, default=tp-dp-pp):
|
| 292 |
+
The rank initialization order of parallelism. Now we support
|
| 293 |
+
tp-dp-pp and tp-pp-dp orders.
|
| 294 |
+
|
| 295 |
+
Let's say we have a total of 16 GPUs denoted by g0 ... g15 and we
|
| 296 |
+
use 2 GPUs to parallelize the model tensor, and 4 GPUs to parallelize
|
| 297 |
+
the model pipeline. The present function will
|
| 298 |
+
create 8 tensor model-parallel groups, 4 pipeline model-parallel groups
|
| 299 |
+
and 8 data-parallel groups as:
|
| 300 |
+
8 data_parallel groups:
|
| 301 |
+
[g0, g2], [g1, g3], [g4, g6], [g5, g7], [g8, g10], [g9, g11], [g12, g14], [g13, g15]
|
| 302 |
+
8 tensor model-parallel groups:
|
| 303 |
+
[g0, g1], [g2, g3], [g4, g5], [g6, g7], [g8, g9], [g10, g11], [g12, g13], [g14, g15]
|
| 304 |
+
4 pipeline model-parallel groups:
|
| 305 |
+
[g0, g4, g8, g12], [g1, g5, g9, g13], [g2, g6, g10, g14], [g3, g7, g11, g15]
|
| 306 |
+
Note that for efficiency, the caller should make sure adjacent ranks
|
| 307 |
+
are on the same DGX box. For example if we are using 2 DGX-1 boxes
|
| 308 |
+
with a total of 16 GPUs, rank 0 to 7 belong to the first box and
|
| 309 |
+
ranks 8 to 15 belong to the second box.
|
| 310 |
+
|
| 311 |
+
"""
|
| 312 |
+
# Get world size and rank. Ensure some consistencies.
|
| 313 |
+
assert torch.distributed.is_initialized()
|
| 314 |
+
world_size: int = torch.distributed.get_world_size()
|
| 315 |
+
if world_size % (tp_size * pp_size * cp_size) != 0:
|
| 316 |
+
raise RuntimeError(
|
| 317 |
+
f"world_size ({world_size}) is not divisible by tp_size "
|
| 318 |
+
f"({tp_size}) x pp_size ({pp_size}) "
|
| 319 |
+
f"x cp_size ({cp_size})"
|
| 320 |
+
)
|
| 321 |
+
|
| 322 |
+
nccl_comm_cfgs = {}
|
| 323 |
+
if nccl_communicator_config_path is not None:
|
| 324 |
+
try:
|
| 325 |
+
import yaml
|
| 326 |
+
except ImportError:
|
| 327 |
+
raise RuntimeError("Cannot import `yaml`. Setting custom nccl communicator configs " "requires the yaml package.")
|
| 328 |
+
|
| 329 |
+
with open(nccl_communicator_config_path, "r") as stream:
|
| 330 |
+
nccl_comm_cfgs = yaml.safe_load(stream)
|
| 331 |
+
|
| 332 |
+
dp_size: int = world_size // (tp_size * pp_size * cp_size)
|
| 333 |
+
rank = torch.distributed.get_rank()
|
| 334 |
+
rank_generator = RankGenerator(tp=tp_size, dp=dp_size, pp=pp_size, cp=cp_size, order=order)
|
| 335 |
+
timeout = timedelta(minutes=distributed_timeout_minutes)
|
| 336 |
+
|
| 337 |
+
# Build the data-parallel groups.
|
| 338 |
+
global _DATA_PARALLEL_GROUP
|
| 339 |
+
global _DATA_PARALLEL_GROUP_GLOO
|
| 340 |
+
global _DATA_PARALLEL_GLOBAL_RANKS
|
| 341 |
+
global _DATA_PARALLEL_GROUP_WITH_CP
|
| 342 |
+
global _DATA_PARALLEL_GROUP_WITH_CP_GLOO
|
| 343 |
+
global _DATA_PARALLEL_GLOBAL_RANKS_WITH_CP
|
| 344 |
+
assert _DATA_PARALLEL_GROUP is None, "data parallel group is already initialized"
|
| 345 |
+
|
| 346 |
+
for ranks in rank_generator.get_ranks("dp"):
|
| 347 |
+
group = torch.distributed.new_group(ranks, timeout=timeout, pg_options=get_nccl_options("dp", nccl_comm_cfgs))
|
| 348 |
+
group_gloo = torch.distributed.new_group(ranks, timeout=timeout, backend="gloo")
|
| 349 |
+
if rank in ranks:
|
| 350 |
+
_DATA_PARALLEL_GROUP = group
|
| 351 |
+
_DATA_PARALLEL_GROUP_GLOO = group_gloo
|
| 352 |
+
_DATA_PARALLEL_GLOBAL_RANKS = ranks
|
| 353 |
+
for ranks_with_cp in rank_generator.get_ranks("dp-cp"):
|
| 354 |
+
group_with_cp = torch.distributed.new_group(
|
| 355 |
+
ranks_with_cp, timeout=timeout, pg_options=get_nccl_options("dp_cp", nccl_comm_cfgs)
|
| 356 |
+
)
|
| 357 |
+
group_with_cp_gloo = torch.distributed.new_group(ranks_with_cp, timeout=timeout, backend="gloo")
|
| 358 |
+
if rank in ranks_with_cp:
|
| 359 |
+
_DATA_PARALLEL_GROUP_WITH_CP = group_with_cp
|
| 360 |
+
_DATA_PARALLEL_GROUP_WITH_CP_GLOO = group_with_cp_gloo
|
| 361 |
+
_DATA_PARALLEL_GLOBAL_RANKS_WITH_CP = ranks_with_cp
|
| 362 |
+
|
| 363 |
+
# Build the context-parallel groups.
|
| 364 |
+
global _CONTEXT_PARALLEL_GROUP
|
| 365 |
+
global _CONTEXT_PARALLEL_GLOBAL_RANKS
|
| 366 |
+
assert _CONTEXT_PARALLEL_GROUP is None, "context parallel group is already initialized"
|
| 367 |
+
for ranks in rank_generator.get_ranks("cp"):
|
| 368 |
+
group = torch.distributed.new_group(ranks, timeout=timeout, pg_options=get_nccl_options("cp", nccl_comm_cfgs))
|
| 369 |
+
if rank in ranks:
|
| 370 |
+
_CONTEXT_PARALLEL_GROUP = group
|
| 371 |
+
_CONTEXT_PARALLEL_GLOBAL_RANKS = ranks
|
| 372 |
+
|
| 373 |
+
# Build the model-parallel groups.
|
| 374 |
+
global _MODEL_PARALLEL_GROUP
|
| 375 |
+
assert _MODEL_PARALLEL_GROUP is None, "model parallel group is already initialized"
|
| 376 |
+
for ranks in rank_generator.get_ranks("tp-pp"):
|
| 377 |
+
group = torch.distributed.new_group(ranks, timeout=timeout, pg_options=get_nccl_options("mp", nccl_comm_cfgs))
|
| 378 |
+
if rank in ranks:
|
| 379 |
+
_MODEL_PARALLEL_GROUP = group
|
| 380 |
+
|
| 381 |
+
# Build the tensor model-parallel groups.
|
| 382 |
+
global _TENSOR_MODEL_PARALLEL_GROUP
|
| 383 |
+
global _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS
|
| 384 |
+
assert _TENSOR_MODEL_PARALLEL_GROUP is None, "tensor model parallel group is already initialized"
|
| 385 |
+
for ranks in rank_generator.get_ranks("tp"):
|
| 386 |
+
group = torch.distributed.new_group(ranks, timeout=timeout, pg_options=get_nccl_options("tp", nccl_comm_cfgs))
|
| 387 |
+
if rank in ranks:
|
| 388 |
+
_TENSOR_MODEL_PARALLEL_GROUP = group
|
| 389 |
+
_TENSOR_MODEL_PARALLEL_GLOBAL_RANKS = ranks
|
| 390 |
+
|
| 391 |
+
# Build the tensor + context parallel groups.
|
| 392 |
+
global _TENSOR_MODEL_PARALLEL_GROUP_WITH_CP
|
| 393 |
+
global _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS_WITH_CP
|
| 394 |
+
assert (
|
| 395 |
+
_TENSOR_MODEL_PARALLEL_GROUP_WITH_CP is None
|
| 396 |
+
), "tensor model parallel group with context parallel is already initialized"
|
| 397 |
+
for ranks in rank_generator.get_ranks("tp-cp"):
|
| 398 |
+
group = torch.distributed.new_group(ranks, timeout=timeout, pg_options=get_nccl_options("tp_cp", nccl_comm_cfgs))
|
| 399 |
+
if rank in ranks:
|
| 400 |
+
_TENSOR_MODEL_PARALLEL_GROUP_WITH_CP = group
|
| 401 |
+
_TENSOR_MODEL_PARALLEL_GLOBAL_RANKS_WITH_CP = ranks
|
| 402 |
+
|
| 403 |
+
# Build the pipeline model-parallel groups
|
| 404 |
+
global _PIPELINE_MODEL_PARALLEL_GROUP
|
| 405 |
+
global _PIPELINE_GLOBAL_RANKS
|
| 406 |
+
assert _PIPELINE_MODEL_PARALLEL_GROUP is None, "pipeline model parallel group is already initialized"
|
| 407 |
+
for ranks in rank_generator.get_ranks("pp"):
|
| 408 |
+
group = torch.distributed.new_group(ranks, timeout=timeout, pg_options=get_nccl_options("pp", nccl_comm_cfgs))
|
| 409 |
+
if rank in ranks:
|
| 410 |
+
_PIPELINE_MODEL_PARALLEL_GROUP = group
|
| 411 |
+
_PIPELINE_GLOBAL_RANKS = ranks
|
| 412 |
+
|
| 413 |
+
# Build the tensor + data parallel groups.
|
| 414 |
+
global _TENSOR_AND_DATA_PARALLEL_GROUP
|
| 415 |
+
global _TENSOR_AND_DATA_PARALLEL_GROUP_WITH_CP
|
| 416 |
+
assert _TENSOR_AND_DATA_PARALLEL_GROUP is None, "Tensor + data parallel group is already initialized"
|
| 417 |
+
for ranks in rank_generator.get_ranks("tp-cp-dp"):
|
| 418 |
+
group = torch.distributed.new_group(ranks, timeout=timeout, pg_options=get_nccl_options("tp_cp_dp", nccl_comm_cfgs))
|
| 419 |
+
if rank in ranks:
|
| 420 |
+
_TENSOR_AND_DATA_PARALLEL_GROUP_WITH_CP = group
|
| 421 |
+
for ranks in rank_generator.get_ranks("tp-dp"):
|
| 422 |
+
group = torch.distributed.new_group(ranks, timeout=timeout, pg_options=get_nccl_options("tp_dp", nccl_comm_cfgs))
|
| 423 |
+
if rank in ranks:
|
| 424 |
+
_TENSOR_AND_DATA_PARALLEL_GROUP = group
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
def is_initialized():
|
| 428 |
+
"""Useful for code segments that may be accessed with or without mpu initialization"""
|
| 429 |
+
return _DATA_PARALLEL_GROUP is not None
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
def is_unitialized() -> bool:
|
| 433 |
+
"""Check if parallel state has been initialized
|
| 434 |
+
|
| 435 |
+
Deprecated. Use is_initialized instead.
|
| 436 |
+
|
| 437 |
+
"""
|
| 438 |
+
warnings.warn("is_unitialized is deprecated, use is_initialized instead", DeprecationWarning)
|
| 439 |
+
return not is_initialized()
|
| 440 |
+
|
| 441 |
+
|
| 442 |
+
def model_parallel_is_initialized():
|
| 443 |
+
"""Check if model and data parallel groups are initialized."""
|
| 444 |
+
if _TENSOR_MODEL_PARALLEL_GROUP is None or _PIPELINE_MODEL_PARALLEL_GROUP is None or _DATA_PARALLEL_GROUP is None:
|
| 445 |
+
return False
|
| 446 |
+
return True
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
def get_model_parallel_group():
|
| 450 |
+
"""Get the model parallel group the caller rank belongs to."""
|
| 451 |
+
assert _MODEL_PARALLEL_GROUP is not None, "model parallel group is not initialized"
|
| 452 |
+
return _MODEL_PARALLEL_GROUP
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
def get_tp_group(check_initialized=True, with_context_parallel=False):
|
| 456 |
+
"""Get the tensor model parallel group the caller rank belongs to."""
|
| 457 |
+
if check_initialized:
|
| 458 |
+
assert _TENSOR_MODEL_PARALLEL_GROUP is not None, "tensor model parallel group is not initialized"
|
| 459 |
+
if with_context_parallel:
|
| 460 |
+
assert (
|
| 461 |
+
_TENSOR_MODEL_PARALLEL_GROUP_WITH_CP is not None
|
| 462 |
+
), "tensor model parallel group with context parallel combined is not initialized"
|
| 463 |
+
return _TENSOR_MODEL_PARALLEL_GROUP_WITH_CP
|
| 464 |
+
else:
|
| 465 |
+
assert _TENSOR_MODEL_PARALLEL_GROUP is not None, "tensor model parallel group is not initialized"
|
| 466 |
+
return _TENSOR_MODEL_PARALLEL_GROUP
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
def get_pp_group():
|
| 470 |
+
"""Get the pipeline model parallel group the caller rank belongs to."""
|
| 471 |
+
assert _PIPELINE_MODEL_PARALLEL_GROUP is not None, "pipeline_model parallel group is not initialized"
|
| 472 |
+
return _PIPELINE_MODEL_PARALLEL_GROUP
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
def get_dp_group(with_context_parallel=False):
|
| 476 |
+
"""Get the data parallel group the caller rank belongs to."""
|
| 477 |
+
if with_context_parallel:
|
| 478 |
+
assert (
|
| 479 |
+
_DATA_PARALLEL_GROUP_WITH_CP is not None
|
| 480 |
+
), "data parallel group with context parallel combined is not initialized"
|
| 481 |
+
return _DATA_PARALLEL_GROUP_WITH_CP
|
| 482 |
+
else:
|
| 483 |
+
assert _DATA_PARALLEL_GROUP is not None, "data parallel group is not initialized"
|
| 484 |
+
return _DATA_PARALLEL_GROUP
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
def get_dp_group_gloo(with_context_parallel=False):
|
| 488 |
+
"""Get the data parallel group-gloo the caller rank belongs to."""
|
| 489 |
+
if with_context_parallel:
|
| 490 |
+
assert (
|
| 491 |
+
_DATA_PARALLEL_GROUP_WITH_CP_GLOO is not None
|
| 492 |
+
), "data parallel group-gloo with context parallel combined is not initialized"
|
| 493 |
+
return _DATA_PARALLEL_GROUP_WITH_CP_GLOO
|
| 494 |
+
else:
|
| 495 |
+
assert _DATA_PARALLEL_GROUP_GLOO is not None, "data parallel group-gloo is not initialized"
|
| 496 |
+
return _DATA_PARALLEL_GROUP_GLOO
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
def get_cp_group(check_initialized=True):
|
| 500 |
+
"""Get the context parallel group the caller rank belongs to."""
|
| 501 |
+
if check_initialized:
|
| 502 |
+
assert _CONTEXT_PARALLEL_GROUP is not None, "context parallel group is not initialized"
|
| 503 |
+
return _CONTEXT_PARALLEL_GROUP
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
def get_tp_world_size(with_context_parallel=False):
|
| 507 |
+
"""Return world size for the tensor model parallel group."""
|
| 508 |
+
return torch.distributed.get_world_size(group=get_tp_group(with_context_parallel=with_context_parallel))
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
def get_pp_world_size():
|
| 512 |
+
"""Return world size for the pipeline model parallel group."""
|
| 513 |
+
return torch.distributed.get_world_size(group=get_pp_group())
|
| 514 |
+
|
| 515 |
+
|
| 516 |
+
def get_tp_rank(with_context_parallel=False):
|
| 517 |
+
"""Return my rank for the tensor model parallel group."""
|
| 518 |
+
return torch.distributed.get_rank(group=get_tp_group(with_context_parallel=with_context_parallel))
|
| 519 |
+
|
| 520 |
+
|
| 521 |
+
def get_pp_rank():
|
| 522 |
+
"""Return my rank for the pipeline model parallel group."""
|
| 523 |
+
return torch.distributed.get_rank(group=get_pp_group())
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
def is_pipeline_first_stage():
|
| 527 |
+
"""Return True if in the first pipeline model-parallel stage, False otherwise."""
|
| 528 |
+
return get_pp_rank() == 0
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
def is_pipeline_last_stage():
|
| 532 |
+
"""Return True if in the last pipeline model-parallel stage, False otherwise."""
|
| 533 |
+
return get_pp_rank() == (get_pp_world_size() - 1)
|
| 534 |
+
|
| 535 |
+
|
| 536 |
+
def get_tensor_model_parallel_src_rank(with_context_parallel=False):
|
| 537 |
+
"""Calculate the global rank corresponding to the first local rank
|
| 538 |
+
in the tensor model parallel group."""
|
| 539 |
+
assert _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS is not None, "Tensor model parallel group is not initialized"
|
| 540 |
+
if with_context_parallel:
|
| 541 |
+
assert (
|
| 542 |
+
_TENSOR_MODEL_PARALLEL_GLOBAL_RANKS_WITH_CP is not None
|
| 543 |
+
), "Tensor model parallel group with context parallel combined is not initialized"
|
| 544 |
+
return _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS_WITH_CP[0]
|
| 545 |
+
else:
|
| 546 |
+
return _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS[0]
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
def get_tensor_model_parallel_ranks(with_context_parallel=False):
|
| 550 |
+
"""Return all global ranks for the tensor model parallel group."""
|
| 551 |
+
if with_context_parallel:
|
| 552 |
+
assert (
|
| 553 |
+
_TENSOR_MODEL_PARALLEL_GLOBAL_RANKS_WITH_CP is not None
|
| 554 |
+
), "Tensor model parallel group with context parallel combined is not initialized"
|
| 555 |
+
return _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS_WITH_CP
|
| 556 |
+
else:
|
| 557 |
+
assert _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS is not None, "Tensor model parallel group is not initialized"
|
| 558 |
+
return _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS
|
| 559 |
+
|
| 560 |
+
|
| 561 |
+
def get_tensor_model_parallel_last_rank(with_context_parallel=False):
|
| 562 |
+
"""Calculate the global rank corresponding to the first local rank
|
| 563 |
+
in the tensor model parallel group."""
|
| 564 |
+
assert _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS is not None, "Tensor model parallel group is not initialized"
|
| 565 |
+
if with_context_parallel:
|
| 566 |
+
assert (
|
| 567 |
+
_TENSOR_MODEL_PARALLEL_GLOBAL_RANKS_WITH_CP is not None
|
| 568 |
+
), "Tensor model parallel group with context parallel combined is not initialized"
|
| 569 |
+
return _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS_WITH_CP[-1]
|
| 570 |
+
else:
|
| 571 |
+
return _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS[-1]
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
def get_pipeline_model_parallel_first_rank():
|
| 575 |
+
"""Return the global rank of the first process in the pipeline for the
|
| 576 |
+
current tensor parallel group"""
|
| 577 |
+
assert _PIPELINE_GLOBAL_RANKS is not None, "Pipeline parallel group is not initialized"
|
| 578 |
+
return _PIPELINE_GLOBAL_RANKS[0]
|
| 579 |
+
|
| 580 |
+
|
| 581 |
+
def get_pipeline_model_parallel_last_rank():
|
| 582 |
+
"""Return the global rank of the last process in the pipeline for the
|
| 583 |
+
current tensor parallel group"""
|
| 584 |
+
assert _PIPELINE_GLOBAL_RANKS is not None, "Pipeline parallel group is not initialized"
|
| 585 |
+
last_rank_local = get_pp_world_size() - 1
|
| 586 |
+
return _PIPELINE_GLOBAL_RANKS[last_rank_local]
|
| 587 |
+
|
| 588 |
+
|
| 589 |
+
def get_pipeline_model_parallel_next_rank():
|
| 590 |
+
"""Return the global rank that follows the caller in the pipeline"""
|
| 591 |
+
assert _PIPELINE_GLOBAL_RANKS is not None, "Pipeline parallel group is not initialized"
|
| 592 |
+
rank_in_pipeline = get_pp_rank()
|
| 593 |
+
world_size = get_pp_world_size()
|
| 594 |
+
return _PIPELINE_GLOBAL_RANKS[(rank_in_pipeline + 1) % world_size]
|
| 595 |
+
|
| 596 |
+
|
| 597 |
+
def get_pipeline_model_parallel_prev_rank():
|
| 598 |
+
"""Return the global rank that preceeds the caller in the pipeline"""
|
| 599 |
+
assert _PIPELINE_GLOBAL_RANKS is not None, "Pipeline parallel group is not initialized"
|
| 600 |
+
rank_in_pipeline = get_pp_rank()
|
| 601 |
+
world_size = get_pp_world_size()
|
| 602 |
+
return _PIPELINE_GLOBAL_RANKS[(rank_in_pipeline - 1) % world_size]
|
| 603 |
+
|
| 604 |
+
|
| 605 |
+
def get_dp_world_size(with_context_parallel=False):
|
| 606 |
+
"""Return world size for the data parallel group."""
|
| 607 |
+
if torch.distributed.is_available() and torch.distributed.is_initialized():
|
| 608 |
+
return torch.distributed.get_world_size(group=get_dp_group(with_context_parallel=with_context_parallel))
|
| 609 |
+
else:
|
| 610 |
+
return 0
|
| 611 |
+
|
| 612 |
+
|
| 613 |
+
def get_dp_rank(with_context_parallel=False):
|
| 614 |
+
"""Return my rank for the data parallel group."""
|
| 615 |
+
if torch.distributed.is_available() and torch.distributed.is_initialized():
|
| 616 |
+
return torch.distributed.get_rank(group=get_dp_group(with_context_parallel=with_context_parallel))
|
| 617 |
+
else:
|
| 618 |
+
return 0
|
| 619 |
+
|
| 620 |
+
|
| 621 |
+
def get_cp_world_size():
|
| 622 |
+
"""Return world size for the context parallel group."""
|
| 623 |
+
if torch.distributed.is_available() and torch.distributed.is_initialized():
|
| 624 |
+
return torch.distributed.get_world_size(group=get_cp_group())
|
| 625 |
+
else:
|
| 626 |
+
return 0
|
| 627 |
+
|
| 628 |
+
|
| 629 |
+
def get_cp_rank():
|
| 630 |
+
"""Return my rank for the context parallel group."""
|
| 631 |
+
if torch.distributed.is_available() and torch.distributed.is_initialized():
|
| 632 |
+
return torch.distributed.get_rank(group=get_cp_group())
|
| 633 |
+
else:
|
| 634 |
+
return 0
|
| 635 |
+
|
| 636 |
+
|
| 637 |
+
def destroy_model_parallel():
|
| 638 |
+
"""Set the groups to none."""
|
| 639 |
+
global _MODEL_PARALLEL_GROUP
|
| 640 |
+
_MODEL_PARALLEL_GROUP = None
|
| 641 |
+
global _TENSOR_MODEL_PARALLEL_GROUP
|
| 642 |
+
_TENSOR_MODEL_PARALLEL_GROUP = None
|
| 643 |
+
global _TENSOR_MODEL_PARALLEL_GROUP_WITH_CP
|
| 644 |
+
_TENSOR_MODEL_PARALLEL_GROUP_WITH_CP = None
|
| 645 |
+
global _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS_WITH_CP
|
| 646 |
+
_TENSOR_MODEL_PARALLEL_GLOBAL_RANKS_WITH_CP = None
|
| 647 |
+
global _PIPELINE_MODEL_PARALLEL_GROUP
|
| 648 |
+
_PIPELINE_MODEL_PARALLEL_GROUP = None
|
| 649 |
+
global _DATA_PARALLEL_GROUP
|
| 650 |
+
_DATA_PARALLEL_GROUP = None
|
| 651 |
+
global _DATA_PARALLEL_GROUP_GLOO
|
| 652 |
+
_DATA_PARALLEL_GROUP_GLOO = None
|
| 653 |
+
global _TENSOR_AND_DATA_PARALLEL_GROUP
|
| 654 |
+
_TENSOR_AND_DATA_PARALLEL_GROUP = None
|
| 655 |
+
global _PIPELINE_GLOBAL_RANKS
|
| 656 |
+
_PIPELINE_GLOBAL_RANKS = None
|
| 657 |
+
global _DATA_PARALLEL_GLOBAL_RANKS
|
| 658 |
+
_DATA_PARALLEL_GLOBAL_RANKS = None
|
| 659 |
+
global _TENSOR_MODEL_PARALLEL_GLOBAL_RANKS
|
| 660 |
+
_TENSOR_MODEL_PARALLEL_GLOBAL_RANKS = None
|
| 661 |
+
global _CONTEXT_PARALLEL_GROUP
|
| 662 |
+
_CONTEXT_PARALLEL_GROUP = None
|
| 663 |
+
global _CONTEXT_PARALLEL_GLOBAL_RANKS
|
| 664 |
+
_CONTEXT_PARALLEL_GLOBAL_RANKS = None
|
| 665 |
+
global _DATA_PARALLEL_GROUP_WITH_CP
|
| 666 |
+
_DATA_PARALLEL_GROUP_WITH_CP = None
|
| 667 |
+
global _DATA_PARALLEL_GROUP_WITH_CP_GLOO
|
| 668 |
+
_DATA_PARALLEL_GROUP_WITH_CP_GLOO = None
|
| 669 |
+
global _DATA_PARALLEL_GLOBAL_RANKS_WITH_CP
|
| 670 |
+
_DATA_PARALLEL_GLOBAL_RANKS_WITH_CP = None
|
| 671 |
+
global _TENSOR_AND_DATA_PARALLEL_GROUP_WITH_CP
|
| 672 |
+
_TENSOR_AND_DATA_PARALLEL_GROUP_WITH_CP = None
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/parallelism/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2025 SandAI. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from .context_parallel import CSOHelper, UlyssesScheduler, cp_post_process, cp_pre_process, cso_communication
|
| 16 |
+
from .pipeline_parallel import pp_scheduler
|
| 17 |
+
from .tile_parallel import TileProcessor
|
| 18 |
+
|
| 19 |
+
__all__ = [
|
| 20 |
+
"CSOHelper",
|
| 21 |
+
"cso_communication",
|
| 22 |
+
"UlyssesScheduler",
|
| 23 |
+
"pp_scheduler",
|
| 24 |
+
"TileProcessor",
|
| 25 |
+
"cp_pre_process",
|
| 26 |
+
"cp_post_process",
|
| 27 |
+
]
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/parallelism/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (523 Bytes). View file
|
|
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/parallelism/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (539 Bytes). View file
|
|
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/parallelism/__pycache__/context_parallel.cpython-310.pyc
ADDED
|
Binary file (19.7 kB). View file
|
|
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/parallelism/__pycache__/context_parallel.cpython-312.pyc
ADDED
|
Binary file (33.9 kB). View file
|
|
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/parallelism/__pycache__/pipeline_parallel.cpython-310.pyc
ADDED
|
Binary file (4.44 kB). View file
|
|
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/parallelism/__pycache__/pipeline_parallel.cpython-312.pyc
ADDED
|
Binary file (6.09 kB). View file
|
|
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/parallelism/__pycache__/tile_parallel.cpython-310.pyc
ADDED
|
Binary file (14 kB). View file
|
|
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/parallelism/__pycache__/tile_parallel.cpython-312.pyc
ADDED
|
Binary file (24.1 kB). View file
|
|
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/parallelism/context_parallel.py
ADDED
|
@@ -0,0 +1,673 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2025 SandAI. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import math
|
| 16 |
+
from typing import Callable, List, Tuple, Union
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
import torch.distributed
|
| 20 |
+
from einops import rearrange
|
| 21 |
+
|
| 22 |
+
from inference.common import ModelMetaArgs, PackedCoreAttnParams, PackedCrossAttnParams, divide
|
| 23 |
+
from inference.infra.distributed import parallel_state as mpu
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
#####################################################
|
| 27 |
+
# Common Primitives
|
| 28 |
+
#####################################################
|
| 29 |
+
def scatter_to_context_parallel_region(input_, cp_split_sizes, cp_shuffle_num=1, cp_pad_size=0):
|
| 30 |
+
"""Split the tensor along its first dimension and keep the
|
| 31 |
+
corresponding slice."""
|
| 32 |
+
|
| 33 |
+
world_size = mpu.get_cp_world_size()
|
| 34 |
+
# Bypass the function if we are using only 1 GPU.
|
| 35 |
+
if world_size == 1:
|
| 36 |
+
return input_
|
| 37 |
+
|
| 38 |
+
# Split along first dimension with padding.
|
| 39 |
+
rank = mpu.get_cp_rank()
|
| 40 |
+
if cp_shuffle_num > 1:
|
| 41 |
+
cp_pad_size = divide(cp_pad_size, cp_shuffle_num)
|
| 42 |
+
cp_split_sizes = [divide(s, cp_shuffle_num) for s in cp_split_sizes]
|
| 43 |
+
dim_offset = sum(cp_split_sizes[:rank])
|
| 44 |
+
xs = []
|
| 45 |
+
for x in torch.chunk(input_, cp_shuffle_num, dim=0):
|
| 46 |
+
x = torch.nn.functional.pad(x, [0, 0] * (x.dim() - 1) + [0, cp_pad_size], mode="constant", value=0)
|
| 47 |
+
xs.append(x[dim_offset : dim_offset + cp_split_sizes[rank]])
|
| 48 |
+
output = torch.concat(xs, dim=0)
|
| 49 |
+
else:
|
| 50 |
+
dim_offset = sum(cp_split_sizes[:rank])
|
| 51 |
+
x = torch.nn.functional.pad(input_, [0, 0] * (input_.dim() - 1) + [0, cp_pad_size], mode="constant", value=0)
|
| 52 |
+
output = x[dim_offset : dim_offset + cp_split_sizes[rank]].contiguous()
|
| 53 |
+
return output
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def gather_from_context_parallel_region(input_, cp_split_sizes, cp_shuffle_num=1, cp_pad_size=0):
|
| 57 |
+
"""Gather tensors and concatinate along the first dimension."""
|
| 58 |
+
|
| 59 |
+
world_size = mpu.get_cp_world_size()
|
| 60 |
+
# Bypass the function if we are using only 1 GPU.
|
| 61 |
+
if world_size == 1:
|
| 62 |
+
return input_
|
| 63 |
+
|
| 64 |
+
input_ = input_.contiguous()
|
| 65 |
+
total_seq_len = sum(cp_split_sizes)
|
| 66 |
+
dim_size = list(input_.size())
|
| 67 |
+
dim_size[0] = total_seq_len
|
| 68 |
+
|
| 69 |
+
output = torch.empty(dim_size, dtype=input_.dtype, device=input_.device)
|
| 70 |
+
outputs = list(torch.split(output, cp_split_sizes, dim=0))
|
| 71 |
+
torch.distributed.all_gather(outputs, input_, group=mpu.get_cp_group())
|
| 72 |
+
if cp_shuffle_num > 1:
|
| 73 |
+
total_seq_len = divide(total_seq_len, cp_shuffle_num)
|
| 74 |
+
cp_pad_size = divide(cp_pad_size, cp_shuffle_num)
|
| 75 |
+
chunks = [torch.chunk(o, cp_shuffle_num, dim=0) for o in outputs]
|
| 76 |
+
output = torch.concat(
|
| 77 |
+
[
|
| 78 |
+
torch.concat([chunk[i] for chunk in chunks], dim=0)[: total_seq_len - cp_pad_size]
|
| 79 |
+
for i in range(cp_shuffle_num)
|
| 80 |
+
],
|
| 81 |
+
dim=0,
|
| 82 |
+
)
|
| 83 |
+
else:
|
| 84 |
+
output = torch.concat(outputs, dim=0)[: total_seq_len - cp_pad_size]
|
| 85 |
+
|
| 86 |
+
return output
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class FakeHandle:
|
| 90 |
+
def __init__(self):
|
| 91 |
+
pass
|
| 92 |
+
|
| 93 |
+
def wait(self):
|
| 94 |
+
pass
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
#####################################################
|
| 98 |
+
# Context Parallel Process
|
| 99 |
+
#####################################################
|
| 100 |
+
def update_packed_seq_params_for_cuda_graph(cross_attn_params: PackedCrossAttnParams, xattn_mask: torch.Tensor):
|
| 101 |
+
assert xattn_mask is not None
|
| 102 |
+
# xattn_mask: (N * denoising_range_num, L, 1, 1)
|
| 103 |
+
xattn_mask = xattn_mask.reshape(xattn_mask.shape[0], -1)
|
| 104 |
+
batch_size, static_caption_length = xattn_mask.shape
|
| 105 |
+
|
| 106 |
+
# Get index_map for kv_range injection, map y_index to static_caption_length
|
| 107 |
+
y_index = torch.sum(xattn_mask, dim=-1)
|
| 108 |
+
cu_seqlens_k = torch.cat([y_index.new_tensor([0]), y_index]).to(torch.int32).to(xattn_mask.device)
|
| 109 |
+
cu_seqlens_k = cu_seqlens_k.cumsum(-1).to(torch.int32)
|
| 110 |
+
static_cu_seqlens_k = torch.arange(0, (batch_size + 1) * static_caption_length, static_caption_length)
|
| 111 |
+
assert cu_seqlens_k.shape[0] == batch_size + 1 == static_cu_seqlens_k.shape[0]
|
| 112 |
+
start_index_map = dict(zip(cu_seqlens_k.flatten().tolist(), static_cu_seqlens_k.flatten().tolist()))
|
| 113 |
+
|
| 114 |
+
# Move kv_range to the right position
|
| 115 |
+
kv_range_start_list = cross_attn_params.kv_ranges[:, 0].flatten().tolist()
|
| 116 |
+
static_kv_range_start = [start_index_map[kv_range_start_list[i]] for i in range(len(kv_range_start_list))]
|
| 117 |
+
static_kv_range_start = torch.tensor(static_kv_range_start, dtype=torch.int32, device=xattn_mask.device)
|
| 118 |
+
assert static_kv_range_start.shape[0] == cross_attn_params.kv_ranges.shape[0]
|
| 119 |
+
static_kv_range_diff = cross_attn_params.kv_ranges[:, 1] - cross_attn_params.kv_ranges[:, 0]
|
| 120 |
+
static_kv_range_end = static_kv_range_start + static_kv_range_diff
|
| 121 |
+
static_kv_range = torch.stack((static_kv_range_start, static_kv_range_end), dim=1)
|
| 122 |
+
|
| 123 |
+
assert static_kv_range.shape == cross_attn_params.kv_ranges.shape
|
| 124 |
+
return PackedCrossAttnParams(
|
| 125 |
+
q_ranges=cross_attn_params.q_ranges,
|
| 126 |
+
kv_ranges=static_kv_range,
|
| 127 |
+
cu_seqlens_q=cross_attn_params.cu_seqlens_q,
|
| 128 |
+
cu_seqlens_kv=cross_attn_params.cu_seqlens_kv,
|
| 129 |
+
max_seqlen_q=cross_attn_params.max_seqlen_q,
|
| 130 |
+
max_seqlen_kv=cross_attn_params.max_seqlen_kv,
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def cp_update_cross_attn_qkv_range(
|
| 135 |
+
cross_attn_params: PackedCrossAttnParams,
|
| 136 |
+
batch_size: int,
|
| 137 |
+
cp_split_sizes: List[int],
|
| 138 |
+
device: torch.device,
|
| 139 |
+
cp_shuffle_num: int = 1,
|
| 140 |
+
cp_pad_size: int = 0,
|
| 141 |
+
):
|
| 142 |
+
"""
|
| 143 |
+
Update cross_attn_params for cross_attn in context parallel.
|
| 144 |
+
|
| 145 |
+
Input:
|
| 146 |
+
cross_attn_params: PackedCrossAttnParams. Packed sequence parameters for cross_atten
|
| 147 |
+
batch_size: int. Batch size
|
| 148 |
+
cp_split_sizes: List[int]. Split sizes for each rank
|
| 149 |
+
device: torch.device. Device
|
| 150 |
+
|
| 151 |
+
Output:
|
| 152 |
+
cross_attn_params: PackedCrossAttnParams. Updated packed parameters for cross_atten
|
| 153 |
+
"""
|
| 154 |
+
# Update cu_seqlens_q and max_seqlen_q because split x maybe unbalanced
|
| 155 |
+
cp_rank = mpu.get_cp_rank()
|
| 156 |
+
seq_len_cur_rank = cp_split_sizes[cp_rank]
|
| 157 |
+
cp_split_sizes = [divide(x, cp_shuffle_num) for x in cp_split_sizes]
|
| 158 |
+
cp_split_sizes = torch.tensor(cp_split_sizes, dtype=torch.int32, device=device)
|
| 159 |
+
base_cp_boundaries = torch.cat((torch.zeros(1, dtype=torch.int32, device=device), cp_split_sizes.cumsum(0)))
|
| 160 |
+
total_seq_len = base_cp_boundaries[-1]
|
| 161 |
+
|
| 162 |
+
cu_seqlens_q = cross_attn_params.cu_seqlens_q
|
| 163 |
+
cu_seqlens_k = cross_attn_params.cu_seqlens_kv
|
| 164 |
+
cu_seqlens_pad = torch.arange(cu_seqlens_q.shape[0], dtype=torch.int32, device=device) * divide(
|
| 165 |
+
cp_pad_size, cp_shuffle_num
|
| 166 |
+
)
|
| 167 |
+
cu_seqlens_q = cu_seqlens_q + cu_seqlens_pad
|
| 168 |
+
|
| 169 |
+
q_seg_starts, q_seg_ends = cu_seqlens_q[:-1], cu_seqlens_q[1:]
|
| 170 |
+
|
| 171 |
+
xattn_q_ranges, xattn_k_ranges = [], []
|
| 172 |
+
for i in range(batch_size):
|
| 173 |
+
inner_xattn_q_ranges, inner_xattn_k_ranges = [], []
|
| 174 |
+
for j in range(cp_shuffle_num):
|
| 175 |
+
global_offset = i * total_seq_len * cp_shuffle_num + j * total_seq_len
|
| 176 |
+
cp_boundaries = base_cp_boundaries + global_offset
|
| 177 |
+
this_cp_start, this_cp_end = (cp_boundaries[cp_rank], cp_boundaries[cp_rank + 1])
|
| 178 |
+
|
| 179 |
+
q_inter_starts = torch.maximum(this_cp_start, q_seg_starts)
|
| 180 |
+
q_inter_ends = torch.minimum(this_cp_end, q_seg_ends)
|
| 181 |
+
|
| 182 |
+
q_mask = q_inter_starts < q_inter_ends
|
| 183 |
+
valid_q_starts = q_inter_starts[q_mask]
|
| 184 |
+
valid_q_ends = q_inter_ends[q_mask]
|
| 185 |
+
|
| 186 |
+
k_seg_starts, k_seg_ends = cu_seqlens_k[:-1], cu_seqlens_k[1:]
|
| 187 |
+
valid_indices = torch.nonzero(q_mask, as_tuple=True)[0]
|
| 188 |
+
|
| 189 |
+
valid_k_starts = k_seg_starts[valid_indices]
|
| 190 |
+
valid_k_ends = k_seg_ends[valid_indices]
|
| 191 |
+
|
| 192 |
+
part_xattn_q_rangs = torch.stack((valid_q_starts, valid_q_ends), dim=1)
|
| 193 |
+
offset = part_xattn_q_rangs[:, 0].min()
|
| 194 |
+
part_xattn_q_rangs = part_xattn_q_rangs - offset
|
| 195 |
+
|
| 196 |
+
inner_xattn_q_ranges.append(part_xattn_q_rangs)
|
| 197 |
+
inner_xattn_k_ranges.append(torch.stack((valid_k_starts, valid_k_ends), dim=1))
|
| 198 |
+
inner_end_values = torch.tensor([ranges[-1, -1] for ranges in inner_xattn_q_ranges], dtype=torch.int32)
|
| 199 |
+
inner_offsets = torch.cat((torch.zeros(1, dtype=inner_end_values.dtype), torch.cumsum(inner_end_values[:-1], dim=0)))
|
| 200 |
+
inner_xattn_q_ranges = [tensor + int(offset) for tensor, offset in zip(inner_xattn_q_ranges, inner_offsets)]
|
| 201 |
+
xattn_q_ranges.append(torch.cat(inner_xattn_q_ranges, dim=0))
|
| 202 |
+
xattn_k_ranges.append(torch.cat(inner_xattn_k_ranges, dim=0))
|
| 203 |
+
|
| 204 |
+
end_values = torch.tensor([ranges[-1, -1].item() for ranges in xattn_q_ranges], dtype=torch.int32)
|
| 205 |
+
offsets = torch.cat((torch.zeros(1, dtype=end_values.dtype), torch.cumsum(end_values[:-1], dim=0)))
|
| 206 |
+
|
| 207 |
+
shifted_tensors = [tensor + int(offset) for tensor, offset in zip(xattn_q_ranges, offsets)]
|
| 208 |
+
xattn_q_ranges_ts = torch.cat(shifted_tensors, dim=0)
|
| 209 |
+
xattn_k_ranges_ts = torch.cat(xattn_k_ranges, dim=0)
|
| 210 |
+
|
| 211 |
+
cu_seqlens_q = torch.unique(xattn_q_ranges_ts)
|
| 212 |
+
cu_seqlens_k = torch.unique(xattn_k_ranges_ts)
|
| 213 |
+
assert (
|
| 214 |
+
cu_seqlens_q.shape == cu_seqlens_k.shape
|
| 215 |
+
), f"cu_seqlens_q.shape: {cu_seqlens_q.shape}, cu_seqlens_k.shape: {cu_seqlens_k.shape}, "
|
| 216 |
+
|
| 217 |
+
return PackedCrossAttnParams(
|
| 218 |
+
q_ranges=xattn_q_ranges_ts,
|
| 219 |
+
kv_ranges=xattn_k_ranges_ts,
|
| 220 |
+
cu_seqlens_q=cu_seqlens_q,
|
| 221 |
+
cu_seqlens_kv=cu_seqlens_k,
|
| 222 |
+
max_seqlen_q=seq_len_cur_rank,
|
| 223 |
+
max_seqlen_kv=cross_attn_params.max_seqlen_kv,
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def cp_ulysses_process(
|
| 228 |
+
cp_size: int,
|
| 229 |
+
x: torch.Tensor,
|
| 230 |
+
condition_map: torch.Tensor,
|
| 231 |
+
rope: torch.Tensor,
|
| 232 |
+
xattn_mask_for_cuda_graph: Union[torch.Tensor, None],
|
| 233 |
+
cross_attn_params: PackedCrossAttnParams,
|
| 234 |
+
):
|
| 235 |
+
seq_len, N, D = x.shape
|
| 236 |
+
assert seq_len == rope.size(0), f"seq_len: {seq_len} != rope.size(0): {rope.size(0)}"
|
| 237 |
+
assert condition_map.size(0) == seq_len, f"condition_map.size(0): {condition_map.size(0)} != seq_len: {seq_len}"
|
| 238 |
+
|
| 239 |
+
# Part1: split for CP
|
| 240 |
+
cp_split_sizes = [seq_len // cp_size] * cp_size
|
| 241 |
+
for i in range(seq_len % cp_size):
|
| 242 |
+
cp_split_sizes[i] += 1
|
| 243 |
+
|
| 244 |
+
# Part2: scatter to CP
|
| 245 |
+
x = scatter_to_context_parallel_region(x, cp_split_sizes)
|
| 246 |
+
condition_map = scatter_to_context_parallel_region(condition_map, cp_split_sizes)
|
| 247 |
+
rope = scatter_to_context_parallel_region(rope, cp_split_sizes)
|
| 248 |
+
|
| 249 |
+
# Part3: update cross_attn cross_attn_params
|
| 250 |
+
cross_attn_params = cp_update_cross_attn_qkv_range(cross_attn_params, N, cp_split_sizes, x.device)
|
| 251 |
+
if xattn_mask_for_cuda_graph is not None:
|
| 252 |
+
cross_attn_params = update_packed_seq_params_for_cuda_graph(cross_attn_params, xattn_mask_for_cuda_graph)
|
| 253 |
+
|
| 254 |
+
return x, condition_map, rope, cp_split_sizes, cross_attn_params
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def cp_shuffle_overlap_process(
|
| 258 |
+
cp_size: int,
|
| 259 |
+
x: torch.Tensor,
|
| 260 |
+
condition_map: torch.Tensor,
|
| 261 |
+
rope: torch.Tensor,
|
| 262 |
+
xattn_mask_for_cuda_graph: Union[torch.Tensor, None],
|
| 263 |
+
ardf_meta: dict,
|
| 264 |
+
core_attn_params: PackedCoreAttnParams,
|
| 265 |
+
cross_attn_params: PackedCrossAttnParams,
|
| 266 |
+
):
|
| 267 |
+
seq_len, N, D = x.shape
|
| 268 |
+
assert seq_len == rope.size(0), f"seq_len: {seq_len} != rope.size(0): {rope.size(0)}"
|
| 269 |
+
assert condition_map.size(0) == seq_len, f"condition_map.size(0): {condition_map.size(0)} != seq_len: {seq_len}"
|
| 270 |
+
cp_shuffle_num = ardf_meta["denoising_range_num"]
|
| 271 |
+
|
| 272 |
+
# Part1: calculate cp_pad_size and cp_split_sizes
|
| 273 |
+
cp_pad_size = 0
|
| 274 |
+
if divide(seq_len, cp_shuffle_num) % cp_size != 0:
|
| 275 |
+
cp_pad_size = (cp_size - divide(seq_len, cp_shuffle_num) % cp_size) * cp_shuffle_num
|
| 276 |
+
cp_split_sizes = [(seq_len + cp_pad_size) // cp_size] * cp_size
|
| 277 |
+
|
| 278 |
+
# Part2: scatter to CP
|
| 279 |
+
x = scatter_to_context_parallel_region(x, cp_split_sizes, cp_shuffle_num, cp_pad_size)
|
| 280 |
+
condition_map = scatter_to_context_parallel_region(condition_map, cp_split_sizes, cp_shuffle_num, cp_pad_size)
|
| 281 |
+
rope = scatter_to_context_parallel_region(rope, cp_split_sizes, cp_shuffle_num, cp_pad_size)
|
| 282 |
+
|
| 283 |
+
# Part3: update core_attn_params
|
| 284 |
+
gcd = math.gcd(seq_len, seq_len + cp_pad_size)
|
| 285 |
+
_sq = seq_len // gcd
|
| 286 |
+
_psq = (seq_len + cp_pad_size) // gcd
|
| 287 |
+
q_range = ardf_meta["q_range"] * _psq // _sq
|
| 288 |
+
max_seqlen_q = ardf_meta["max_seqlen_q"] * _psq // _sq
|
| 289 |
+
core_attn_params = PackedCoreAttnParams(
|
| 290 |
+
q_range=q_range,
|
| 291 |
+
k_range=ardf_meta["k_range"],
|
| 292 |
+
np_q_range=q_range.cpu().numpy(),
|
| 293 |
+
np_k_range=ardf_meta["k_range"].cpu().numpy(),
|
| 294 |
+
max_seqlen_q=max_seqlen_q,
|
| 295 |
+
max_seqlen_k=ardf_meta["max_seqlen_k"],
|
| 296 |
+
)
|
| 297 |
+
|
| 298 |
+
# Part4: update cross_attn cross_attn_params
|
| 299 |
+
cross_attn_params = cp_update_cross_attn_qkv_range(
|
| 300 |
+
cross_attn_params, N, cp_split_sizes, x.device, cp_shuffle_num, cp_pad_size
|
| 301 |
+
)
|
| 302 |
+
if xattn_mask_for_cuda_graph is not None:
|
| 303 |
+
cross_attn_params = update_packed_seq_params_for_cuda_graph(cross_attn_params, xattn_mask_for_cuda_graph)
|
| 304 |
+
|
| 305 |
+
return x, condition_map, rope, cp_pad_size, cp_split_sizes, core_attn_params, cross_attn_params
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
def cp_pre_process(
|
| 309 |
+
cp_size: int,
|
| 310 |
+
cp_strategy: str,
|
| 311 |
+
x: torch.Tensor,
|
| 312 |
+
condition_map: torch.Tensor,
|
| 313 |
+
rope: torch.Tensor,
|
| 314 |
+
xattn_mask_for_cuda_graph: Union[torch.Tensor, None],
|
| 315 |
+
ardf_meta: dict,
|
| 316 |
+
core_attn_params: PackedCoreAttnParams,
|
| 317 |
+
cross_attn_params: PackedCrossAttnParams,
|
| 318 |
+
):
|
| 319 |
+
"""
|
| 320 |
+
This function is used to handle context parallel behavior,
|
| 321 |
+
split input tensors into multiple parts and scatter them to different GPUs.
|
| 322 |
+
|
| 323 |
+
Input:
|
| 324 |
+
cp_strategy: str. cp_ulysses for hopper or newer, cp_shuffle_overlap for 4090 or older
|
| 325 |
+
x: (S, N, D). torch.Tensor of inputs embedding (images or latent representations of images)
|
| 326 |
+
condition_map: (N * S). torch.Tensor determine which condition to use for each token
|
| 327 |
+
rope: (S, 96). torch.Tensor of rope
|
| 328 |
+
xattn_mask_for_cuda_graph: (N * denoising_range_num, L, 1, 1). torch.Tensor of xattn mask for cuda graph, None means no cuda graph
|
| 329 |
+
core_attn_params: PackedCoreAttnParams. Packed sequence parameters for core_atten
|
| 330 |
+
cross_attn_params: PackedCrossAttnParams. Packed sequence parameters for cross_atten
|
| 331 |
+
|
| 332 |
+
Output:
|
| 333 |
+
x: (S', N, D). torch.Tensor of inputs embedding (images or latent representations of images)
|
| 334 |
+
condition_map: (N * S'). torch.Tensor determine which condition to use for each token
|
| 335 |
+
rope: (S', 96). torch.Tensor of rope
|
| 336 |
+
cp_split_sizes: List[int]. Split sizes for each rank
|
| 337 |
+
core_attn_params: PackedCoreAttnParams
|
| 338 |
+
cross_attn_params: PackedCrossAttnParams
|
| 339 |
+
"""
|
| 340 |
+
if cp_size == 1:
|
| 341 |
+
return x, condition_map, rope, None, None, core_attn_params, cross_attn_params
|
| 342 |
+
if cp_strategy == "cp_ulysses":
|
| 343 |
+
(x, condition_map, rope, cp_split_sizes, cross_attn_params) = cp_ulysses_process(
|
| 344 |
+
cp_size, x, condition_map, rope, xattn_mask_for_cuda_graph, cross_attn_params
|
| 345 |
+
)
|
| 346 |
+
return (x, condition_map, rope, 0, cp_split_sizes, core_attn_params, cross_attn_params)
|
| 347 |
+
elif cp_strategy == "cp_shuffle_overlap":
|
| 348 |
+
(
|
| 349 |
+
x,
|
| 350 |
+
condition_map,
|
| 351 |
+
rope,
|
| 352 |
+
cp_pad_size,
|
| 353 |
+
cp_split_sizes,
|
| 354 |
+
core_attn_params,
|
| 355 |
+
cross_attn_params,
|
| 356 |
+
) = cp_shuffle_overlap_process(
|
| 357 |
+
cp_size, x, condition_map, rope, xattn_mask_for_cuda_graph, ardf_meta, core_attn_params, cross_attn_params
|
| 358 |
+
)
|
| 359 |
+
return (x, condition_map, rope, cp_pad_size, cp_split_sizes, core_attn_params, cross_attn_params)
|
| 360 |
+
else:
|
| 361 |
+
raise ValueError(f"Invalid CP strategy: {cp_strategy}, expected cp_ulysses or cp_shuffle_overlap")
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
def cp_post_process(cp_size: int, cp_strategy: str, x: torch.Tensor, meta_args: ModelMetaArgs) -> torch.Tensor:
|
| 365 |
+
if cp_size == 1:
|
| 366 |
+
return x
|
| 367 |
+
if cp_strategy == "cp_shuffle_overlap":
|
| 368 |
+
x = gather_from_context_parallel_region(
|
| 369 |
+
x, meta_args.cp_split_sizes, meta_args.denoising_range_num, meta_args.cp_pad_size
|
| 370 |
+
)
|
| 371 |
+
elif cp_strategy == "cp_ulysses":
|
| 372 |
+
x = gather_from_context_parallel_region(x, meta_args.cp_split_sizes)
|
| 373 |
+
else:
|
| 374 |
+
raise ValueError(f"Invalid CP strategy: {cp_strategy}, expected cp_ulysses or cp_shuffle_overlap")
|
| 375 |
+
return x
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
#####################################################
|
| 379 |
+
# Ulysses Attention Pipeline
|
| 380 |
+
#####################################################
|
| 381 |
+
def all_to_all_input_split(tensor: torch.Tensor, cp_split_sizes: List[int]) -> Tuple[torch.Tensor, torch.distributed.Work]:
|
| 382 |
+
"""
|
| 383 |
+
Scatter head_number and gather seq_len, for example:
|
| 384 |
+
input: (seq_len, cp * hn, hd)
|
| 385 |
+
output: (seq_len * cp, hn, hd)
|
| 386 |
+
NOTE: seq_len of input maybe not equal, which depends on cp_split_sizes[mpu.get_cp_rank()]
|
| 387 |
+
"""
|
| 388 |
+
cp_world_size = mpu.get_cp_world_size()
|
| 389 |
+
if cp_world_size == 1:
|
| 390 |
+
return tensor, FakeHandle()
|
| 391 |
+
assert cp_split_sizes is not None
|
| 392 |
+
_, hn, _ = tensor.shape
|
| 393 |
+
if cp_world_size % hn == 0 and cp_world_size != hn:
|
| 394 |
+
tensor = torch.repeat_interleave(tensor, repeats=divide(cp_world_size, hn), dim=1).contiguous()
|
| 395 |
+
assert tensor.is_contiguous()
|
| 396 |
+
input = rearrange(tensor, "seq (cp hn) hd -> (cp seq) hn hd", cp=cp_world_size).contiguous()
|
| 397 |
+
output = torch.empty([sum(cp_split_sizes), *input.shape[1:]], device=input.device, dtype=input.dtype)
|
| 398 |
+
handle = torch.distributed.all_to_all_single(
|
| 399 |
+
output, input, output_split_sizes=cp_split_sizes, group=mpu.get_cp_group(), async_op=True
|
| 400 |
+
)
|
| 401 |
+
return output, handle
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def all_to_all_output_split(tensor: torch.Tensor, cp_split_sizes: List[int]) -> Tuple[torch.Tensor, torch.distributed.Work]:
|
| 405 |
+
"""
|
| 406 |
+
Scatter seq_len and gather head_number, for example:
|
| 407 |
+
input: (seq_len * cp, hn, hd)
|
| 408 |
+
output: (seq_len, cp * hn, hd)
|
| 409 |
+
NOTE: seq_len of output maybe not equal, which depends on cp_split_sizes[mpu.get_cp_rank()]
|
| 410 |
+
"""
|
| 411 |
+
cp_world_size = mpu.get_cp_world_size()
|
| 412 |
+
if cp_world_size == 1:
|
| 413 |
+
return tensor, FakeHandle()
|
| 414 |
+
assert cp_split_sizes is not None
|
| 415 |
+
assert tensor.is_contiguous()
|
| 416 |
+
_, hn, _ = tensor.shape
|
| 417 |
+
output = torch.empty(
|
| 418 |
+
[cp_split_sizes[mpu.get_cp_rank()] * cp_world_size, *tensor.shape[1:]], device=tensor.device, dtype=tensor.dtype
|
| 419 |
+
)
|
| 420 |
+
handle = torch.distributed.all_to_all_single(
|
| 421 |
+
output, tensor, input_split_sizes=cp_split_sizes, group=mpu.get_cp_group(), async_op=True
|
| 422 |
+
)
|
| 423 |
+
return output, handle
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
def fused_qkv_communication(
|
| 427 |
+
q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, cp_split_sizes: List[int]
|
| 428 |
+
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 429 |
+
cp_world_size = mpu.get_cp_world_size()
|
| 430 |
+
if cp_world_size == 1:
|
| 431 |
+
return q, k, v
|
| 432 |
+
assert cp_split_sizes is not None
|
| 433 |
+
_, k_head, _ = k.shape
|
| 434 |
+
if cp_world_size % k_head == 0 and cp_world_size != k_head:
|
| 435 |
+
k = torch.repeat_interleave(k, repeats=divide(cp_world_size, k_head), dim=1)
|
| 436 |
+
v = torch.repeat_interleave(v, repeats=divide(cp_world_size, k_head), dim=1)
|
| 437 |
+
|
| 438 |
+
q = rearrange(q, "seq (cp hn) hd -> (cp seq) hn hd", cp=cp_world_size).contiguous()
|
| 439 |
+
k = rearrange(k, "seq (cp hn) hd -> (cp seq) hn hd", cp=cp_world_size).contiguous()
|
| 440 |
+
v = rearrange(v, "seq (cp hn) hd -> (cp seq) hn hd", cp=cp_world_size).contiguous()
|
| 441 |
+
head_split_number = [q.shape[1], k.shape[1], v.shape[1]]
|
| 442 |
+
qkv = torch.cat([q, k, v], dim=1).contiguous()
|
| 443 |
+
|
| 444 |
+
qkv_output = torch.empty([sum(cp_split_sizes), *qkv.shape[1:]], device=qkv.device, dtype=qkv.dtype)
|
| 445 |
+
torch.distributed.all_to_all_single(
|
| 446 |
+
qkv_output, qkv, output_split_sizes=cp_split_sizes, group=mpu.get_cp_group(), async_op=False
|
| 447 |
+
)
|
| 448 |
+
q, k, v = torch.split(qkv_output, head_split_number, dim=1)
|
| 449 |
+
return q, k, v
|
| 450 |
+
|
| 451 |
+
|
| 452 |
+
class UlyssesScheduler:
|
| 453 |
+
def __init__(self):
|
| 454 |
+
pass
|
| 455 |
+
|
| 456 |
+
@staticmethod
|
| 457 |
+
def get_attn_and_xattn_with_comm_overlap(
|
| 458 |
+
get_q_func: Callable, # [seq hn hd]
|
| 459 |
+
get_k_func: Callable, # [seq hn hd]
|
| 460 |
+
get_v_func: Callable, # [seq hn hd]
|
| 461 |
+
kv_cache_func: Callable,
|
| 462 |
+
core_attn_func: Callable,
|
| 463 |
+
cross_attn_func: Callable,
|
| 464 |
+
overlap_degree: int,
|
| 465 |
+
batch_size: int,
|
| 466 |
+
cp_size: int,
|
| 467 |
+
cp_split_sizes: List[int] = None,
|
| 468 |
+
):
|
| 469 |
+
"""
|
| 470 |
+
Get Q, K, V with communication overlap.
|
| 471 |
+
Input:
|
| 472 |
+
get_q: Callable, function to get q, shape [b, sq, hn, hd]
|
| 473 |
+
get_k: Callable, function to get k, shape [sq, b, hn, hd]
|
| 474 |
+
get_v: Callable, function to get v, shape [sq, b, hn, hd]
|
| 475 |
+
NOTE: Why follow such compute and comm order?
|
| 476 |
+
1. v_compute
|
| 477 |
+
2. k_compute(overlap with v_comm)
|
| 478 |
+
3. q_compute(overlap with k_comm)
|
| 479 |
+
4. kv_cache_func(overlap with q_comm)
|
| 480 |
+
Follow the principle: We need to begin comm as soon as possible to hide the comm latency.
|
| 481 |
+
The computation flops and commnunication order is:
|
| 482 |
+
flops order: q_compute (larger hidden_size + layernorm) > k_compute (layernorm) > v_compute
|
| 483 |
+
comm order: q_compute (larger hidden_size) > k_compute = v_compute
|
| 484 |
+
"""
|
| 485 |
+
value = get_v_func()
|
| 486 |
+
value, handle_v = all_to_all_input_split(value, cp_split_sizes)
|
| 487 |
+
key = get_k_func()
|
| 488 |
+
key, handle_k = all_to_all_input_split(key, cp_split_sizes)
|
| 489 |
+
query = get_q_func()
|
| 490 |
+
query, handle_q = all_to_all_input_split(query, cp_split_sizes)
|
| 491 |
+
|
| 492 |
+
handle_v.wait()
|
| 493 |
+
handle_k.wait()
|
| 494 |
+
kv = torch.concat([key, value], dim=-1)
|
| 495 |
+
|
| 496 |
+
key, value = kv_cache_func(kv)
|
| 497 |
+
handle_q.wait()
|
| 498 |
+
return UlyssesScheduler.get_attn_and_xattn_base(
|
| 499 |
+
query, key, value, core_attn_func, cross_attn_func, overlap_degree, batch_size, cp_size, cp_split_sizes
|
| 500 |
+
)
|
| 501 |
+
|
| 502 |
+
@staticmethod
|
| 503 |
+
def get_attn_and_xattn_with_fused_kv_comm(
|
| 504 |
+
get_q_func: Callable,
|
| 505 |
+
get_kv_func: Callable,
|
| 506 |
+
kv_cache_func: Callable,
|
| 507 |
+
core_attn_func: Callable,
|
| 508 |
+
cross_attn_func: Callable,
|
| 509 |
+
overlap_degree: int,
|
| 510 |
+
batch_size: int,
|
| 511 |
+
cp_size: int,
|
| 512 |
+
cp_split_sizes: List[int] = None,
|
| 513 |
+
):
|
| 514 |
+
"""
|
| 515 |
+
When seq_len is very small, CPU-bound issues are severe. By fusing kv communication,
|
| 516 |
+
CPU operations and the number of kernel launches are reduced.
|
| 517 |
+
"""
|
| 518 |
+
kv = get_kv_func()
|
| 519 |
+
kv, handle_kv = all_to_all_input_split(kv, cp_split_sizes)
|
| 520 |
+
query = get_q_func()
|
| 521 |
+
query, handle_q = all_to_all_input_split(query, cp_split_sizes)
|
| 522 |
+
handle_kv.wait()
|
| 523 |
+
key, value = kv_cache_func(kv)
|
| 524 |
+
handle_q.wait()
|
| 525 |
+
return UlyssesScheduler.get_attn_and_xattn_base(
|
| 526 |
+
query, key, value, core_attn_func, cross_attn_func, overlap_degree, batch_size, cp_size, cp_split_sizes
|
| 527 |
+
)
|
| 528 |
+
|
| 529 |
+
def get_attn_and_xattn_with_fused_qkv_comm(
|
| 530 |
+
get_qkv_func: Callable,
|
| 531 |
+
kv_cache_func: Callable,
|
| 532 |
+
core_attn_func: Callable,
|
| 533 |
+
cross_attn_func: Callable,
|
| 534 |
+
overlap_degree: int,
|
| 535 |
+
batch_size: int,
|
| 536 |
+
cp_size: int,
|
| 537 |
+
cp_split_sizes: List[int] = None,
|
| 538 |
+
):
|
| 539 |
+
"""
|
| 540 |
+
By fusing the communication of q, k, and v together, further optimize CPU-bound issues.
|
| 541 |
+
"""
|
| 542 |
+
q, k, v = get_qkv_func()
|
| 543 |
+
q, k, v = fused_qkv_communication(q, k, v, cp_split_sizes)
|
| 544 |
+
k, v = kv_cache_func(torch.cat([k, v], dim=-1))
|
| 545 |
+
return UlyssesScheduler.get_attn_and_xattn_base(
|
| 546 |
+
q, k, v, core_attn_func, cross_attn_func, overlap_degree, batch_size, cp_size, cp_split_sizes
|
| 547 |
+
)
|
| 548 |
+
|
| 549 |
+
@staticmethod
|
| 550 |
+
def get_attn_and_xattn_base(
|
| 551 |
+
query: torch.Tensor,
|
| 552 |
+
key: torch.Tensor,
|
| 553 |
+
value: torch.Tensor,
|
| 554 |
+
core_attn_func: Callable,
|
| 555 |
+
cross_attn_func: Callable,
|
| 556 |
+
overlap_degree: int,
|
| 557 |
+
batch_size: int,
|
| 558 |
+
cp_size: int,
|
| 559 |
+
cp_split_sizes: List[int] = None,
|
| 560 |
+
):
|
| 561 |
+
# Split Query, Key, Value into multiple parts
|
| 562 |
+
# k/v may have different sequence length with q due to kv cache
|
| 563 |
+
q_seq, q_head, q_hidden = query.shape
|
| 564 |
+
kv_seq, kv_head, kv_hidden = key.shape
|
| 565 |
+
if overlap_degree == -1:
|
| 566 |
+
overlap_degree = q_head // kv_head
|
| 567 |
+
else:
|
| 568 |
+
assert overlap_degree <= q_head
|
| 569 |
+
|
| 570 |
+
if overlap_degree == 1:
|
| 571 |
+
query = [query]
|
| 572 |
+
elif kv_head == 1: # MQA
|
| 573 |
+
query = query.chunk(overlap_degree, dim=1)
|
| 574 |
+
else: # GQA
|
| 575 |
+
assert q_head % (overlap_degree * kv_head) == 0
|
| 576 |
+
query = query.reshape(q_seq, kv_head, -1, q_hidden)
|
| 577 |
+
query = query.chunk(overlap_degree, dim=2)
|
| 578 |
+
query = [q.reshape(q_seq, -1, q_hidden) for q in query]
|
| 579 |
+
|
| 580 |
+
# Compute Core Attention
|
| 581 |
+
handle_attn = None
|
| 582 |
+
core_attn_out = None
|
| 583 |
+
core_attn_outs = []
|
| 584 |
+
for i in range(overlap_degree):
|
| 585 |
+
core_attn_out_new = core_attn_func(query[i], key, value)
|
| 586 |
+
if not torch.isfinite(core_attn_out_new).all():
|
| 587 |
+
import pdb; pdb.set_trace()
|
| 588 |
+
if handle_attn is not None:
|
| 589 |
+
handle_attn.wait()
|
| 590 |
+
core_attn_outs.append(core_attn_out)
|
| 591 |
+
core_attn_out, handle_attn = all_to_all_output_split(core_attn_out_new, cp_split_sizes)
|
| 592 |
+
if not torch.isfinite(core_attn_out).all():
|
| 593 |
+
import pdb; pdb.set_trace()
|
| 594 |
+
|
| 595 |
+
xattn_out = cross_attn_func()
|
| 596 |
+
handle_attn.wait()
|
| 597 |
+
if not torch.isfinite(core_attn_out).all():
|
| 598 |
+
import pdb; pdb.set_trace()
|
| 599 |
+
core_attn_outs.append(core_attn_out)
|
| 600 |
+
core_attn_out = torch.cat(core_attn_outs, dim=1)
|
| 601 |
+
|
| 602 |
+
if not torch.isfinite(core_attn_out).all():
|
| 603 |
+
import pdb; pdb.set_trace()
|
| 604 |
+
|
| 605 |
+
core_attn_out = rearrange(core_attn_out, "(cp sq b) hn hd -> (sq) b (cp hn hd)", cp=cp_size, b=batch_size)
|
| 606 |
+
return core_attn_out, xattn_out
|
| 607 |
+
|
| 608 |
+
|
| 609 |
+
#####################################################
|
| 610 |
+
# CSO(context shuffle overlap) Attention Pipeline
|
| 611 |
+
#####################################################
|
| 612 |
+
def cso_communication(
|
| 613 |
+
input: torch.Tensor, cp_world_size: int, cp_split_sizes: List[int], comm_type: str = None
|
| 614 |
+
) -> Tuple[torch.Tensor, torch.distributed.Work]:
|
| 615 |
+
if cp_world_size == 1:
|
| 616 |
+
return input, FakeHandle()
|
| 617 |
+
assert cp_split_sizes is not None
|
| 618 |
+
_, hn, _ = input.shape
|
| 619 |
+
if comm_type == "kv":
|
| 620 |
+
if cp_world_size % hn == 0 and cp_world_size != hn:
|
| 621 |
+
input = torch.repeat_interleave(input, repeats=divide(cp_world_size, hn), dim=1)
|
| 622 |
+
input = rearrange(input, "spb (cp hn) hd -> (cp spb) hn hd", cp=cp_world_size).contiguous()
|
| 623 |
+
output = torch.empty(input.shape, device=input.device, dtype=input.dtype)
|
| 624 |
+
|
| 625 |
+
handle = torch.distributed.all_to_all_single(
|
| 626 |
+
output, input, input_split_sizes=cp_split_sizes, group=mpu.get_cp_group(), async_op=True
|
| 627 |
+
)
|
| 628 |
+
|
| 629 |
+
return output, handle
|
| 630 |
+
|
| 631 |
+
|
| 632 |
+
class CSOHelper:
|
| 633 |
+
def __init__(self, cp_shuffle_num, cp_world_size, cp_split_sizes):
|
| 634 |
+
self.cp_shuffle_num = cp_shuffle_num
|
| 635 |
+
self.cp_world_size = cp_world_size
|
| 636 |
+
self.cp_split_sizes = [divide(x, self.cp_shuffle_num) for x in cp_split_sizes]
|
| 637 |
+
|
| 638 |
+
def split_query_for_overlap(self, query):
|
| 639 |
+
query = rearrange(
|
| 640 |
+
query, "(dn spb) (cp hn) hd -> (dn cp spb) hn hd", cp=self.cp_world_size, dn=self.cp_shuffle_num
|
| 641 |
+
).contiguous()
|
| 642 |
+
querys = list(torch.chunk(query, self.cp_shuffle_num, dim=0))
|
| 643 |
+
querys[0], handle_q = cso_communication(querys[0], self.cp_world_size, self.cp_split_sizes)
|
| 644 |
+
return querys, handle_q
|
| 645 |
+
|
| 646 |
+
def overlap(self, fattn, qs, k, v):
|
| 647 |
+
core_attn_outs = []
|
| 648 |
+
for i in range(self.cp_shuffle_num):
|
| 649 |
+
if self.cp_shuffle_num == 1:
|
| 650 |
+
q = qs[0]
|
| 651 |
+
elif i == 0:
|
| 652 |
+
q = qs[0]
|
| 653 |
+
loop_var, loop_handle = cso_communication(qs[i + 1], self.cp_world_size, self.cp_split_sizes)
|
| 654 |
+
else:
|
| 655 |
+
loop_handle.wait()
|
| 656 |
+
if loop_var.numel() == qs[0].numel():
|
| 657 |
+
q = loop_var
|
| 658 |
+
else:
|
| 659 |
+
assert loop_var.numel() == qs[0].numel() * 2
|
| 660 |
+
q, ready_o = torch.chunk(loop_var, 2, dim=-1)
|
| 661 |
+
core_attn_outs.append(ready_o)
|
| 662 |
+
loop_var = torch.concat([qs[i + 1], o], dim=-1) if i < self.cp_shuffle_num - 1 else o
|
| 663 |
+
loop_var, loop_handle = cso_communication(loop_var, self.cp_world_size, self.cp_split_sizes)
|
| 664 |
+
|
| 665 |
+
o = fattn(q, k, v, i)
|
| 666 |
+
if i == self.cp_shuffle_num - 1:
|
| 667 |
+
if i != 0:
|
| 668 |
+
loop_handle.wait()
|
| 669 |
+
assert loop_var.numel() == qs[0].numel()
|
| 670 |
+
core_attn_outs.append(loop_var)
|
| 671 |
+
last_o, handle_attn = cso_communication(o, self.cp_world_size, self.cp_split_sizes)
|
| 672 |
+
core_attn_outs.append(last_o)
|
| 673 |
+
return core_attn_outs, handle_attn
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/parallelism/pipeline_parallel.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2025 SandAI. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import queue
|
| 16 |
+
from dataclasses import dataclass
|
| 17 |
+
from typing import Optional
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
|
| 21 |
+
from inference.infra.distributed import parallel_state as mpu
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@dataclass
|
| 25 |
+
class TensorAndHandler:
|
| 26 |
+
tensor: torch.Tensor
|
| 27 |
+
handler: torch.distributed.Work
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class PPScheduler:
|
| 31 |
+
def __init__(self):
|
| 32 |
+
"""Initialize an instance of the PPScheduler class"""
|
| 33 |
+
|
| 34 |
+
self.device: torch.device = torch.device(f"cuda:{torch.cuda.current_device()}")
|
| 35 |
+
self.recv_queue: queue.Queue = queue.Queue()
|
| 36 |
+
|
| 37 |
+
def isend_next(self, tensor: torch.Tensor) -> torch.distributed.Work:
|
| 38 |
+
"""Asynchronously send a tensor to the next pipeline and return the send handle.
|
| 39 |
+
|
| 40 |
+
Args:
|
| 41 |
+
tensor (torch.Tensor): The tensor to be sent.
|
| 42 |
+
|
| 43 |
+
Returns:
|
| 44 |
+
torch.distributed.Work: The handle for the send operation.
|
| 45 |
+
"""
|
| 46 |
+
handle = torch.distributed.isend(
|
| 47 |
+
tensor.contiguous(), dst=mpu.get_pipeline_model_parallel_next_rank(), group=mpu.get_pp_group()
|
| 48 |
+
)
|
| 49 |
+
return handle
|
| 50 |
+
|
| 51 |
+
def irecv_prev(self, buffer: torch.Tensor) -> torch.distributed.Work:
|
| 52 |
+
"""Asynchronously receive a tensor from the previous pipeline and return the receive handle.
|
| 53 |
+
|
| 54 |
+
Args:
|
| 55 |
+
buffer (torch.Tensor): The buffer tensor for receiving data.
|
| 56 |
+
|
| 57 |
+
Returns:
|
| 58 |
+
torch.distributed.Work: The handle for the receive operation.
|
| 59 |
+
"""
|
| 60 |
+
handle = torch.distributed.irecv(buffer, src=mpu.get_pipeline_model_parallel_prev_rank(), group=mpu.get_pp_group())
|
| 61 |
+
return handle
|
| 62 |
+
|
| 63 |
+
def recv_prev_data(self, shape: torch.Size, dtype: torch.dtype) -> torch.Tensor:
|
| 64 |
+
"""Receive data from the previous pipeline and return the received tensor.
|
| 65 |
+
|
| 66 |
+
Args:
|
| 67 |
+
shape (torch.Size): The shape of the tensor to receive.
|
| 68 |
+
dtype (torch.dtype): The data type of the tensor to receive.
|
| 69 |
+
|
| 70 |
+
Returns:
|
| 71 |
+
torch.Tensor: The received tensor.
|
| 72 |
+
"""
|
| 73 |
+
recv_tensor = torch.empty(shape, dtype=dtype, device=self.device)
|
| 74 |
+
self.irecv_prev(recv_tensor).wait()
|
| 75 |
+
return recv_tensor
|
| 76 |
+
|
| 77 |
+
def queue_irecv_prev(self, shape: torch.Size, dtype: torch.dtype) -> None:
|
| 78 |
+
"""Put the asynchronously received tensor and handle into the receive queue.
|
| 79 |
+
|
| 80 |
+
Args:
|
| 81 |
+
shape (torch.Size): The shape of the tensor to receive.
|
| 82 |
+
dtype (torch.dtype): The data type of the tensor to receive.
|
| 83 |
+
"""
|
| 84 |
+
recv_tensor = torch.empty(shape, dtype=dtype, device=self.device)
|
| 85 |
+
handle = self.irecv_prev(recv_tensor)
|
| 86 |
+
self.recv_queue.put(TensorAndHandler(tensor=recv_tensor, handler=handle))
|
| 87 |
+
|
| 88 |
+
def queue_irecv_prev_data(self) -> torch.Tensor:
|
| 89 |
+
"""Get a tensor from the receive queue and wait for the receive operation to complete.
|
| 90 |
+
|
| 91 |
+
Returns:
|
| 92 |
+
torch.Tensor: The received tensor obtained from the queue.
|
| 93 |
+
"""
|
| 94 |
+
tensor_and_handler = self.recv_queue.get()
|
| 95 |
+
tensor_and_handler.handler.wait()
|
| 96 |
+
return tensor_and_handler.tensor
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
_PP_SCHEDULER: Optional[PPScheduler] = None
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def init_pp_scheduler():
|
| 103 |
+
"""Initialize the PPScheduler instance.
|
| 104 |
+
|
| 105 |
+
Raises:
|
| 106 |
+
AssertionError: If the PPScheduler is already initialized.
|
| 107 |
+
"""
|
| 108 |
+
global _PP_SCHEDULER
|
| 109 |
+
assert _PP_SCHEDULER is None, "pipeline model parallel group is already initialized"
|
| 110 |
+
_PP_SCHEDULER = PPScheduler()
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def pp_scheduler() -> PPScheduler:
|
| 114 |
+
"""Get the current PPScheduler instance.
|
| 115 |
+
|
| 116 |
+
Returns:
|
| 117 |
+
PPScheduler: The current PPScheduler instance.
|
| 118 |
+
|
| 119 |
+
Raises:
|
| 120 |
+
AssertionError: If the PPScheduler has not been initialized.
|
| 121 |
+
"""
|
| 122 |
+
assert _PP_SCHEDULER is not None, "pipeline model parallel group is not initialized"
|
| 123 |
+
return _PP_SCHEDULER
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/infra/parallelism/tile_parallel.py
ADDED
|
@@ -0,0 +1,448 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2025 SandAI. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from collections import OrderedDict
|
| 16 |
+
from typing import List
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
from tqdm import tqdm
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class ParallelHelper:
|
| 23 |
+
def __init__(self):
|
| 24 |
+
pass
|
| 25 |
+
|
| 26 |
+
@staticmethod
|
| 27 |
+
def split_tile_list(
|
| 28 |
+
tile_numel_dict: OrderedDict[int, int], parallel_group: torch.distributed.ProcessGroup = None
|
| 29 |
+
) -> List[int]:
|
| 30 |
+
"""
|
| 31 |
+
Splits the given tile size into a list of sizes that each rank should handle.
|
| 32 |
+
|
| 33 |
+
This method takes into account the number of ranks in a distributed setting.
|
| 34 |
+
If the distributed environment is not initialized, it returns a list of
|
| 35 |
+
integers from 0 to tile_size - 1, representing each tile index.
|
| 36 |
+
|
| 37 |
+
If the distributed environment is initialized, it calculates the base tile size
|
| 38 |
+
for each rank and distributes any remaining tiles among the ranks.
|
| 39 |
+
|
| 40 |
+
Args:
|
| 41 |
+
tile_numel_dict (OrderedDict[int, int]): Dict of index and numel of tiles.
|
| 42 |
+
parallel_group (torch.distributed.ProcessGroup, optional):
|
| 43 |
+
Distributed decoding group. Defaults to None.
|
| 44 |
+
|
| 45 |
+
Returns:
|
| 46 |
+
List[int]: A list of tile indices assigned to the current rank.
|
| 47 |
+
List[int]: A list of global tile indices.
|
| 48 |
+
"""
|
| 49 |
+
if not torch.distributed.is_initialized():
|
| 50 |
+
return list(range(len(tile_numel_dict))), list(range(len(tile_numel_dict)))
|
| 51 |
+
else:
|
| 52 |
+
tile_idxs = list(OrderedDict(sorted(tile_numel_dict.items(), key=lambda x: x[1], reverse=True)).keys())
|
| 53 |
+
world_size = torch.distributed.get_world_size(group=parallel_group)
|
| 54 |
+
cur_rank = torch.distributed.get_rank(group=parallel_group)
|
| 55 |
+
global_tile_idxs = []
|
| 56 |
+
cur_rank_tile_idxs = []
|
| 57 |
+
for rank in range(world_size):
|
| 58 |
+
rank_tile_idxs = [tile_idxs[rank + world_size * i] for i in range(len(tile_idxs) // world_size)]
|
| 59 |
+
if rank < len(tile_idxs) % world_size:
|
| 60 |
+
rank_tile_idxs.append(tile_idxs[len(tile_idxs) // world_size * world_size + rank])
|
| 61 |
+
if rank == cur_rank:
|
| 62 |
+
cur_rank_tile_idxs = rank_tile_idxs
|
| 63 |
+
global_tile_idxs = global_tile_idxs + rank_tile_idxs
|
| 64 |
+
return cur_rank_tile_idxs, global_tile_idxs
|
| 65 |
+
|
| 66 |
+
@staticmethod
|
| 67 |
+
def gather_frames(
|
| 68 |
+
frames: List[torch.Tensor], global_tile_idxs: List[int], parallel_group: torch.distributed.ProcessGroup = None
|
| 69 |
+
) -> List[torch.Tensor]:
|
| 70 |
+
"""
|
| 71 |
+
Gathers frame data from all ranks in a distributed environment.
|
| 72 |
+
|
| 73 |
+
This method collects frames from all ranks and combines them into a single list.
|
| 74 |
+
If the distributed environment is not initialized, it simply returns the input frames.
|
| 75 |
+
|
| 76 |
+
Args:
|
| 77 |
+
frames (List[torch.Tensor]): A list of frames (tensors) from the current rank.
|
| 78 |
+
global_tile_idxs (List[int]): A list of global tile indices.
|
| 79 |
+
parallel_group (torch.distributed.ProcessGroup, optional):
|
| 80 |
+
Distributed decoding group. Defaults to None.
|
| 81 |
+
|
| 82 |
+
Returns:
|
| 83 |
+
List[torch.Tensor]: A list of frames (tensors) from all ranks.
|
| 84 |
+
"""
|
| 85 |
+
if not torch.distributed.is_initialized():
|
| 86 |
+
return frames
|
| 87 |
+
else:
|
| 88 |
+
# assert len(frames) > 0
|
| 89 |
+
# Communicate shapes
|
| 90 |
+
if len(frames) == 0:
|
| 91 |
+
cur_rank_shapes = []
|
| 92 |
+
else:
|
| 93 |
+
cur_rank_shapes = [frame.shape for frame in frames]
|
| 94 |
+
all_rank_shapes = [None] * torch.distributed.get_world_size(group=parallel_group)
|
| 95 |
+
torch.distributed.all_gather_object(all_rank_shapes, cur_rank_shapes, group=parallel_group)
|
| 96 |
+
|
| 97 |
+
all_rank_sizes = []
|
| 98 |
+
total_size = []
|
| 99 |
+
for per_rank_shapes in all_rank_shapes:
|
| 100 |
+
per_rank_sizes = []
|
| 101 |
+
per_rank_total_size = 0
|
| 102 |
+
for shape in per_rank_shapes:
|
| 103 |
+
per_rank_sizes.append(shape[0] * shape[1] * shape[2] * shape[3] * shape[4])
|
| 104 |
+
per_rank_total_size += shape[0] * shape[1] * shape[2] * shape[3] * shape[4]
|
| 105 |
+
all_rank_sizes.append(per_rank_sizes)
|
| 106 |
+
total_size.append(per_rank_total_size)
|
| 107 |
+
|
| 108 |
+
# Gather all frames
|
| 109 |
+
if len(frames) == 0:
|
| 110 |
+
flattened_frames = torch.zeros([0], dtype=torch.bfloat16, device="cuda")
|
| 111 |
+
else:
|
| 112 |
+
flattened_frames = torch.cat([frame.flatten().contiguous() for frame in frames], dim=0)
|
| 113 |
+
assert flattened_frames.dtype == torch.bfloat16
|
| 114 |
+
gather_tensors = [
|
| 115 |
+
torch.zeros(total_size[i], dtype=torch.bfloat16, device="cuda")
|
| 116 |
+
for i in range(torch.distributed.get_world_size(group=parallel_group))
|
| 117 |
+
]
|
| 118 |
+
torch.distributed.all_gather(gather_tensors, flattened_frames, group=parallel_group)
|
| 119 |
+
|
| 120 |
+
result_frames = []
|
| 121 |
+
for idx, per_rank_shapes in enumerate(all_rank_shapes):
|
| 122 |
+
offset = 0
|
| 123 |
+
for j, shape in enumerate(per_rank_shapes):
|
| 124 |
+
result_frames.append(gather_tensors[idx][offset : offset + all_rank_sizes[idx][j]].view(shape))
|
| 125 |
+
offset += all_rank_sizes[idx][j]
|
| 126 |
+
result_frames_dict = OrderedDict((idx, frame) for idx, frame in zip(global_tile_idxs, result_frames))
|
| 127 |
+
result_frames = list(OrderedDict(sorted(result_frames_dict.items())).values())
|
| 128 |
+
return result_frames
|
| 129 |
+
|
| 130 |
+
@staticmethod
|
| 131 |
+
def index_undot(index: int, loop_size: List[int]) -> List[int]:
|
| 132 |
+
"""
|
| 133 |
+
Converts a single index into a list of indices, representing the position in a multi-dimensional space.
|
| 134 |
+
|
| 135 |
+
This method takes an integer index and a list of loop sizes, and converts the index into a list of indices
|
| 136 |
+
that correspond to the position in a multi-dimensional space.
|
| 137 |
+
|
| 138 |
+
Args:
|
| 139 |
+
index (int): The single index to be converted.
|
| 140 |
+
loop_size (List[int]): A list of integers representing the size of each dimension in the multi-dimensional space.
|
| 141 |
+
|
| 142 |
+
Returns:
|
| 143 |
+
List[int]: A list of integers representing the position in the multi-dimensional space.
|
| 144 |
+
"""
|
| 145 |
+
undotted_index = []
|
| 146 |
+
for i in range(len(loop_size) - 1, -1, -1):
|
| 147 |
+
undotted_index.append(index % loop_size[i])
|
| 148 |
+
index = index // loop_size[i]
|
| 149 |
+
undotted_index.reverse()
|
| 150 |
+
assert len(undotted_index) == len(loop_size)
|
| 151 |
+
return undotted_index
|
| 152 |
+
|
| 153 |
+
@staticmethod
|
| 154 |
+
def index_dot(index: List[int], loop_size: List[int]) -> int:
|
| 155 |
+
"""
|
| 156 |
+
Converts a list of indices into a single index, representing the position in a multi-dimensional space.
|
| 157 |
+
|
| 158 |
+
This method takes a list of indices and a list of loop sizes, and converts the list of indices into a single index
|
| 159 |
+
that corresponds to the position in a multi-dimensional space.
|
| 160 |
+
|
| 161 |
+
Args:
|
| 162 |
+
index (List[int]): A list of integers representing the position in the multi-dimensional space.
|
| 163 |
+
loop_size (List[int]): A list of integers representing the size of each dimension in the multi-dimensional space.
|
| 164 |
+
|
| 165 |
+
Returns:
|
| 166 |
+
int: A single integer representing the position in the multi-dimensional space.
|
| 167 |
+
"""
|
| 168 |
+
assert len(index) == len(loop_size)
|
| 169 |
+
dot_index = 0
|
| 170 |
+
strides = [1]
|
| 171 |
+
for i in range(len(loop_size) - 1, -1, -1):
|
| 172 |
+
strides.append(strides[-1] * loop_size[i])
|
| 173 |
+
strides.reverse()
|
| 174 |
+
strides = strides[1:]
|
| 175 |
+
assert len(index) == len(strides)
|
| 176 |
+
for i in range(len(index)):
|
| 177 |
+
dot_index += index[i] * strides[i]
|
| 178 |
+
return dot_index
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
class TileProcessor:
|
| 182 |
+
def __init__(
|
| 183 |
+
self,
|
| 184 |
+
encode_fn,
|
| 185 |
+
decode_fn,
|
| 186 |
+
tile_sample_min_height: int = 256,
|
| 187 |
+
tile_sample_min_width: int = 256,
|
| 188 |
+
tile_sample_min_length: int = 16,
|
| 189 |
+
spatial_downsample_factor: int = 8,
|
| 190 |
+
temporal_downsample_factor: int = 1,
|
| 191 |
+
spatial_tile_overlap_factor: float = 0.25,
|
| 192 |
+
temporal_tile_overlap_factor: float = 0,
|
| 193 |
+
sr_ratio=1,
|
| 194 |
+
first_frame_as_image: bool = False,
|
| 195 |
+
parallel_group: torch.distributed.ProcessGroup = None,
|
| 196 |
+
):
|
| 197 |
+
"""
|
| 198 |
+
Initializes an instance of the class.
|
| 199 |
+
|
| 200 |
+
Args:
|
| 201 |
+
encode_fn (function): The encoding function used for tile sampling.
|
| 202 |
+
decode_fn (function): The decoding function used for tile reconstruction.
|
| 203 |
+
tile_sample_min_size (int, optional): The minimum size of the sampled tiles. Defaults to 256.
|
| 204 |
+
tile_sample_min_length (int, optional): The minimum length of the sampled tiles. Defaults to 16.
|
| 205 |
+
spatial_downsample_factor (int, optional): The actual spataial downsample factor of given encode_fn. Defaults to 8.
|
| 206 |
+
temporal_downsample_factor (int, optional): The actual temporal downsample factor of the latent space tiles. Defaults to 1.
|
| 207 |
+
tile_overlap_factor (float, optional): The overlap factor between adjacent tiles. Defaults to 0.25.
|
| 208 |
+
parallel_group (torch.distributed.ProcessGroup, optional): Distributed decoding group. Defaults to None.
|
| 209 |
+
"""
|
| 210 |
+
self.encode_fn = encode_fn
|
| 211 |
+
self.decode_fn = decode_fn
|
| 212 |
+
|
| 213 |
+
self.spatial_downsample_factor = spatial_downsample_factor
|
| 214 |
+
self.temporal_downsample_factor = temporal_downsample_factor
|
| 215 |
+
self.tile_sample_min_height = tile_sample_min_height
|
| 216 |
+
self.tile_sample_min_width = tile_sample_min_width
|
| 217 |
+
self.tile_sample_min_length = tile_sample_min_length
|
| 218 |
+
self.tile_latent_min_height = tile_sample_min_height // spatial_downsample_factor
|
| 219 |
+
self.tile_latent_min_width = tile_sample_min_width // spatial_downsample_factor
|
| 220 |
+
|
| 221 |
+
self.tile_latent_min_length = tile_sample_min_length // temporal_downsample_factor
|
| 222 |
+
if first_frame_as_image:
|
| 223 |
+
self.tile_latent_min_length += 1
|
| 224 |
+
|
| 225 |
+
self.spatial_tile_overlap_factor = spatial_tile_overlap_factor
|
| 226 |
+
self.temporal_tile_overlap_factor = temporal_tile_overlap_factor
|
| 227 |
+
self.sr_ratio = sr_ratio
|
| 228 |
+
self.parallel_group = parallel_group
|
| 229 |
+
|
| 230 |
+
def blend_t(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor:
|
| 231 |
+
blend_extent = min(a.shape[2], b.shape[2], blend_extent)
|
| 232 |
+
for t in range(blend_extent):
|
| 233 |
+
b[:, :, t, :, :] = a[:, :, -blend_extent + t, :, :] * (1 - t / blend_extent) + b[:, :, t, :, :] * (
|
| 234 |
+
t / blend_extent
|
| 235 |
+
)
|
| 236 |
+
return b
|
| 237 |
+
|
| 238 |
+
def blend_v(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor:
|
| 239 |
+
blend_extent = min(a.shape[3], b.shape[3], blend_extent)
|
| 240 |
+
for y in range(blend_extent):
|
| 241 |
+
b[:, :, :, y, :] = a[:, :, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, :, y, :] * (
|
| 242 |
+
y / blend_extent
|
| 243 |
+
)
|
| 244 |
+
return b
|
| 245 |
+
|
| 246 |
+
def blend_h(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor:
|
| 247 |
+
blend_extent = min(a.shape[4], b.shape[4], blend_extent)
|
| 248 |
+
for x in range(blend_extent):
|
| 249 |
+
b[:, :, :, :, x] = a[:, :, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, :, x] * (
|
| 250 |
+
x / blend_extent
|
| 251 |
+
)
|
| 252 |
+
return b
|
| 253 |
+
|
| 254 |
+
def tiled_encode(self, x: torch.FloatTensor, verbose: bool = False):
|
| 255 |
+
overlap_height = int(self.tile_sample_min_height * (1 - self.spatial_tile_overlap_factor))
|
| 256 |
+
overlap_width = int(self.tile_sample_min_width * (1 - self.spatial_tile_overlap_factor))
|
| 257 |
+
overlap_length = int(self.tile_sample_min_length * (1 - self.temporal_tile_overlap_factor))
|
| 258 |
+
blend_extent_h = int(self.tile_latent_min_height * self.spatial_tile_overlap_factor)
|
| 259 |
+
blend_extent_w = int(self.tile_latent_min_width * self.spatial_tile_overlap_factor)
|
| 260 |
+
blend_extent_t = int(self.tile_latent_min_length * self.temporal_tile_overlap_factor)
|
| 261 |
+
height_limit = self.tile_latent_min_height - blend_extent_h
|
| 262 |
+
width_limit = self.tile_latent_min_width - blend_extent_w
|
| 263 |
+
frame_limit = self.tile_latent_min_length - blend_extent_t
|
| 264 |
+
|
| 265 |
+
length_tile_size = (x.shape[2] + overlap_length - 1) // overlap_length
|
| 266 |
+
height_tile_size = (x.shape[3] + overlap_height - 1) // overlap_height
|
| 267 |
+
width_tile_size = (x.shape[4] + overlap_width - 1) // overlap_width
|
| 268 |
+
total_tile_size = length_tile_size * height_tile_size * width_tile_size
|
| 269 |
+
for_loop_size = [length_tile_size, height_tile_size, width_tile_size]
|
| 270 |
+
|
| 271 |
+
tiles = []
|
| 272 |
+
tile_numel_dict = OrderedDict()
|
| 273 |
+
for tile_index in range(total_tile_size):
|
| 274 |
+
undot_tile_index = ParallelHelper.index_undot(tile_index, for_loop_size)
|
| 275 |
+
f_idx, i_idx, j_idx = undot_tile_index
|
| 276 |
+
f = f_idx * overlap_length
|
| 277 |
+
i = i_idx * overlap_height
|
| 278 |
+
j = j_idx * overlap_width
|
| 279 |
+
|
| 280 |
+
# Extract the tile from the latent representation and decode it
|
| 281 |
+
tile = x[
|
| 282 |
+
:,
|
| 283 |
+
:,
|
| 284 |
+
f : f + self.tile_sample_min_length,
|
| 285 |
+
i : i + self.tile_sample_min_height,
|
| 286 |
+
j : j + self.tile_sample_min_width,
|
| 287 |
+
]
|
| 288 |
+
tiles.append(tile)
|
| 289 |
+
tile_numel_dict[tile_index] = tile.numel()
|
| 290 |
+
tile_index_list, global_tile_index_list = ParallelHelper.split_tile_list(
|
| 291 |
+
tile_numel_dict, parallel_group=self.parallel_group
|
| 292 |
+
)
|
| 293 |
+
progress_bar = tqdm(
|
| 294 |
+
total=len(tile_index_list),
|
| 295 |
+
desc=f"[Rank {torch.distributed.get_rank(group=self.parallel_group)}] Encoding Tiles",
|
| 296 |
+
disable=not verbose,
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
frames = []
|
| 300 |
+
# Encode each tile based on the tile index list
|
| 301 |
+
for tile_index in tile_index_list:
|
| 302 |
+
tile = tiles[tile_index]
|
| 303 |
+
encoded = self.encode_fn(tile)
|
| 304 |
+
frames.append(encoded)
|
| 305 |
+
progress_bar.update(1)
|
| 306 |
+
|
| 307 |
+
# Gather all decoded frames from different ranks
|
| 308 |
+
frames = ParallelHelper.gather_frames(frames, global_tile_index_list, parallel_group=self.parallel_group)
|
| 309 |
+
assert len(frames) == total_tile_size
|
| 310 |
+
progress_bar.close()
|
| 311 |
+
|
| 312 |
+
result_frames = []
|
| 313 |
+
# Blend the encoded tiles to create the final output
|
| 314 |
+
for tile_index in range(total_tile_size):
|
| 315 |
+
undot_tile_index = ParallelHelper.index_undot(tile_index, for_loop_size)
|
| 316 |
+
f, i, j = undot_tile_index
|
| 317 |
+
|
| 318 |
+
tile = frames[tile_index]
|
| 319 |
+
# Blend with previous tiles if applicable
|
| 320 |
+
if f > 0:
|
| 321 |
+
idx = ParallelHelper.index_dot([f - 1, i, j], for_loop_size)
|
| 322 |
+
tile = self.blend_t(frames[idx], tile, blend_extent_t)
|
| 323 |
+
if i > 0:
|
| 324 |
+
idx = ParallelHelper.index_dot([f, i - 1, j], for_loop_size)
|
| 325 |
+
tile = self.blend_v(frames[idx], tile, blend_extent_h)
|
| 326 |
+
if j > 0:
|
| 327 |
+
idx = ParallelHelper.index_dot([f, i, j - 1], for_loop_size)
|
| 328 |
+
tile = self.blend_h(frames[idx], tile, blend_extent_w)
|
| 329 |
+
result_frames.append(tile[:, :, :frame_limit, :height_limit, :width_limit])
|
| 330 |
+
|
| 331 |
+
assert len(result_frames) == total_tile_size
|
| 332 |
+
|
| 333 |
+
concat_frames = []
|
| 334 |
+
for f in range(length_tile_size):
|
| 335 |
+
result_rows = []
|
| 336 |
+
for i in range(height_tile_size):
|
| 337 |
+
result_row = []
|
| 338 |
+
for j in range(width_tile_size):
|
| 339 |
+
idx = ParallelHelper.index_dot([f, i, j], for_loop_size)
|
| 340 |
+
result_row.append(result_frames[idx])
|
| 341 |
+
result_rows.append(torch.cat(result_row, dim=4))
|
| 342 |
+
concat_frames.append(torch.cat(result_rows, dim=3))
|
| 343 |
+
|
| 344 |
+
# Concatenate all result frames along the temporal dimension
|
| 345 |
+
result = torch.cat(concat_frames, dim=2)
|
| 346 |
+
return result
|
| 347 |
+
|
| 348 |
+
def tiled_decode(self, z: torch.FloatTensor, verbose: bool = False):
|
| 349 |
+
overlap_height = int(self.tile_latent_min_height * (1 - self.spatial_tile_overlap_factor))
|
| 350 |
+
overlap_width = int(self.tile_latent_min_width * (1 - self.spatial_tile_overlap_factor))
|
| 351 |
+
overlap_length = int(self.tile_latent_min_length * (1 - self.temporal_tile_overlap_factor))
|
| 352 |
+
|
| 353 |
+
real_tile_sample_min_height = int(self.tile_latent_min_height * self.spatial_downsample_factor * self.sr_ratio)
|
| 354 |
+
real_tile_sample_min_width = int(self.tile_latent_min_width * self.spatial_downsample_factor * self.sr_ratio)
|
| 355 |
+
real_tile_sample_min_length = int(self.tile_latent_min_length * self.temporal_downsample_factor)
|
| 356 |
+
|
| 357 |
+
blend_extent_h = int(real_tile_sample_min_height * self.spatial_tile_overlap_factor)
|
| 358 |
+
blend_extent_w = int(real_tile_sample_min_width * self.spatial_tile_overlap_factor)
|
| 359 |
+
blend_extent_t = int(real_tile_sample_min_length * self.temporal_tile_overlap_factor)
|
| 360 |
+
|
| 361 |
+
height_limit = real_tile_sample_min_height - blend_extent_h
|
| 362 |
+
width_limit = real_tile_sample_min_width - blend_extent_w
|
| 363 |
+
frame_limit = real_tile_sample_min_length - blend_extent_t
|
| 364 |
+
|
| 365 |
+
length_tile_size = (z.shape[2] + overlap_length - 1) // overlap_length
|
| 366 |
+
height_tile_size = (z.shape[3] + overlap_height - 1) // overlap_height
|
| 367 |
+
width_tile_size = (z.shape[4] + overlap_width - 1) // overlap_width
|
| 368 |
+
total_tile_size = length_tile_size * height_tile_size * width_tile_size
|
| 369 |
+
for_loop_size = [length_tile_size, height_tile_size, width_tile_size]
|
| 370 |
+
|
| 371 |
+
tiles = []
|
| 372 |
+
tile_numel_dict = OrderedDict()
|
| 373 |
+
for tile_index in range(total_tile_size):
|
| 374 |
+
undot_tile_index = ParallelHelper.index_undot(tile_index, for_loop_size)
|
| 375 |
+
f_idx, i_idx, j_idx = undot_tile_index
|
| 376 |
+
f = f_idx * overlap_length
|
| 377 |
+
i = i_idx * overlap_height
|
| 378 |
+
j = j_idx * overlap_width
|
| 379 |
+
|
| 380 |
+
# Extract the tile from the latent representation and decode it
|
| 381 |
+
tile = z[
|
| 382 |
+
:,
|
| 383 |
+
:,
|
| 384 |
+
f : f + self.tile_latent_min_length,
|
| 385 |
+
i : i + self.tile_latent_min_height,
|
| 386 |
+
j : j + self.tile_latent_min_width,
|
| 387 |
+
]
|
| 388 |
+
tiles.append(tile)
|
| 389 |
+
tile_numel_dict[tile_index] = tile.numel()
|
| 390 |
+
tile_index_list, global_tile_index_list = ParallelHelper.split_tile_list(
|
| 391 |
+
tile_numel_dict, parallel_group=self.parallel_group
|
| 392 |
+
)
|
| 393 |
+
progress_bar = tqdm(
|
| 394 |
+
total=len(tile_index_list),
|
| 395 |
+
desc=f"[Rank {torch.distributed.get_rank(group=self.parallel_group)}] Decoding Tiles",
|
| 396 |
+
disable=not verbose,
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
frames = []
|
| 400 |
+
# Decode each tile based on the tile index list
|
| 401 |
+
for tile_index in tile_index_list:
|
| 402 |
+
tile = tiles[tile_index]
|
| 403 |
+
decoded = self.decode_fn(tile)
|
| 404 |
+
frames.append(decoded)
|
| 405 |
+
progress_bar.update(1)
|
| 406 |
+
|
| 407 |
+
progress_bar.close()
|
| 408 |
+
# Gather all decoded frames from different ranks
|
| 409 |
+
frames = ParallelHelper.gather_frames(frames, global_tile_index_list, parallel_group=self.parallel_group)
|
| 410 |
+
assert len(frames) == total_tile_size
|
| 411 |
+
|
| 412 |
+
result_frames = []
|
| 413 |
+
# Blend the decoded tiles to create the final output
|
| 414 |
+
for tile_index in tile_index_list:
|
| 415 |
+
undot_tile_index = ParallelHelper.index_undot(tile_index, for_loop_size)
|
| 416 |
+
f, i, j = undot_tile_index
|
| 417 |
+
|
| 418 |
+
tile = frames[tile_index].clone()
|
| 419 |
+
# Blend with previous tiles if applicable
|
| 420 |
+
if f > 0:
|
| 421 |
+
idx = ParallelHelper.index_dot([f - 1, i, j], for_loop_size)
|
| 422 |
+
tile = torch.compile(self.blend_t, dynamic=False)(frames[idx], tile, blend_extent_t)
|
| 423 |
+
if i > 0:
|
| 424 |
+
idx = ParallelHelper.index_dot([f, i - 1, j], for_loop_size)
|
| 425 |
+
tile = torch.compile(self.blend_v, dynamic=False)(frames[idx], tile, blend_extent_h)
|
| 426 |
+
if j > 0:
|
| 427 |
+
idx = ParallelHelper.index_dot([f, i, j - 1], for_loop_size)
|
| 428 |
+
tile = torch.compile(self.blend_h, dynamic=False)(frames[idx], tile, blend_extent_w)
|
| 429 |
+
result_frames.append(tile[:, :, :frame_limit, :height_limit, :width_limit])
|
| 430 |
+
|
| 431 |
+
# Gather and concatenate the final result frames
|
| 432 |
+
result_frames = ParallelHelper.gather_frames(result_frames, global_tile_index_list, parallel_group=self.parallel_group)
|
| 433 |
+
assert len(result_frames) == total_tile_size
|
| 434 |
+
|
| 435 |
+
concat_frames = []
|
| 436 |
+
for f in range(length_tile_size):
|
| 437 |
+
result_rows = []
|
| 438 |
+
for i in range(height_tile_size):
|
| 439 |
+
result_row = []
|
| 440 |
+
for j in range(width_tile_size):
|
| 441 |
+
idx = ParallelHelper.index_dot([f, i, j], for_loop_size)
|
| 442 |
+
result_row.append(result_frames[idx])
|
| 443 |
+
result_rows.append(torch.cat(result_row, dim=4))
|
| 444 |
+
concat_frames.append(torch.cat(result_rows, dim=3))
|
| 445 |
+
|
| 446 |
+
# Concatenate all result frames along the temporal dimension
|
| 447 |
+
result = torch.cat(concat_frames, dim=2)
|
| 448 |
+
return result
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/model/dit/__init__.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2025 SandAI. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from .dit_model import get_dit, VideoDiTModel
|
| 16 |
+
from .dit_module import FullyParallelAttention
|
| 17 |
+
|
| 18 |
+
__all__ = ["get_dit", "VideoDiTModel", "FullyParallelAttention"]
|
FlowCache/FlowCache4MAGI-1-dev-V1/inference/model/dit/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (356 Bytes). View file
|
|
|