Update deprecated type hinting in models (#18132)
Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com>
This commit is contained in:
@@ -16,7 +16,7 @@
|
||||
"""PyTorch Mllama model."""
|
||||
import math
|
||||
from collections.abc import Iterable, Mapping, Sequence
|
||||
from typing import List, Literal, Optional, Set, Tuple, TypedDict, Union
|
||||
from typing import Literal, Optional, TypedDict, Union
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
@@ -224,7 +224,7 @@ class MllamaMultiModalProcessor(EncDecMultiModalProcessor[MllamaProcessingInfo]
|
||||
|
||||
return mm_inputs
|
||||
|
||||
def _get_num_image_in_last_group(self, prompt_token_ids: List[int]) -> int:
|
||||
def _get_num_image_in_last_group(self, prompt_token_ids: list[int]) -> int:
|
||||
num_images = 0
|
||||
for token_id in prompt_token_ids[::-1]:
|
||||
if token_id == self.info.get_hf_config().image_token_index:
|
||||
@@ -370,8 +370,8 @@ class ColumnParallelConv2dPatch(torch.nn.Module):
|
||||
self,
|
||||
in_channels: int,
|
||||
out_channels: int,
|
||||
kernel_size: Union[int, Tuple[int, int]],
|
||||
stride: Union[int, Tuple[int, int]],
|
||||
kernel_size: Union[int, tuple[int, int]],
|
||||
stride: Union[int, tuple[int, int]],
|
||||
bias: bool = False,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
@@ -603,7 +603,7 @@ class MllamaVisionEncoder(nn.Module):
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
attention_mask: Optional[torch.Tensor] = None,
|
||||
) -> Union[Tuple, BaseModelOutput]:
|
||||
) -> Union[BaseModelOutput]:
|
||||
encoder_states = ()
|
||||
|
||||
for i, encoder_layer in enumerate(self.layers):
|
||||
@@ -878,7 +878,7 @@ class MllamaTextCrossAttention(nn.Module):
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
attention_mask: Optional[torch.Tensor],
|
||||
kv_range_for_decode: Optional[List[Tuple[int, int]]],
|
||||
kv_range_for_decode: Optional[list[tuple[int, int]]],
|
||||
cross_attention_states: Optional[torch.Tensor],
|
||||
) -> torch.Tensor:
|
||||
q, k, v = self.qkv_proj(hidden_states, cross_attention_states)
|
||||
@@ -905,7 +905,7 @@ class MllamaTextCrossAttention(nn.Module):
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
attention_mask: torch.Tensor,
|
||||
kv_range_for_decode: List[Tuple[int, int]],
|
||||
kv_range_for_decode: list[tuple[int, int]],
|
||||
) -> torch.Tensor:
|
||||
kv_cache = self.attn.kv_cache[self.pipeline_parallel_rank]
|
||||
attn_metadata: AttentionMetadata = get_forward_context().attn_metadata
|
||||
@@ -1019,7 +1019,7 @@ class MllamaCrossAttentionDecoderLayer(torch.nn.Module):
|
||||
hidden_states: torch.Tensor,
|
||||
cross_attention_states: torch.Tensor,
|
||||
cross_attention_mask: torch.Tensor,
|
||||
kv_range_for_decode: Optional[List[Tuple[int, int]]],
|
||||
kv_range_for_decode: Optional[list[tuple[int, int]]],
|
||||
full_text_row_masked_out_mask: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
residual = hidden_states
|
||||
@@ -1089,8 +1089,8 @@ class MllamaTextModel(nn.Module):
|
||||
positions: Optional[torch.LongTensor],
|
||||
cross_attention_states: Optional[torch.LongTensor],
|
||||
cross_attention_mask: Optional[torch.LongTensor],
|
||||
kv_range_for_decode: Optional[List[Tuple[int, int]]],
|
||||
full_text_row_masked_out_mask: Optional[Tuple[torch.Tensor,
|
||||
kv_range_for_decode: Optional[list[tuple[int, int]]],
|
||||
full_text_row_masked_out_mask: Optional[tuple[torch.Tensor,
|
||||
torch.Tensor]],
|
||||
skip_cross_attention: bool,
|
||||
) -> torch.Tensor:
|
||||
@@ -1150,8 +1150,8 @@ class MllamaForCausalLM(nn.Module):
|
||||
positions: Optional[torch.LongTensor],
|
||||
cross_attention_states: Optional[torch.LongTensor],
|
||||
cross_attention_mask: Optional[torch.LongTensor],
|
||||
kv_range_for_decode: Optional[List[Tuple[int, int]]],
|
||||
full_text_row_masked_out_mask: Optional[Tuple[torch.Tensor,
|
||||
kv_range_for_decode: Optional[list[tuple[int, int]]],
|
||||
full_text_row_masked_out_mask: Optional[tuple[torch.Tensor,
|
||||
torch.Tensor]],
|
||||
skip_cross_attention: bool,
|
||||
) -> torch.Tensor:
|
||||
@@ -1221,7 +1221,7 @@ class MllamaForConditionalGeneration(nn.Module, SupportsMultiModal,
|
||||
return logits
|
||||
|
||||
def unpack_data(self,
|
||||
image_data: Union[List[torch.Tensor], torch.Tensor],
|
||||
image_data: Union[list[torch.Tensor], torch.Tensor],
|
||||
padding_value=0) -> torch.Tensor:
|
||||
if isinstance(image_data, torch.Tensor):
|
||||
# torch.Tensor
|
||||
@@ -1230,7 +1230,7 @@ class MllamaForConditionalGeneration(nn.Module, SupportsMultiModal,
|
||||
assert isinstance(
|
||||
image_data[0],
|
||||
torch.Tensor), "Image data is not properly batched."
|
||||
# List[torch.Tensor]
|
||||
# list[torch.Tensor]
|
||||
bsz = len(image_data)
|
||||
max_length = max(t.size(0) for t in image_data)
|
||||
trailing_dims = image_data[0].shape[1:]
|
||||
@@ -1248,24 +1248,24 @@ class MllamaForConditionalGeneration(nn.Module, SupportsMultiModal,
|
||||
def _parse_and_validate_image_input(self, **kwargs: object):
|
||||
# tensor with the same shape will be batched together by
|
||||
# MultiModalKwargs.batch, so pixel_values here can be:
|
||||
# - List[torch.Tensor]:
|
||||
# - list[torch.Tensor]:
|
||||
# with shape (num_image, num_tiles, 3, image_res, image_res)
|
||||
# - torch.Tensor:
|
||||
# with shape (bs, num_image, num_tiles, 3, image_res, image_res)
|
||||
pixel_values: Optional[Union[List[List[torch.Tensor]],
|
||||
List[torch.Tensor],
|
||||
pixel_values: Optional[Union[list[list[torch.Tensor]],
|
||||
list[torch.Tensor],
|
||||
torch.Tensor]] = kwargs.pop(
|
||||
"pixel_values", None)
|
||||
image_embeds: Optional[Union[List[List[torch.Tensor]],
|
||||
List[torch.Tensor],
|
||||
image_embeds: Optional[Union[list[list[torch.Tensor]],
|
||||
list[torch.Tensor],
|
||||
torch.Tensor]] = kwargs.pop(
|
||||
"image_embeds", None)
|
||||
aspect_ratio_ids: Optional[Union[List[List[torch.Tensor]],
|
||||
List[torch.Tensor],
|
||||
aspect_ratio_ids: Optional[Union[list[list[torch.Tensor]],
|
||||
list[torch.Tensor],
|
||||
torch.Tensor]] = kwargs.pop(
|
||||
"aspect_ratio_ids", None)
|
||||
aspect_ratio_mask: Optional[Union[List[List[torch.Tensor]],
|
||||
List[torch.Tensor],
|
||||
aspect_ratio_mask: Optional[Union[list[list[torch.Tensor]],
|
||||
list[torch.Tensor],
|
||||
torch.Tensor]] = kwargs.pop(
|
||||
"aspect_ratio_mask", None)
|
||||
|
||||
@@ -1293,10 +1293,10 @@ class MllamaForConditionalGeneration(nn.Module, SupportsMultiModal,
|
||||
|
||||
def _get_and_validate_encoder_lens(
|
||||
self,
|
||||
encoder_seq_lens: List[int],
|
||||
num_tiles: List[List[int]],
|
||||
encoder_seq_lens: list[int],
|
||||
num_tiles: list[list[int]],
|
||||
num_tokens_per_tile: int,
|
||||
) -> List[int]:
|
||||
) -> list[int]:
|
||||
# Get the actual number of encoder tokens for each sample.
|
||||
# Because attn_metadata.encoder_seq_lens only counts the last
|
||||
# group of images for each sample, which is used to cheat the
|
||||
@@ -1318,7 +1318,7 @@ class MllamaForConditionalGeneration(nn.Module, SupportsMultiModal,
|
||||
|
||||
def flat_encoder_result(self, cross_attention_states: torch.Tensor,
|
||||
attn_metadata: AttentionMetadata,
|
||||
actual_encoder_seq_lens: List[int]):
|
||||
actual_encoder_seq_lens: list[int]):
|
||||
|
||||
cross_attention_states_flat = torch.zeros(
|
||||
sum(actual_encoder_seq_lens),
|
||||
@@ -1342,8 +1342,8 @@ class MllamaForConditionalGeneration(nn.Module, SupportsMultiModal,
|
||||
self,
|
||||
image_inputs: MllamaImagePixelInputs,
|
||||
attn_metadata: AttentionMetadata,
|
||||
actual_encoder_seq_lens: List[int],
|
||||
) -> Tuple[torch.Tensor]:
|
||||
actual_encoder_seq_lens: list[int],
|
||||
) -> tuple[torch.Tensor]:
|
||||
# NOTE: llama's reference implementation runs vision model on CPU
|
||||
pixel_values = image_inputs['data']
|
||||
aspect_ratio_ids = image_inputs['aspect_ratio_ids']
|
||||
@@ -1367,10 +1367,10 @@ class MllamaForConditionalGeneration(nn.Module, SupportsMultiModal,
|
||||
self,
|
||||
input_ids: torch.Tensor,
|
||||
attn_metadata: AttentionMetadata,
|
||||
num_tiles: List[List[int]],
|
||||
num_tiles: list[list[int]],
|
||||
num_tokens_per_tile: int,
|
||||
dtype: torch.dtype,
|
||||
) -> Tuple[torch.Tensor, torch.Tensor]:
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
token_ids = input_ids.tolist()
|
||||
start = 0
|
||||
batch_token_ids = []
|
||||
@@ -1422,7 +1422,7 @@ class MllamaForConditionalGeneration(nn.Module, SupportsMultiModal,
|
||||
input_ids: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
**kwargs: object,
|
||||
) -> Union[Tuple, CausalLMOutputWithPast]:
|
||||
) -> Union[CausalLMOutputWithPast]:
|
||||
attn_metadata = get_forward_context().attn_metadata
|
||||
if attn_metadata.num_prefill_tokens > 0 and \
|
||||
attn_metadata.num_decode_tokens > 0:
|
||||
@@ -1476,8 +1476,8 @@ class MllamaForConditionalGeneration(nn.Module, SupportsMultiModal,
|
||||
|
||||
return outputs
|
||||
|
||||
def load_weights(self, weights: Iterable[Tuple[str,
|
||||
torch.Tensor]]) -> Set[str]:
|
||||
def load_weights(self, weights: Iterable[tuple[str,
|
||||
torch.Tensor]]) -> set[str]:
|
||||
stacked_params_mapping = [
|
||||
# (param_name, shard_name, shard_id)
|
||||
(".qkv_proj", ".q_proj", "q"),
|
||||
@@ -1487,7 +1487,7 @@ class MllamaForConditionalGeneration(nn.Module, SupportsMultiModal,
|
||||
(".gate_up_proj", ".up_proj", 1),
|
||||
]
|
||||
params_dict = dict(self.named_parameters())
|
||||
updated_params: Set[str] = set()
|
||||
updated_params: set[str] = set()
|
||||
for name, loaded_weight in weights:
|
||||
if 'patch_embedding.weight' in name:
|
||||
name = name.replace('patch_embedding.weight',
|
||||
@@ -1538,7 +1538,7 @@ class MllamaForConditionalGeneration(nn.Module, SupportsMultiModal,
|
||||
tower_model="vision_model")
|
||||
|
||||
|
||||
def skip_attention_mask(sparse_mask: List[List[int]]) -> bool:
|
||||
def skip_attention_mask(sparse_mask: list[list[int]]) -> bool:
|
||||
for mask in sparse_mask:
|
||||
# Skip text-only samples.
|
||||
if len(mask) == 0:
|
||||
@@ -1556,10 +1556,10 @@ def skip_attention_mask(sparse_mask: List[List[int]]) -> bool:
|
||||
|
||||
|
||||
def convert_sparse_cross_attention_mask_to_dense(
|
||||
sparse_mask: List[List[List[int]]],
|
||||
num_tiles: List[List[int]],
|
||||
lengths: List[int],
|
||||
) -> Tuple[np.ndarray, List[Tuple[int, int]]]:
|
||||
sparse_mask: list[list[list[int]]],
|
||||
num_tiles: list[list[int]],
|
||||
lengths: list[int],
|
||||
) -> tuple[np.ndarray, list[tuple[int, int]]]:
|
||||
total_length = sum(lengths)
|
||||
total_tiles = sum([sum(tiles) for tiles in num_tiles])
|
||||
dense_mask = np.zeros(shape=(total_length, total_tiles), dtype=np.int64)
|
||||
|
||||
Reference in New Issue
Block a user