Spaces:
Running
Running
Upload 10 files
Browse files- __init__.cpython-310.pyc +0 -0
- __init__.cpython-311.pyc +0 -0
- __init__.py +13 -0
- flash_attention_utils.cpython-310.pyc +0 -0
- flash_attention_utils.py +191 -0
- monkey_patch.cpython-310.pyc +0 -0
- monkey_patch.py +32 -0
- protocol.py +689 -0
- qwen2_vl.cpython-310.pyc +0 -0
- qwen2_vl.py +189 -0
__init__.cpython-310.pyc
ADDED
|
Binary file (171 Bytes). View file
|
|
|
__init__.cpython-311.pyc
ADDED
|
Binary file (187 Bytes). View file
|
|
|
__init__.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 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.
|
flash_attention_utils.cpython-310.pyc
ADDED
|
Binary file (4.29 kB). View file
|
|
|
flash_attention_utils.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 3 |
+
# Based on https://github.com/huggingface/transformers/blob/v4.49.0/src/transformers/modeling_flash_attention_utils.py
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
|
| 17 |
+
import inspect
|
| 18 |
+
import os
|
| 19 |
+
from typing import Optional, Tuple
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
import torch.distributed as dist
|
| 23 |
+
from transformers.modeling_flash_attention_utils import _flash_attention_forward, fa_peft_integration_check
|
| 24 |
+
from transformers.utils import is_flash_attn_2_available, is_flash_attn_greater_or_equal_2_10
|
| 25 |
+
|
| 26 |
+
from ...utils.ulysses import (
|
| 27 |
+
gather_heads_scatter_seq,
|
| 28 |
+
gather_seq_scatter_heads,
|
| 29 |
+
get_ulysses_sequence_parallel_group,
|
| 30 |
+
get_ulysses_sequence_parallel_world_size,
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
if is_flash_attn_2_available():
|
| 35 |
+
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
| 36 |
+
|
| 37 |
+
_flash_supports_window_size = "window_size" in inspect.signature(flash_attn_func).parameters
|
| 38 |
+
_flash_supports_deterministic = "deterministic" in inspect.signature(flash_attn_func).parameters
|
| 39 |
+
_flash_deterministic_enabled = os.environ.get("FLASH_ATTENTION_DETERMINISTIC", "0") == "1"
|
| 40 |
+
_flash_use_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def prepare_fa2_from_position_ids(
|
| 44 |
+
query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, position_ids: torch.Tensor
|
| 45 |
+
):
|
| 46 |
+
query = query.view(-1, query.size(-2), query.size(-1))
|
| 47 |
+
key = key.contiguous().view(-1, key.size(-2), key.size(-1))
|
| 48 |
+
value = value.contiguous().view(-1, value.size(-2), value.size(-1))
|
| 49 |
+
position_ids = position_ids.flatten()
|
| 50 |
+
indices_q = torch.arange(position_ids.size(0), device=position_ids.device, dtype=torch.int32)
|
| 51 |
+
cu_seqlens = torch.cat(
|
| 52 |
+
(
|
| 53 |
+
indices_q[position_ids == 0],
|
| 54 |
+
torch.tensor(position_ids.size(), device=position_ids.device, dtype=torch.int32),
|
| 55 |
+
)
|
| 56 |
+
)
|
| 57 |
+
max_length = cu_seqlens.diff().max() # use cu_seqlens to infer max_length for qwen2vl mrope
|
| 58 |
+
return (query, key, value, indices_q, (cu_seqlens, cu_seqlens), (max_length, max_length))
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _custom_flash_attention_forward(
|
| 62 |
+
query_states: torch.Tensor,
|
| 63 |
+
key_states: torch.Tensor,
|
| 64 |
+
value_states: torch.Tensor,
|
| 65 |
+
attention_mask: Optional[torch.Tensor],
|
| 66 |
+
query_length: int,
|
| 67 |
+
is_causal: bool = True,
|
| 68 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 69 |
+
sliding_window: Optional[int] = None,
|
| 70 |
+
use_top_left_mask: bool = False,
|
| 71 |
+
deterministic: Optional[bool] = None,
|
| 72 |
+
**kwargs,
|
| 73 |
+
):
|
| 74 |
+
"""
|
| 75 |
+
Patches flash attention forward to handle 3D position ids in mrope. (3, batch_size, seq_length)
|
| 76 |
+
"""
|
| 77 |
+
if not use_top_left_mask:
|
| 78 |
+
causal = is_causal
|
| 79 |
+
else:
|
| 80 |
+
causal = is_causal and query_length != 1
|
| 81 |
+
|
| 82 |
+
# Assuming 4D tensors, key_states.shape[1] is the key/value sequence length (source length).
|
| 83 |
+
use_sliding_windows = (
|
| 84 |
+
_flash_supports_window_size and sliding_window is not None and key_states.shape[1] > sliding_window
|
| 85 |
+
)
|
| 86 |
+
flash_kwargs = {"window_size": (sliding_window, sliding_window)} if use_sliding_windows else {}
|
| 87 |
+
|
| 88 |
+
if _flash_supports_deterministic:
|
| 89 |
+
flash_kwargs["deterministic"] = deterministic if deterministic is not None else _flash_deterministic_enabled
|
| 90 |
+
|
| 91 |
+
if kwargs.get("softcap") is not None:
|
| 92 |
+
flash_kwargs["softcap"] = kwargs.pop("softcap")
|
| 93 |
+
|
| 94 |
+
query_states, key_states, value_states = fa_peft_integration_check(
|
| 95 |
+
query_states, key_states, value_states, target_dtype=torch.bfloat16
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
sp_size = get_ulysses_sequence_parallel_world_size()
|
| 99 |
+
if sp_size > 1:
|
| 100 |
+
# (batch_size, seq_length, num_head, head_size)
|
| 101 |
+
query_states = gather_seq_scatter_heads(query_states, seq_dim=1, head_dim=2)
|
| 102 |
+
key_states = gather_seq_scatter_heads(key_states, seq_dim=1, head_dim=2)
|
| 103 |
+
value_states = gather_seq_scatter_heads(value_states, seq_dim=1, head_dim=2)
|
| 104 |
+
position_ids_lst = [torch.empty_like(position_ids) for _ in range(sp_size)]
|
| 105 |
+
position_ids = dist.all_gather(position_ids_lst, position_ids, group=get_ulysses_sequence_parallel_group())
|
| 106 |
+
position_ids = torch.cat(position_ids_lst, dim=-1) # (..., batch_size, seq_length)
|
| 107 |
+
|
| 108 |
+
if position_ids is not None and position_ids.dim() == 3: # qwen2vl mrope
|
| 109 |
+
position_ids = position_ids[0]
|
| 110 |
+
|
| 111 |
+
if position_ids is not None and query_length != 1 and not (torch.diff(position_ids, dim=-1) >= 0).all():
|
| 112 |
+
batch_size = query_states.size(0)
|
| 113 |
+
query_states, key_states, value_states, _, cu_seq_lens, max_seq_lens = prepare_fa2_from_position_ids(
|
| 114 |
+
query_states, key_states, value_states, position_ids
|
| 115 |
+
)
|
| 116 |
+
cu_seqlens_q, cu_seqlens_k = cu_seq_lens
|
| 117 |
+
max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
|
| 118 |
+
attn_output = flash_attn_varlen_func(
|
| 119 |
+
query_states,
|
| 120 |
+
key_states,
|
| 121 |
+
value_states,
|
| 122 |
+
cu_seqlens_q=cu_seqlens_q,
|
| 123 |
+
cu_seqlens_k=cu_seqlens_k,
|
| 124 |
+
max_seqlen_q=max_seqlen_in_batch_q,
|
| 125 |
+
max_seqlen_k=max_seqlen_in_batch_k,
|
| 126 |
+
dropout_p=kwargs.pop("dropout", 0.0),
|
| 127 |
+
softmax_scale=kwargs.pop("softmax_scale", None),
|
| 128 |
+
causal=causal,
|
| 129 |
+
**flash_kwargs,
|
| 130 |
+
)
|
| 131 |
+
attn_output = attn_output.view(batch_size, -1, attn_output.size(-2), attn_output.size(-1))
|
| 132 |
+
else:
|
| 133 |
+
attn_output = _flash_attention_forward(
|
| 134 |
+
query_states,
|
| 135 |
+
key_states,
|
| 136 |
+
value_states,
|
| 137 |
+
attention_mask,
|
| 138 |
+
query_length,
|
| 139 |
+
is_causal=is_causal,
|
| 140 |
+
sliding_window=sliding_window,
|
| 141 |
+
use_top_left_mask=use_top_left_mask,
|
| 142 |
+
deterministic=deterministic,
|
| 143 |
+
**kwargs,
|
| 144 |
+
) # do not pass position_ids to old flash_attention_forward
|
| 145 |
+
|
| 146 |
+
if sp_size > 1:
|
| 147 |
+
# (batch_size, seq_length, num_head, head_size)
|
| 148 |
+
attn_output = gather_heads_scatter_seq(attn_output, head_dim=2, seq_dim=1)
|
| 149 |
+
|
| 150 |
+
return attn_output
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def flash_attention_forward(
|
| 154 |
+
module: torch.nn.Module,
|
| 155 |
+
query: torch.Tensor,
|
| 156 |
+
key: torch.Tensor,
|
| 157 |
+
value: torch.Tensor,
|
| 158 |
+
attention_mask: Optional[torch.Tensor],
|
| 159 |
+
dropout: float = 0.0,
|
| 160 |
+
scaling: Optional[float] = None,
|
| 161 |
+
sliding_window: Optional[int] = None,
|
| 162 |
+
softcap: Optional[float] = None,
|
| 163 |
+
**kwargs,
|
| 164 |
+
) -> Tuple[torch.Tensor, None]:
|
| 165 |
+
# This is before the transpose
|
| 166 |
+
q_len = query.shape[2]
|
| 167 |
+
|
| 168 |
+
# FA2 uses non-transposed inputs
|
| 169 |
+
query = query.transpose(1, 2)
|
| 170 |
+
key = key.transpose(1, 2)
|
| 171 |
+
value = value.transpose(1, 2)
|
| 172 |
+
|
| 173 |
+
# FA2 always relies on the value set in the module, so remove it if present in kwargs to avoid passing it twice
|
| 174 |
+
kwargs.pop("is_causal", None)
|
| 175 |
+
|
| 176 |
+
attn_output = _custom_flash_attention_forward(
|
| 177 |
+
query,
|
| 178 |
+
key,
|
| 179 |
+
value,
|
| 180 |
+
attention_mask,
|
| 181 |
+
query_length=q_len,
|
| 182 |
+
is_causal=True,
|
| 183 |
+
dropout=dropout,
|
| 184 |
+
softmax_scale=scaling,
|
| 185 |
+
sliding_window=sliding_window,
|
| 186 |
+
softcap=softcap,
|
| 187 |
+
use_top_left_mask=_flash_use_top_left_mask,
|
| 188 |
+
**kwargs,
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
return attn_output, None
|
monkey_patch.cpython-310.pyc
ADDED
|
Binary file (1.01 kB). View file
|
|
|
monkey_patch.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 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 |
+
|
| 16 |
+
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS
|
| 17 |
+
|
| 18 |
+
from .transformers.flash_attention_utils import flash_attention_forward
|
| 19 |
+
from .transformers.qwen2_vl import qwen2_vl_attn_forward
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def apply_ulysses_patch(model_type: str) -> None:
|
| 23 |
+
if model_type in ("llama", "gemma", "gemma2", "mistral", "qwen2", "qwen3", "qwen3_moe"):
|
| 24 |
+
ALL_ATTENTION_FUNCTIONS["flash_attention_2"] = flash_attention_forward
|
| 25 |
+
elif model_type in ("qwen2_vl", "qwen2_5_vl"):
|
| 26 |
+
from transformers.models.qwen2_5_vl.modeling_qwen2_5_vl import Qwen2_5_VLFlashAttention2
|
| 27 |
+
from transformers.models.qwen2_vl.modeling_qwen2_vl import Qwen2VLFlashAttention2
|
| 28 |
+
|
| 29 |
+
Qwen2VLFlashAttention2.forward = qwen2_vl_attn_forward
|
| 30 |
+
Qwen2_5_VLFlashAttention2.forward = qwen2_vl_attn_forward
|
| 31 |
+
else:
|
| 32 |
+
raise NotImplementedError(f"Model architecture {model_type} is not supported yet.")
|
protocol.py
ADDED
|
@@ -0,0 +1,689 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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yright 2024 Bytedance Ltd. and/or its affiliates
|
| 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 |
+
Implement base data transfer protocol between any two functions, modules.
|
| 16 |
+
We can subclass Protocol to define more detailed batch info with specific keys
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import copy
|
| 20 |
+
import io
|
| 21 |
+
import pickle
|
| 22 |
+
from collections import defaultdict
|
| 23 |
+
from dataclasses import dataclass, field
|
| 24 |
+
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
|
| 25 |
+
|
| 26 |
+
import numpy as np
|
| 27 |
+
import ray
|
| 28 |
+
import torch
|
| 29 |
+
from numpy.typing import NDArray
|
| 30 |
+
from tensordict import TensorDict
|
| 31 |
+
from torch.distributed import ProcessGroup
|
| 32 |
+
from torch.utils.data import DataLoader
|
| 33 |
+
|
| 34 |
+
from .utils.py_functional import union_two_dict
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
try:
|
| 38 |
+
import tensordict
|
| 39 |
+
|
| 40 |
+
tensordict.set_lazy_legacy(False).set()
|
| 41 |
+
except Exception:
|
| 42 |
+
pass
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
__all__ = ["DataProto", "union_tensor_dict"]
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def pad_dataproto_to_divisor(data: "DataProto", size_divisor: int) -> Tuple["DataProto", int]:
|
| 49 |
+
"""Pad a DataProto to size divisible by size_divisor
|
| 50 |
+
|
| 51 |
+
Args:
|
| 52 |
+
data (DataProto): the unpadded DataProto
|
| 53 |
+
size_divisor (int): size divisor
|
| 54 |
+
|
| 55 |
+
Returns:
|
| 56 |
+
data (DataProto): the padded DataProto
|
| 57 |
+
pad_size (int)
|
| 58 |
+
"""
|
| 59 |
+
assert isinstance(data, DataProto), "data must be a DataProto"
|
| 60 |
+
if len(data) % size_divisor != 0:
|
| 61 |
+
pad_size = size_divisor - len(data) % size_divisor
|
| 62 |
+
padding_protos = []
|
| 63 |
+
remaining_pad = pad_size
|
| 64 |
+
while remaining_pad > 0:
|
| 65 |
+
take_size = min(remaining_pad, len(data))
|
| 66 |
+
padding_protos.append(data[:take_size])
|
| 67 |
+
remaining_pad -= take_size
|
| 68 |
+
|
| 69 |
+
data_padded = DataProto.concat([data] + padding_protos)
|
| 70 |
+
else:
|
| 71 |
+
pad_size = 0
|
| 72 |
+
data_padded = data
|
| 73 |
+
|
| 74 |
+
return data_padded, pad_size
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def unpad_dataproto(data: "DataProto", pad_size: int) -> "DataProto":
|
| 78 |
+
if pad_size != 0:
|
| 79 |
+
data = data[:-pad_size]
|
| 80 |
+
|
| 81 |
+
return data
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def union_tensor_dict(tensor_dict1: TensorDict, tensor_dict2: TensorDict) -> TensorDict:
|
| 85 |
+
"""Union two tensordicts."""
|
| 86 |
+
if tensor_dict1.batch_size != tensor_dict2.batch_size:
|
| 87 |
+
raise ValueError(
|
| 88 |
+
f"Two tensor dict must have identical batch size. Got {tensor_dict1.batch_size} and {tensor_dict2.batch_size}"
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
for key in tensor_dict2.keys():
|
| 92 |
+
if key in tensor_dict1 and not torch.equal(tensor_dict1[key], tensor_dict2[key]):
|
| 93 |
+
raise ValueError(f"Key already exists: {key}.")
|
| 94 |
+
|
| 95 |
+
tensor_dict1[key] = tensor_dict2[key]
|
| 96 |
+
|
| 97 |
+
return tensor_dict1
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def union_numpy_dict(tensor_dict1: Dict[str, NDArray], tensor_dict2: Dict[str, NDArray]) -> Dict[str, NDArray]:
|
| 101 |
+
for key in tensor_dict2.keys():
|
| 102 |
+
if key in tensor_dict1:
|
| 103 |
+
assert isinstance(tensor_dict2[key], np.ndarray)
|
| 104 |
+
assert isinstance(tensor_dict1[key], np.ndarray)
|
| 105 |
+
if not np.all(tensor_dict1[key] == tensor_dict2[key]):
|
| 106 |
+
raise ValueError(f"Key already exists: {key}.")
|
| 107 |
+
|
| 108 |
+
tensor_dict1[key] = tensor_dict2[key]
|
| 109 |
+
|
| 110 |
+
return tensor_dict1
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def batch_collate(features: List[Dict[str, Any]]) -> Dict[str, List[Any]]:
|
| 114 |
+
if len(features) == 0:
|
| 115 |
+
return {}
|
| 116 |
+
|
| 117 |
+
batch_features = defaultdict(list)
|
| 118 |
+
for feature in features:
|
| 119 |
+
for key, value in feature.items():
|
| 120 |
+
batch_features[key].append(value)
|
| 121 |
+
|
| 122 |
+
return batch_features
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def fold_batch_dim(data: "DataProto", new_batch_size: int):
|
| 126 |
+
"""
|
| 127 |
+
Fold a batch dim from [bsz, xxx] into [new_bsz, bsz // new_bsz, xxx]
|
| 128 |
+
"""
|
| 129 |
+
batch_size = data.batch.batch_size[0]
|
| 130 |
+
|
| 131 |
+
assert batch_size % new_batch_size == 0
|
| 132 |
+
|
| 133 |
+
tensor: TensorDict = data.batch
|
| 134 |
+
non_tensor = data.non_tensor_batch
|
| 135 |
+
|
| 136 |
+
tensor = tensor.view(new_batch_size, -1)
|
| 137 |
+
tensor.auto_batch_size_(batch_dims=1)
|
| 138 |
+
|
| 139 |
+
for key, value in non_tensor.items():
|
| 140 |
+
non_tensor[key] = np.reshape(value, newshape=(new_batch_size, -1, *value.shape[1:]))
|
| 141 |
+
|
| 142 |
+
return DataProto(batch=tensor, non_tensor_batch=non_tensor, meta_info=data.meta_info)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def collate_fn(data_items: list["DataProtoItem"]):
|
| 146 |
+
batch = []
|
| 147 |
+
non_tensor_batch = []
|
| 148 |
+
for data in data_items:
|
| 149 |
+
batch.append(data.batch)
|
| 150 |
+
non_tensor_batch.append(data.non_tensor_batch)
|
| 151 |
+
|
| 152 |
+
batch = torch.stack(batch).contiguous()
|
| 153 |
+
non_tensor_batch = batch_collate(non_tensor_batch)
|
| 154 |
+
non_tensor_batch = {key: np.array(value, dtype=object) for key, value in non_tensor_batch.items()}
|
| 155 |
+
return DataProto(batch=batch, non_tensor_batch=non_tensor_batch)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
@dataclass
|
| 159 |
+
class DataProtoItem:
|
| 160 |
+
batch: Optional[TensorDict] = None
|
| 161 |
+
non_tensor_batch: Dict[str, NDArray] = field(default_factory=dict)
|
| 162 |
+
meta_info: Dict[str, Any] = field(default_factory=dict)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
@dataclass
|
| 166 |
+
class DataProto:
|
| 167 |
+
"""
|
| 168 |
+
A DataProto is a data structure that aims to provide a standard protocol for data exchange between functions.
|
| 169 |
+
It contains a batch (TensorDict) and a meta_info (Dict). The batch is a TensorDict https://pytorch.org/tensordict/.
|
| 170 |
+
TensorDict allows you to manipulate a dictionary of Tensors like a single Tensor. Ideally, the tensors with the
|
| 171 |
+
same batch size should be put inside batch.
|
| 172 |
+
"""
|
| 173 |
+
|
| 174 |
+
batch: Optional[TensorDict] = None
|
| 175 |
+
non_tensor_batch: Dict[str, NDArray] = field(default_factory=dict)
|
| 176 |
+
meta_info: Dict[str, Any] = field(default_factory=dict)
|
| 177 |
+
|
| 178 |
+
def __post_init__(self):
|
| 179 |
+
self.check_consistency() # perform necessary checking
|
| 180 |
+
|
| 181 |
+
def __len__(self) -> int:
|
| 182 |
+
if self.batch is not None:
|
| 183 |
+
return self.batch.batch_size[0]
|
| 184 |
+
elif self.non_tensor_batch is not None and len(self.non_tensor_batch) > 0:
|
| 185 |
+
pivot_key = list(self.non_tensor_batch.keys())[0]
|
| 186 |
+
return self.non_tensor_batch[pivot_key].shape[0]
|
| 187 |
+
else:
|
| 188 |
+
return 0
|
| 189 |
+
|
| 190 |
+
def __getitem__(self, item: Union[int, slice]) -> Union["DataProto", "DataProtoItem"]:
|
| 191 |
+
tensor_data = self.batch[item]
|
| 192 |
+
non_tensor_data = {key: value[item] for key, value in self.non_tensor_batch.items()}
|
| 193 |
+
return_type = DataProto if isinstance(item, slice) else DataProtoItem
|
| 194 |
+
return return_type(batch=tensor_data, non_tensor_batch=non_tensor_data, meta_info=self.meta_info)
|
| 195 |
+
|
| 196 |
+
def __getstate__(self) -> Tuple[bytes, Dict[str, NDArray], Dict[str, Any]]:
|
| 197 |
+
buffer = io.BytesIO()
|
| 198 |
+
if self.batch is not None:
|
| 199 |
+
self.batch: TensorDict = self.batch.contiguous()
|
| 200 |
+
self.batch: TensorDict = self.batch.consolidate()
|
| 201 |
+
|
| 202 |
+
torch.save(self.batch, buffer)
|
| 203 |
+
buffer_bytes = buffer.getvalue()
|
| 204 |
+
return buffer_bytes, self.non_tensor_batch, self.meta_info
|
| 205 |
+
|
| 206 |
+
def __setstate__(self, data: Tuple[bytes, Dict[str, NDArray], Dict[str, Any]]) -> None:
|
| 207 |
+
batch_deserialized_bytes, non_tensor_batch, meta_info = data
|
| 208 |
+
batch_deserialized = io.BytesIO(batch_deserialized_bytes)
|
| 209 |
+
batch = torch.load(batch_deserialized, weights_only=False, map_location="cpu")
|
| 210 |
+
self.batch = batch
|
| 211 |
+
self.non_tensor_batch = non_tensor_batch
|
| 212 |
+
self.meta_info = meta_info
|
| 213 |
+
|
| 214 |
+
def save_to_disk(self, filepath: str) -> None:
|
| 215 |
+
with open(filepath, "wb") as f:
|
| 216 |
+
pickle.dump(self, f)
|
| 217 |
+
|
| 218 |
+
@staticmethod
|
| 219 |
+
def load_from_disk(filepath: str) -> "DataProto":
|
| 220 |
+
with open(filepath, "rb") as f:
|
| 221 |
+
data = pickle.load(f)
|
| 222 |
+
return data
|
| 223 |
+
|
| 224 |
+
def print_size(self, prefix: str = "") -> None:
|
| 225 |
+
size_of_tensordict = 0
|
| 226 |
+
if self.batch is not None:
|
| 227 |
+
for tensor in self.batch.values():
|
| 228 |
+
if isinstance(tensor, torch.Tensor):
|
| 229 |
+
size_of_tensordict += tensor.element_size() * tensor.numel()
|
| 230 |
+
|
| 231 |
+
size_of_numpy_array = 0
|
| 232 |
+
for value in self.non_tensor_batch.values():
|
| 233 |
+
size_of_numpy_array += value.nbytes
|
| 234 |
+
|
| 235 |
+
size_of_numpy_array /= 1024**3
|
| 236 |
+
size_of_tensordict /= 1024**3
|
| 237 |
+
|
| 238 |
+
message = f"Size of tensordict: {size_of_tensordict} GB, size of non_tensor_batch: {size_of_numpy_array} GB."
|
| 239 |
+
print({prefix}, {message})
|
| 240 |
+
|
| 241 |
+
def check_consistency(self):
|
| 242 |
+
"""Check the consistency of the DataProto. Mainly for batch and non_tensor_batch
|
| 243 |
+
We expose this function as a public one so that user can call themselves directly
|
| 244 |
+
"""
|
| 245 |
+
if self.batch is not None:
|
| 246 |
+
assert len(self.batch.batch_size) == 1, "only support num_batch_dims=1"
|
| 247 |
+
|
| 248 |
+
if self.batch is not None and len(self.non_tensor_batch) != 0:
|
| 249 |
+
# TODO: we can actually lift this restriction if needed
|
| 250 |
+
assert len(self.batch.batch_size) == 1, "only support num_batch_dims=1 when non_tensor_batch is not empty."
|
| 251 |
+
|
| 252 |
+
batch_size = self.batch.batch_size[0]
|
| 253 |
+
for key, value in self.non_tensor_batch.items():
|
| 254 |
+
assert len(value) == batch_size, f"key {key} length {len(value)} is not equal to bsz {batch_size}."
|
| 255 |
+
|
| 256 |
+
@classmethod
|
| 257 |
+
def from_single_dict(
|
| 258 |
+
cls,
|
| 259 |
+
data: Dict[str, Union[torch.Tensor, NDArray]],
|
| 260 |
+
meta_info: Optional[Dict[str, Any]] = None,
|
| 261 |
+
) -> "DataProto":
|
| 262 |
+
tensors, non_tensors = {}, {}
|
| 263 |
+
for key, value in data.items():
|
| 264 |
+
if isinstance(value, torch.Tensor):
|
| 265 |
+
tensors[key] = value
|
| 266 |
+
elif isinstance(value, np.ndarray):
|
| 267 |
+
non_tensors[key] = value
|
| 268 |
+
else:
|
| 269 |
+
raise ValueError(f"Unsupported type in data {type(value)}")
|
| 270 |
+
|
| 271 |
+
return DataProto.from_dict(tensors=tensors, non_tensors=non_tensors, meta_info=meta_info)
|
| 272 |
+
|
| 273 |
+
@classmethod
|
| 274 |
+
def from_dict(
|
| 275 |
+
cls,
|
| 276 |
+
tensors: Dict[str, torch.Tensor],
|
| 277 |
+
non_tensors: Dict[str, NDArray] = None,
|
| 278 |
+
meta_info: Optional[Dict[str, Any]] = None,
|
| 279 |
+
num_batch_dims: int = 1,
|
| 280 |
+
) -> "DataProto":
|
| 281 |
+
"""Create a DataProto from a dict of tensors. This assumes that
|
| 282 |
+
1. All the tensor in tensors have the same dim0
|
| 283 |
+
2. Only dim0 is the batch dim
|
| 284 |
+
"""
|
| 285 |
+
assert len(tensors) > 0, "tensors must not be empty"
|
| 286 |
+
assert num_batch_dims > 0, "num_batch_dims must be greater than zero"
|
| 287 |
+
if non_tensors is not None:
|
| 288 |
+
assert num_batch_dims == 1, "only support num_batch_dims=1 when non_tensors is not None."
|
| 289 |
+
|
| 290 |
+
meta_info = meta_info or {}
|
| 291 |
+
non_tensors = non_tensors or {}
|
| 292 |
+
assert isinstance(non_tensors, dict), "non_tensors should be a dictionary."
|
| 293 |
+
|
| 294 |
+
# get and check batch size
|
| 295 |
+
batch_size = None
|
| 296 |
+
pivot_key = None
|
| 297 |
+
for key, tensor in tensors.items():
|
| 298 |
+
if batch_size is None:
|
| 299 |
+
batch_size = tensor.shape[:num_batch_dims]
|
| 300 |
+
pivot_key = key
|
| 301 |
+
else:
|
| 302 |
+
current_batch = tensor.shape[:num_batch_dims]
|
| 303 |
+
assert batch_size == current_batch, (
|
| 304 |
+
f"Not all the tensor in tensors have the same batch size with batch_dims={num_batch_dims}. "
|
| 305 |
+
f"Got {pivot_key} has {batch_size}, {key} has {current_batch}"
|
| 306 |
+
)
|
| 307 |
+
|
| 308 |
+
tensor_dict = TensorDict(source=tensors, batch_size=batch_size)
|
| 309 |
+
return cls(batch=tensor_dict, non_tensor_batch=non_tensors, meta_info=meta_info)
|
| 310 |
+
|
| 311 |
+
def to(self, device: torch.device) -> "DataProto":
|
| 312 |
+
"""move the batch to device
|
| 313 |
+
|
| 314 |
+
Args:
|
| 315 |
+
device (torch.device, str): torch device
|
| 316 |
+
|
| 317 |
+
Returns:
|
| 318 |
+
DataProto: the current DataProto
|
| 319 |
+
|
| 320 |
+
"""
|
| 321 |
+
if self.batch is not None:
|
| 322 |
+
self.batch = self.batch.to(device)
|
| 323 |
+
|
| 324 |
+
return self
|
| 325 |
+
|
| 326 |
+
def select(
|
| 327 |
+
self,
|
| 328 |
+
batch_keys: Optional[List[str]] = None,
|
| 329 |
+
non_tensor_batch_keys: Optional[List[str]] = None,
|
| 330 |
+
meta_info_keys: Optional[List[str]] = None,
|
| 331 |
+
deepcopy: bool = False,
|
| 332 |
+
) -> "DataProto":
|
| 333 |
+
"""Select a subset of the DataProto via batch_keys and meta_info_keys
|
| 334 |
+
|
| 335 |
+
Args:
|
| 336 |
+
batch_keys (list, optional): a list of strings indicating the keys in batch to select
|
| 337 |
+
meta_info_keys (list, optional): a list of keys indicating the meta info to select
|
| 338 |
+
|
| 339 |
+
Returns:
|
| 340 |
+
DataProto: the DataProto with the selected batch_keys and meta_info_keys
|
| 341 |
+
"""
|
| 342 |
+
# TODO (zhangchi.usc1992) whether to copy
|
| 343 |
+
if batch_keys is not None:
|
| 344 |
+
batch_keys = tuple(batch_keys)
|
| 345 |
+
sub_batch = self.batch.select(*batch_keys)
|
| 346 |
+
else:
|
| 347 |
+
sub_batch = self.batch
|
| 348 |
+
|
| 349 |
+
if non_tensor_batch_keys is not None:
|
| 350 |
+
non_tensor_batch = {k: v for k, v in self.non_tensor_batch.items() if k in non_tensor_batch_keys}
|
| 351 |
+
else:
|
| 352 |
+
non_tensor_batch = self.non_tensor_batch
|
| 353 |
+
|
| 354 |
+
if deepcopy:
|
| 355 |
+
non_tensor_batch = copy.deepcopy(non_tensor_batch)
|
| 356 |
+
|
| 357 |
+
if meta_info_keys is not None:
|
| 358 |
+
sub_meta_info = {k: v for k, v in self.meta_info.items() if k in meta_info_keys}
|
| 359 |
+
else:
|
| 360 |
+
sub_meta_info = self.meta_info
|
| 361 |
+
|
| 362 |
+
if deepcopy:
|
| 363 |
+
sub_meta_info = copy.deepcopy(sub_meta_info)
|
| 364 |
+
|
| 365 |
+
return DataProto(batch=sub_batch, non_tensor_batch=non_tensor_batch, meta_info=sub_meta_info)
|
| 366 |
+
|
| 367 |
+
def pop(
|
| 368 |
+
self,
|
| 369 |
+
batch_keys: Optional[List[str]] = None,
|
| 370 |
+
non_tensor_batch_keys: Optional[List[str]] = None,
|
| 371 |
+
meta_info_keys: Optional[List[str]] = None,
|
| 372 |
+
) -> "DataProto":
|
| 373 |
+
"""Pop a subset of the DataProto via `batch_keys` and `meta_info_keys`
|
| 374 |
+
|
| 375 |
+
Args:
|
| 376 |
+
batch_keys (list, optional): a list of strings indicating the keys in batch to pop
|
| 377 |
+
meta_info_keys (list, optional): a list of keys indicating the meta info to pop
|
| 378 |
+
|
| 379 |
+
Returns:
|
| 380 |
+
DataProto: the DataProto with the poped batch_keys and meta_info_keys
|
| 381 |
+
"""
|
| 382 |
+
assert batch_keys is not None
|
| 383 |
+
non_tensor_batch_keys = non_tensor_batch_keys or []
|
| 384 |
+
meta_info_keys = meta_info_keys or []
|
| 385 |
+
|
| 386 |
+
tensors = {}
|
| 387 |
+
for key in batch_keys:
|
| 388 |
+
tensors[key] = self.batch.pop(key)
|
| 389 |
+
|
| 390 |
+
non_tensors = {}
|
| 391 |
+
for key in non_tensor_batch_keys:
|
| 392 |
+
non_tensors[key] = self.non_tensor_batch.pop(key)
|
| 393 |
+
|
| 394 |
+
meta_info = {}
|
| 395 |
+
for key in meta_info_keys:
|
| 396 |
+
meta_info[key] = self.meta_info.pop(key)
|
| 397 |
+
|
| 398 |
+
return DataProto.from_dict(tensors=tensors, non_tensors=non_tensors, meta_info=meta_info)
|
| 399 |
+
|
| 400 |
+
def rename(
|
| 401 |
+
self, old_keys: Optional[Union[str, List[str]]] = None, new_keys: Optional[Union[str, List[str]]] = None
|
| 402 |
+
) -> "DataProto":
|
| 403 |
+
"""
|
| 404 |
+
Note that this function only rename the key in the batch
|
| 405 |
+
"""
|
| 406 |
+
|
| 407 |
+
def validate_input(keys):
|
| 408 |
+
if keys is not None:
|
| 409 |
+
if isinstance(keys, str):
|
| 410 |
+
keys = [keys]
|
| 411 |
+
elif isinstance(keys, list):
|
| 412 |
+
pass
|
| 413 |
+
else:
|
| 414 |
+
raise TypeError(f"keys must be a list or a string, but got {type(keys)}")
|
| 415 |
+
return keys
|
| 416 |
+
|
| 417 |
+
old_keys = validate_input(old_keys)
|
| 418 |
+
new_keys = validate_input(new_keys)
|
| 419 |
+
|
| 420 |
+
if len(new_keys) != len(old_keys):
|
| 421 |
+
raise ValueError(
|
| 422 |
+
f"new_keys and old_keys must have the same length, but got {len(new_keys)} and {len(old_keys)}"
|
| 423 |
+
)
|
| 424 |
+
|
| 425 |
+
self.batch.rename_key_(tuple(old_keys), tuple(new_keys))
|
| 426 |
+
|
| 427 |
+
return self
|
| 428 |
+
|
| 429 |
+
def union(self, other: "DataProto") -> "DataProto":
|
| 430 |
+
"""Union with another DataProto. Union batch and meta_info separately.
|
| 431 |
+
Throw an error if
|
| 432 |
+
- there are conflict keys in batch and they are not equal
|
| 433 |
+
- the batch size of two data batch is not the same
|
| 434 |
+
- there are conflict keys in meta_info and they are not the same.
|
| 435 |
+
|
| 436 |
+
Args:
|
| 437 |
+
other (DataProto): another DataProto to union
|
| 438 |
+
|
| 439 |
+
Returns:
|
| 440 |
+
DataProto: the DataProto after union
|
| 441 |
+
"""
|
| 442 |
+
self.batch = union_tensor_dict(self.batch, other.batch)
|
| 443 |
+
self.non_tensor_batch = union_numpy_dict(self.non_tensor_batch, other.non_tensor_batch)
|
| 444 |
+
self.meta_info = union_two_dict(self.meta_info, other.meta_info)
|
| 445 |
+
return self
|
| 446 |
+
|
| 447 |
+
def make_iterator(
|
| 448 |
+
self, mini_batch_size: int, epochs: int, seed: int = None, dataloader_kwargs: Dict[str, Any] = None
|
| 449 |
+
):
|
| 450 |
+
"""Make an iterator from the DataProto. This is built upon that TensorDict can be used as a normal Pytorch
|
| 451 |
+
dataset. See https://pytorch.org/tensordict/tutorials/data_fashion for more details.
|
| 452 |
+
|
| 453 |
+
Args:
|
| 454 |
+
mini_batch_size (int): mini-batch size when iterating the dataset. We require that
|
| 455 |
+
``batch.batch_size[0] % mini_batch_size == 0``
|
| 456 |
+
epochs (int): number of epochs when iterating the dataset.
|
| 457 |
+
dataloader_kwargs: internally, it returns a DataLoader over the batch.
|
| 458 |
+
The dataloader_kwargs is the kwargs passed to the DataLoader
|
| 459 |
+
|
| 460 |
+
Returns:
|
| 461 |
+
Iterator: an iterator that yields a mini-batch data at a time. The total number of iteration steps is
|
| 462 |
+
``self.batch.batch_size * epochs // mini_batch_size``
|
| 463 |
+
"""
|
| 464 |
+
assert self.batch.batch_size[0] % mini_batch_size == 0, f"{self.batch.batch_size[0]} % {mini_batch_size} != 0"
|
| 465 |
+
# we can directly create a dataloader from TensorDict
|
| 466 |
+
if dataloader_kwargs is None:
|
| 467 |
+
dataloader_kwargs = {}
|
| 468 |
+
|
| 469 |
+
if seed is not None:
|
| 470 |
+
generator = torch.Generator()
|
| 471 |
+
generator.manual_seed(seed)
|
| 472 |
+
else:
|
| 473 |
+
generator = None
|
| 474 |
+
|
| 475 |
+
assert isinstance(dataloader_kwargs, Dict)
|
| 476 |
+
train_dataloader = DataLoader(
|
| 477 |
+
dataset=self, batch_size=mini_batch_size, collate_fn=collate_fn, generator=generator, **dataloader_kwargs
|
| 478 |
+
)
|
| 479 |
+
|
| 480 |
+
def get_data():
|
| 481 |
+
for _ in range(epochs):
|
| 482 |
+
for d in train_dataloader:
|
| 483 |
+
d.meta_info = self.meta_info
|
| 484 |
+
yield d
|
| 485 |
+
|
| 486 |
+
return iter(get_data())
|
| 487 |
+
|
| 488 |
+
def chunk(self, chunks: int) -> List["DataProto"]:
|
| 489 |
+
"""Split the batch among dim=0 into chunks. The meta_info is passed to each DataProto after split.
|
| 490 |
+
|
| 491 |
+
Args:
|
| 492 |
+
chunks (int): the number of chunks to split on dim=0
|
| 493 |
+
|
| 494 |
+
Returns:
|
| 495 |
+
List[DataProto]: a list of DataProto after splitting
|
| 496 |
+
"""
|
| 497 |
+
assert len(self) % chunks == 0, (
|
| 498 |
+
f"only support equal chunk. Got size of DataProto {len(self)} and chunk {chunks}."
|
| 499 |
+
)
|
| 500 |
+
if self.batch is not None:
|
| 501 |
+
batch_lst = self.batch.chunk(chunks=chunks, dim=0)
|
| 502 |
+
else:
|
| 503 |
+
batch_lst = [None for _ in range(chunks)]
|
| 504 |
+
|
| 505 |
+
non_tensor_batch_lst = [{} for _ in range(chunks)]
|
| 506 |
+
for key, value in self.non_tensor_batch.items():
|
| 507 |
+
assert isinstance(value, np.ndarray)
|
| 508 |
+
non_tensor_lst = np.array_split(value, chunks)
|
| 509 |
+
assert len(non_tensor_lst) == chunks
|
| 510 |
+
for i in range(chunks):
|
| 511 |
+
non_tensor_batch_lst[i][key] = non_tensor_lst[i]
|
| 512 |
+
|
| 513 |
+
output = []
|
| 514 |
+
for i in range(chunks):
|
| 515 |
+
output.append(
|
| 516 |
+
DataProto(batch=batch_lst[i], non_tensor_batch=non_tensor_batch_lst[i], meta_info=self.meta_info)
|
| 517 |
+
)
|
| 518 |
+
|
| 519 |
+
return output
|
| 520 |
+
|
| 521 |
+
def split(self, split_size: int) -> List["DataProto"]:
|
| 522 |
+
chunks = len(self) // split_size
|
| 523 |
+
return self.chunk(chunks)
|
| 524 |
+
|
| 525 |
+
@staticmethod
|
| 526 |
+
def concat(data: List["DataProto"]) -> "DataProto":
|
| 527 |
+
"""Concat a list of DataProto. The batch is concatenated among dim=0.
|
| 528 |
+
The meta_info is assumed to be identical and will use the first one.
|
| 529 |
+
|
| 530 |
+
Args:
|
| 531 |
+
data (List[DataProto]): list of DataProto
|
| 532 |
+
|
| 533 |
+
Returns:
|
| 534 |
+
DataProto: concatenated DataProto
|
| 535 |
+
"""
|
| 536 |
+
batch_lst = [batch.batch for batch in data]
|
| 537 |
+
if batch_lst[0] is not None:
|
| 538 |
+
new_batch = torch.cat(batch_lst, dim=0)
|
| 539 |
+
else:
|
| 540 |
+
new_batch = None
|
| 541 |
+
|
| 542 |
+
non_tensor_batch = batch_collate([d.non_tensor_batch for d in data])
|
| 543 |
+
for key, value in non_tensor_batch.items():
|
| 544 |
+
non_tensor_batch[key] = np.concatenate(value, axis=0)
|
| 545 |
+
|
| 546 |
+
return DataProto(batch=new_batch, non_tensor_batch=non_tensor_batch, meta_info=data[0].meta_info)
|
| 547 |
+
|
| 548 |
+
def reorder(self, indices: torch.Tensor) -> None:
|
| 549 |
+
"""
|
| 550 |
+
Note that this operation is in-place
|
| 551 |
+
"""
|
| 552 |
+
indices_np = indices.detach().numpy()
|
| 553 |
+
self.batch = self.batch[indices]
|
| 554 |
+
self.non_tensor_batch = {key: value[indices_np] for key, value in self.non_tensor_batch.items()}
|
| 555 |
+
|
| 556 |
+
def repeat(self, repeat_times: int = 2, interleave: bool = True) -> "DataProto":
|
| 557 |
+
"""
|
| 558 |
+
Repeat the batch data a specified number of times.
|
| 559 |
+
|
| 560 |
+
Args:
|
| 561 |
+
repeat_times (int): Number of times to repeat the data.
|
| 562 |
+
interleave (bool): Whether to interleave the repeated data.
|
| 563 |
+
|
| 564 |
+
Returns:
|
| 565 |
+
DataProto: A new DataProto with repeated data.
|
| 566 |
+
"""
|
| 567 |
+
if self.batch is not None:
|
| 568 |
+
if interleave:
|
| 569 |
+
# Interleave the data
|
| 570 |
+
repeated_tensors = {
|
| 571 |
+
key: tensor.repeat_interleave(repeat_times, dim=0) for key, tensor in self.batch.items()
|
| 572 |
+
}
|
| 573 |
+
else:
|
| 574 |
+
# Stack the data
|
| 575 |
+
repeated_tensors = {
|
| 576 |
+
key: tensor.unsqueeze(0).expand(repeat_times, *tensor.shape).reshape(-1, *tensor.shape[1:])
|
| 577 |
+
for key, tensor in self.batch.items()
|
| 578 |
+
}
|
| 579 |
+
|
| 580 |
+
repeated_batch = TensorDict(
|
| 581 |
+
source=repeated_tensors,
|
| 582 |
+
batch_size=(self.batch.batch_size[0] * repeat_times,),
|
| 583 |
+
)
|
| 584 |
+
else:
|
| 585 |
+
repeated_batch = None
|
| 586 |
+
|
| 587 |
+
repeated_non_tensor_batch = {}
|
| 588 |
+
for key, value in self.non_tensor_batch.items():
|
| 589 |
+
if interleave:
|
| 590 |
+
repeated_non_tensor_batch[key] = np.repeat(value, repeat_times, axis=0)
|
| 591 |
+
else:
|
| 592 |
+
repeated_non_tensor_batch[key] = np.tile(value, (repeat_times,) + (1,) * (value.ndim - 1))
|
| 593 |
+
|
| 594 |
+
return DataProto(
|
| 595 |
+
batch=repeated_batch,
|
| 596 |
+
non_tensor_batch=repeated_non_tensor_batch,
|
| 597 |
+
meta_info=self.meta_info,
|
| 598 |
+
)
|
| 599 |
+
|
| 600 |
+
|
| 601 |
+
@dataclass
|
| 602 |
+
class DataProtoFuture:
|
| 603 |
+
"""
|
| 604 |
+
DataProtoFuture aims to eliminate actual data fetching on driver. By doing so, the driver doesn't have to wait
|
| 605 |
+
for data so that asynchronous execution becomes possible.
|
| 606 |
+
DataProtoFuture contains a list of futures from another WorkerGroup of size world_size.
|
| 607 |
+
- collect_fn is a Callable that reduces the list of futures to a DataProto
|
| 608 |
+
- dispatch_fn is a Callable that partitions the DataProto into a list of DataProto of size world_size and then select
|
| 609 |
+
|
| 610 |
+
Potential issue: we can optimize dispatch_fn(collect_fn) such that only needed data is fetched on destination
|
| 611 |
+
- DataProtoFuture only supports directly passing from the output of a method to another input. You can't perform any
|
| 612 |
+
operation on the DataProtoFuture in driver.
|
| 613 |
+
"""
|
| 614 |
+
|
| 615 |
+
collect_fn: Callable
|
| 616 |
+
futures: List[ray.ObjectRef]
|
| 617 |
+
dispatch_fn: Callable = None
|
| 618 |
+
|
| 619 |
+
@staticmethod
|
| 620 |
+
def concat(data: List[ray.ObjectRef]) -> "DataProtoFuture":
|
| 621 |
+
output = DataProtoFuture(collect_fn=DataProto.concat, futures=data)
|
| 622 |
+
return output
|
| 623 |
+
|
| 624 |
+
def chunk(self, chunks: int) -> List["DataProtoFuture"]:
|
| 625 |
+
from functools import partial
|
| 626 |
+
|
| 627 |
+
arg_future_lst = []
|
| 628 |
+
for i in range(chunks):
|
| 629 |
+
# note that we can't directly pass i and chunks
|
| 630 |
+
def dispatch_fn(x, i, chunks):
|
| 631 |
+
return x.chunk(chunks=chunks)[i]
|
| 632 |
+
|
| 633 |
+
arg_future = DataProtoFuture(
|
| 634 |
+
collect_fn=self.collect_fn, dispatch_fn=partial(dispatch_fn, i=i, chunks=chunks), futures=self.futures
|
| 635 |
+
)
|
| 636 |
+
arg_future_lst.append(arg_future)
|
| 637 |
+
return arg_future_lst
|
| 638 |
+
|
| 639 |
+
def get(self):
|
| 640 |
+
outputs = ray.get(self.futures) # dp_size.
|
| 641 |
+
for output in outputs:
|
| 642 |
+
assert isinstance(output, DataProto)
|
| 643 |
+
|
| 644 |
+
outputs = self.collect_fn(outputs) # select dp, concat
|
| 645 |
+
if self.dispatch_fn is not None:
|
| 646 |
+
outputs = self.dispatch_fn(outputs) # split in batch dim, select using dp
|
| 647 |
+
|
| 648 |
+
return outputs
|
| 649 |
+
|
| 650 |
+
|
| 651 |
+
def allgather_dict_tensors(
|
| 652 |
+
tensors: Union[Dict[str, torch.Tensor], TensorDict], size: int, group: ProcessGroup, dim: int = 0
|
| 653 |
+
) -> Union[Dict[str, torch.Tensor], TensorDict]:
|
| 654 |
+
"""
|
| 655 |
+
TODO: optimize this.
|
| 656 |
+
- We can use async ops
|
| 657 |
+
- We can use only one allgather
|
| 658 |
+
"""
|
| 659 |
+
if isinstance(tensors, TensorDict):
|
| 660 |
+
is_tensor_dict = True
|
| 661 |
+
tensors_as_dict = tensors.to_dict()
|
| 662 |
+
else:
|
| 663 |
+
tensors_as_dict = tensors
|
| 664 |
+
is_tensor_dict = False
|
| 665 |
+
|
| 666 |
+
output = {}
|
| 667 |
+
sorted_keys = sorted(tensors_as_dict.keys())
|
| 668 |
+
for key in sorted_keys:
|
| 669 |
+
value = tensors_as_dict[key]
|
| 670 |
+
output[key] = [torch.empty_like(value) for _ in range(size)]
|
| 671 |
+
torch.distributed.all_gather(output[key], value, group=group, async_op=False)
|
| 672 |
+
output[key] = torch.cat(output[key], dim=dim)
|
| 673 |
+
|
| 674 |
+
if is_tensor_dict:
|
| 675 |
+
output = TensorDict(source=output, batch_size=tensors.batch_size[0] * size)
|
| 676 |
+
|
| 677 |
+
return output
|
| 678 |
+
|
| 679 |
+
|
| 680 |
+
def all_gather_data_proto(data: DataProto, size: int, group: ProcessGroup) -> None:
|
| 681 |
+
# Note that this is an inplace operator just like torch.distributed.all_gather
|
| 682 |
+
prev_device = data.batch.device
|
| 683 |
+
data.batch = data.batch.cuda(device=torch.cuda.current_device())
|
| 684 |
+
data.batch = allgather_dict_tensors(data.batch.contiguous(), size=size, group=group, dim=0)
|
| 685 |
+
data.batch = data.batch.to(prev_device)
|
| 686 |
+
# all gather non_tensor_batch
|
| 687 |
+
all_non_tensor_batch = [None for _ in range(size)]
|
| 688 |
+
torch.distributed.all_gather_object(all_non_tensor_batch, data.non_tensor_batch, group=group)
|
| 689 |
+
data.non_tensor_batch = {k: np.concatenate([d[k] for d in all_non_tensor_batch]) for k in data.non_tensor_batch}
|
qwen2_vl.cpython-310.pyc
ADDED
|
Binary file (4.45 kB). View file
|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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team
|
| 2 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 3 |
+
# Based on:
|
| 4 |
+
# https://github.com/huggingface/transformers/blob/v4.49.0/src/transformers/models/qwen2_vl/modeling_qwen2_vl.py
|
| 5 |
+
#
|
| 6 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 7 |
+
# you may not use this file except in compliance with the License.
|
| 8 |
+
# You may obtain a copy of the License at
|
| 9 |
+
#
|
| 10 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 11 |
+
#
|
| 12 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 13 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 14 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 15 |
+
# See the License for the specific language governing permissions and
|
| 16 |
+
# limitations under the License.
|
| 17 |
+
|
| 18 |
+
from typing import Optional, Tuple
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
|
| 22 |
+
from .flash_attention_utils import flash_attention_forward
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
try:
|
| 26 |
+
from transformers.models.qwen2_vl.modeling_qwen2_vl import (
|
| 27 |
+
Qwen2VLAttention,
|
| 28 |
+
apply_multimodal_rotary_pos_emb,
|
| 29 |
+
repeat_kv,
|
| 30 |
+
)
|
| 31 |
+
from transformers.models.qwen2_vl.processing_qwen2_vl import Qwen2VLProcessor
|
| 32 |
+
except ImportError:
|
| 33 |
+
pass
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def get_rope_index(
|
| 37 |
+
processor: "Qwen2VLProcessor",
|
| 38 |
+
input_ids: torch.Tensor,
|
| 39 |
+
image_grid_thw: Optional[torch.Tensor] = None,
|
| 40 |
+
video_grid_thw: Optional[torch.Tensor] = None,
|
| 41 |
+
second_per_grid_ts: Optional[torch.Tensor] = None,
|
| 42 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 43 |
+
) -> torch.Tensor:
|
| 44 |
+
"""
|
| 45 |
+
Gets the position ids for Qwen2-VL, it should be generated before sharding the sequence.
|
| 46 |
+
The batch dim has been removed and the input_ids should be a 1D tensor representing a single example.
|
| 47 |
+
https://github.com/huggingface/transformers/blob/v4.49.0/src/transformers/models/qwen2_5_vl/modeling_qwen2_5_vl.py#L1546
|
| 48 |
+
"""
|
| 49 |
+
spatial_merge_size = processor.image_processor.merge_size
|
| 50 |
+
tokens_per_second = 2
|
| 51 |
+
image_token_id = processor.tokenizer.convert_tokens_to_ids("<|image_pad|>")
|
| 52 |
+
video_token_id = processor.tokenizer.convert_tokens_to_ids("<|video_pad|>")
|
| 53 |
+
vision_start_token_id = processor.tokenizer.convert_tokens_to_ids("<|vision_start|>")
|
| 54 |
+
if input_ids is not None and (image_grid_thw is not None or video_grid_thw is not None):
|
| 55 |
+
if attention_mask is None:
|
| 56 |
+
attention_mask = torch.ones_like(input_ids)
|
| 57 |
+
|
| 58 |
+
position_ids = torch.ones(3, input_ids.size(0), dtype=input_ids.dtype, device=input_ids.device) # (3, seqlen)
|
| 59 |
+
image_index, video_index = 0, 0
|
| 60 |
+
input_ids = input_ids[attention_mask == 1]
|
| 61 |
+
image_nums, video_nums = 0, 0
|
| 62 |
+
vision_start_indices = torch.argwhere(input_ids == vision_start_token_id)
|
| 63 |
+
vision_tokens = input_ids[vision_start_indices + 1]
|
| 64 |
+
image_nums = (vision_tokens == image_token_id).sum()
|
| 65 |
+
video_nums = (vision_tokens == video_token_id).sum()
|
| 66 |
+
input_tokens = input_ids.tolist()
|
| 67 |
+
llm_pos_ids_list: list = []
|
| 68 |
+
st = 0
|
| 69 |
+
remain_images, remain_videos = image_nums, video_nums
|
| 70 |
+
for _ in range(image_nums + video_nums):
|
| 71 |
+
if image_token_id in input_tokens and remain_images > 0:
|
| 72 |
+
ed_image = input_tokens.index(image_token_id, st)
|
| 73 |
+
else:
|
| 74 |
+
ed_image = len(input_tokens) + 1
|
| 75 |
+
if video_token_id in input_tokens and remain_videos > 0:
|
| 76 |
+
ed_video = input_tokens.index(video_token_id, st)
|
| 77 |
+
else:
|
| 78 |
+
ed_video = len(input_tokens) + 1
|
| 79 |
+
if ed_image < ed_video:
|
| 80 |
+
t, h, w = (
|
| 81 |
+
image_grid_thw[image_index][0],
|
| 82 |
+
image_grid_thw[image_index][1],
|
| 83 |
+
image_grid_thw[image_index][2],
|
| 84 |
+
)
|
| 85 |
+
second_per_grid_t = 0
|
| 86 |
+
image_index += 1
|
| 87 |
+
remain_images -= 1
|
| 88 |
+
ed = ed_image
|
| 89 |
+
else:
|
| 90 |
+
t, h, w = (
|
| 91 |
+
video_grid_thw[video_index][0],
|
| 92 |
+
video_grid_thw[video_index][1],
|
| 93 |
+
video_grid_thw[video_index][2],
|
| 94 |
+
)
|
| 95 |
+
if second_per_grid_ts is not None:
|
| 96 |
+
second_per_grid_t = second_per_grid_ts[video_index]
|
| 97 |
+
else:
|
| 98 |
+
second_per_grid_t = 1.0
|
| 99 |
+
|
| 100 |
+
video_index += 1
|
| 101 |
+
remain_videos -= 1
|
| 102 |
+
ed = ed_video
|
| 103 |
+
|
| 104 |
+
llm_grid_t, llm_grid_h, llm_grid_w = (
|
| 105 |
+
t.item(),
|
| 106 |
+
h.item() // spatial_merge_size,
|
| 107 |
+
w.item() // spatial_merge_size,
|
| 108 |
+
)
|
| 109 |
+
text_len = ed - st
|
| 110 |
+
|
| 111 |
+
st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0
|
| 112 |
+
llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx)
|
| 113 |
+
|
| 114 |
+
t_index = torch.arange(llm_grid_t).view(-1, 1).expand(-1, llm_grid_h * llm_grid_w)
|
| 115 |
+
t_index = (t_index * second_per_grid_t * tokens_per_second).long().flatten()
|
| 116 |
+
h_index = torch.arange(llm_grid_h).view(1, -1, 1).expand(llm_grid_t, -1, llm_grid_w).flatten()
|
| 117 |
+
w_index = torch.arange(llm_grid_w).view(1, 1, -1).expand(llm_grid_t, llm_grid_h, -1).flatten()
|
| 118 |
+
llm_pos_ids_list.append(torch.stack([t_index, h_index, w_index]) + text_len + st_idx)
|
| 119 |
+
st = ed + llm_grid_t * llm_grid_h * llm_grid_w
|
| 120 |
+
|
| 121 |
+
if st < len(input_tokens):
|
| 122 |
+
st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0
|
| 123 |
+
text_len = len(input_tokens) - st
|
| 124 |
+
llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx)
|
| 125 |
+
|
| 126 |
+
llm_positions = torch.cat(llm_pos_ids_list, dim=1).reshape(3, -1)
|
| 127 |
+
position_ids[..., attention_mask == 1] = llm_positions.to(position_ids.device)
|
| 128 |
+
else:
|
| 129 |
+
if attention_mask is not None:
|
| 130 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
| 131 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
| 132 |
+
position_ids = position_ids.unsqueeze(0).expand(3, -1).to(input_ids.device)
|
| 133 |
+
else:
|
| 134 |
+
position_ids = torch.arange(input_ids.shape[1], device=input_ids.device).view(1, -1).expand(3, -1)
|
| 135 |
+
|
| 136 |
+
return position_ids
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def qwen2_vl_attn_forward(
|
| 140 |
+
self: "Qwen2VLAttention",
|
| 141 |
+
hidden_states: torch.Tensor,
|
| 142 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 143 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 144 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
|
| 145 |
+
**kwargs,
|
| 146 |
+
) -> Tuple[torch.Tensor, None, None]:
|
| 147 |
+
bsz, q_len, _ = hidden_states.size() # q_len = seq_length / sp_size
|
| 148 |
+
query_states = self.q_proj(hidden_states) # (batch_size, seq_length / sp_size, num_heads * head_size)
|
| 149 |
+
key_states = self.k_proj(hidden_states)
|
| 150 |
+
value_states = self.v_proj(hidden_states)
|
| 151 |
+
|
| 152 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 153 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 154 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 155 |
+
|
| 156 |
+
# Because the input can be padded, the absolute sequence length depends on the max position id.
|
| 157 |
+
if position_embeddings is None:
|
| 158 |
+
cos, sin = self.rotary_emb(value_states, position_ids)
|
| 159 |
+
else:
|
| 160 |
+
cos, sin = position_embeddings
|
| 161 |
+
|
| 162 |
+
query_states, key_states = apply_multimodal_rotary_pos_emb(
|
| 163 |
+
query_states, key_states, cos, sin, self.rope_scaling["mrope_section"]
|
| 164 |
+
)
|
| 165 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
| 166 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
| 167 |
+
dropout_rate = 0.0 if not self.training else self.attention_dropout
|
| 168 |
+
|
| 169 |
+
sliding_window = None
|
| 170 |
+
if (
|
| 171 |
+
self.config.use_sliding_window
|
| 172 |
+
and getattr(self.config, "sliding_window", None) is not None
|
| 173 |
+
and self.layer_idx >= self.config.max_window_layers
|
| 174 |
+
):
|
| 175 |
+
sliding_window = self.config.sliding_window
|
| 176 |
+
|
| 177 |
+
attn_output, _ = flash_attention_forward(
|
| 178 |
+
self,
|
| 179 |
+
query_states,
|
| 180 |
+
key_states,
|
| 181 |
+
value_states,
|
| 182 |
+
attention_mask,
|
| 183 |
+
dropout=dropout_rate,
|
| 184 |
+
sliding_window=sliding_window,
|
| 185 |
+
position_ids=position_ids, # important: pass position ids
|
| 186 |
+
) # (batch_size, seq_length, num_head / sp_size, head_size)
|
| 187 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
|
| 188 |
+
attn_output = self.o_proj(attn_output)
|
| 189 |
+
return attn_output, None, None
|