AdithyaSK HF Staff commited on
Commit
5a0060e
·
verified ·
1 Parent(s): 10baf90

Stage Harbor release files 42001-42500

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/umt5/modeling_umt5.py +1959 -0
  2. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/unispeech/__init__.py +27 -0
  3. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/unispeech/configuration_unispeech.py +309 -0
  4. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/unispeech/convert_unispeech_original_pytorch_checkpoint_to_pytorch.py +273 -0
  5. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/unispeech/modeling_unispeech.py +1518 -0
  6. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/unispeech/modular_unispeech.py +445 -0
  7. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/unispeech_sat/__init__.py +27 -0
  8. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/unispeech_sat/configuration_unispeech_sat.py +327 -0
  9. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/unispeech_sat/convert_unispeech_original_s3prl_checkpoint_to_pytorch.py +109 -0
  10. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/unispeech_sat/convert_unispeech_sat_original_pytorch_checkpoint_to_pytorch.py +224 -0
  11. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/unispeech_sat/modeling_unispeech_sat.py +1826 -0
  12. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/unispeech_sat/modular_unispeech_sat.py +457 -0
  13. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/univnet/__init__.py +28 -0
  14. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/univnet/configuration_univnet.py +125 -0
  15. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/univnet/convert_univnet.py +162 -0
  16. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/univnet/feature_extraction_univnet.py +459 -0
  17. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/univnet/modeling_univnet.py +618 -0
  18. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/upernet/__init__.py +27 -0
  19. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/upernet/configuration_upernet.py +148 -0
  20. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/upernet/convert_convnext_upernet_to_pytorch.py +214 -0
  21. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/upernet/convert_swin_upernet_to_pytorch.py +297 -0
  22. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/upernet/modeling_upernet.py +388 -0
  23. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/video_llava/__init__.py +29 -0
  24. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/video_llava/configuration_video_llava.py +143 -0
  25. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/video_llava/convert_video_llava_weights_to_hf.py +159 -0
  26. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/video_llava/image_processing_video_llava.py +390 -0
  27. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/video_llava/modeling_video_llava.py +721 -0
  28. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/video_llava/processing_video_llava.py +223 -0
  29. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/video_llava/video_processing_video_llava.py +57 -0
  30. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/videomae/__init__.py +29 -0
  31. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/videomae/configuration_videomae.py +148 -0
  32. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/videomae/convert_videomae_to_pytorch.py +324 -0
  33. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/videomae/feature_extraction_videomae.py +38 -0
  34. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/videomae/image_processing_videomae.py +350 -0
  35. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/videomae/modeling_videomae.py +1048 -0
  36. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/vilt/__init__.py +31 -0
  37. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/vilt/configuration_vilt.py +147 -0
  38. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/vilt/convert_vilt_original_to_pytorch.py +299 -0
  39. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/vilt/feature_extraction_vilt.py +38 -0
  40. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/vilt/image_processing_vilt.py +492 -0
  41. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/vilt/image_processing_vilt_fast.py +263 -0
  42. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/vilt/modeling_vilt.py +1356 -0
  43. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/vilt/processing_vilt.py +151 -0
  44. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/vipllava/__init__.py +27 -0
  45. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/vipllava/configuration_vipllava.py +122 -0
  46. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/vipllava/convert_vipllava_weights_to_hf.py +132 -0
  47. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/vipllava/modeling_vipllava.py +464 -0
  48. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/vipllava/modular_vipllava.py +278 -0
  49. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/vision_encoder_decoder/__init__.py +29 -0
  50. tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/vision_encoder_decoder/configuration_vision_encoder_decoder.py +215 -0
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/umt5/modeling_umt5.py ADDED
@@ -0,0 +1,1959 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Mesh TensorFlow authors, T5 Authors and HuggingFace Inc. team.
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
+ """PyTorch UMT5 model."""
16
+
17
+ import copy
18
+ import math
19
+ from typing import Optional, Union
20
+
21
+ import torch
22
+ from torch import nn
23
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
24
+
25
+ from ...activations import ACT2FN
26
+ from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
27
+ from ...generation import GenerationMixin
28
+ from ...modeling_attn_mask_utils import AttentionMaskConverter
29
+ from ...modeling_layers import GradientCheckpointingLayer
30
+ from ...modeling_outputs import (
31
+ BaseModelOutput,
32
+ BaseModelOutputWithPastAndCrossAttentions,
33
+ Seq2SeqLMOutput,
34
+ Seq2SeqModelOutput,
35
+ Seq2SeqQuestionAnsweringModelOutput,
36
+ Seq2SeqSequenceClassifierOutput,
37
+ TokenClassifierOutput,
38
+ )
39
+ from ...modeling_utils import PreTrainedModel
40
+ from ...utils import (
41
+ DUMMY_INPUTS,
42
+ DUMMY_MASK,
43
+ auto_docstring,
44
+ is_torch_flex_attn_available,
45
+ is_torch_fx_proxy,
46
+ is_torchdynamo_compiling,
47
+ logging,
48
+ )
49
+ from ...utils.deprecation import deprecate_kwarg
50
+ from .configuration_umt5 import UMT5Config
51
+
52
+
53
+ if is_torch_flex_attn_available():
54
+ from torch.nn.attention.flex_attention import BlockMask
55
+
56
+ from ...integrations.flex_attention import make_flex_block_causal_mask
57
+
58
+ logger = logging.get_logger(__name__)
59
+
60
+
61
+ # Copied from transformers.models.t5.modeling_t5.T5LayerNorm with T5->UMT5
62
+ class UMT5LayerNorm(nn.Module):
63
+ def __init__(self, hidden_size, eps=1e-6):
64
+ """
65
+ Construct a layernorm module in the UMT5 style. No bias and no subtraction of mean.
66
+ """
67
+ super().__init__()
68
+ self.weight = nn.Parameter(torch.ones(hidden_size))
69
+ self.variance_epsilon = eps
70
+
71
+ def forward(self, hidden_states):
72
+ # UMT5 uses a layer_norm which only scales and doesn't shift, which is also known as Root Mean
73
+ # Square Layer Normalization https://huggingface.co/papers/1910.07467 thus variance is calculated
74
+ # w/o mean and there is no bias. Additionally we want to make sure that the accumulation for
75
+ # half-precision inputs is done in fp32
76
+
77
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
78
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
79
+
80
+ # convert into half-precision if necessary
81
+ if self.weight.dtype in [torch.float16, torch.bfloat16]:
82
+ hidden_states = hidden_states.to(self.weight.dtype)
83
+
84
+ return self.weight * hidden_states
85
+
86
+
87
+ # Copied from transformers.models.t5.modeling_t5.T5DenseActDense with T5->UMT5
88
+ class UMT5DenseActDense(nn.Module):
89
+ def __init__(self, config: UMT5Config):
90
+ super().__init__()
91
+ self.wi = nn.Linear(config.d_model, config.d_ff, bias=False)
92
+ self.wo = nn.Linear(config.d_ff, config.d_model, bias=False)
93
+ self.dropout = nn.Dropout(config.dropout_rate)
94
+ self.act = ACT2FN[config.dense_act_fn]
95
+
96
+ def forward(self, hidden_states):
97
+ hidden_states = self.wi(hidden_states)
98
+ hidden_states = self.act(hidden_states)
99
+ hidden_states = self.dropout(hidden_states)
100
+ if (
101
+ isinstance(self.wo.weight, torch.Tensor)
102
+ and hidden_states.dtype != self.wo.weight.dtype
103
+ and self.wo.weight.dtype != torch.int8
104
+ ):
105
+ hidden_states = hidden_states.to(self.wo.weight.dtype)
106
+ hidden_states = self.wo(hidden_states)
107
+ return hidden_states
108
+
109
+
110
+ # Copied from transformers.models.t5.modeling_t5.T5DenseGatedActDense with T5->UMT5
111
+ class UMT5DenseGatedActDense(nn.Module):
112
+ def __init__(self, config: UMT5Config):
113
+ super().__init__()
114
+ self.wi_0 = nn.Linear(config.d_model, config.d_ff, bias=False)
115
+ self.wi_1 = nn.Linear(config.d_model, config.d_ff, bias=False)
116
+ self.wo = nn.Linear(config.d_ff, config.d_model, bias=False)
117
+ self.dropout = nn.Dropout(config.dropout_rate)
118
+ self.act = ACT2FN[config.dense_act_fn]
119
+
120
+ def forward(self, hidden_states):
121
+ hidden_gelu = self.act(self.wi_0(hidden_states))
122
+ hidden_linear = self.wi_1(hidden_states)
123
+ hidden_states = hidden_gelu * hidden_linear
124
+ hidden_states = self.dropout(hidden_states)
125
+
126
+ # To make 8bit quantization work for google/flan-t5-xxl, self.wo is kept in float32.
127
+ # See https://github.com/huggingface/transformers/issues/20287
128
+ # we also make sure the weights are not in `int8` in case users will force `_keep_in_fp32_modules` to be `None``
129
+ if (
130
+ isinstance(self.wo.weight, torch.Tensor)
131
+ and hidden_states.dtype != self.wo.weight.dtype
132
+ and self.wo.weight.dtype != torch.int8
133
+ ):
134
+ hidden_states = hidden_states.to(self.wo.weight.dtype)
135
+
136
+ hidden_states = self.wo(hidden_states)
137
+ return hidden_states
138
+
139
+
140
+ # Copied from transformers.models.t5.modeling_t5.T5LayerFF with T5->UMT5
141
+ class UMT5LayerFF(nn.Module):
142
+ def __init__(self, config: UMT5Config):
143
+ super().__init__()
144
+ if config.is_gated_act:
145
+ self.DenseReluDense = UMT5DenseGatedActDense(config)
146
+ else:
147
+ self.DenseReluDense = UMT5DenseActDense(config)
148
+
149
+ self.layer_norm = UMT5LayerNorm(config.d_model, eps=config.layer_norm_epsilon)
150
+ self.dropout = nn.Dropout(config.dropout_rate)
151
+
152
+ def forward(self, hidden_states):
153
+ forwarded_states = self.layer_norm(hidden_states)
154
+ forwarded_states = self.DenseReluDense(forwarded_states)
155
+ hidden_states = hidden_states + self.dropout(forwarded_states)
156
+ return hidden_states
157
+
158
+
159
+ class UMT5Attention(nn.Module):
160
+ """
161
+ T5's attention using relative_attention_bias.
162
+ """
163
+
164
+ def __init__(self, config, has_relative_attention_bias=False, layer_idx: Optional[int] = None):
165
+ super().__init__()
166
+ self.is_decoder = config.is_decoder
167
+ self.has_relative_attention_bias = has_relative_attention_bias
168
+ self.relative_attention_num_buckets = config.relative_attention_num_buckets
169
+ self.relative_attention_max_distance = config.relative_attention_max_distance
170
+ self.d_model = config.d_model
171
+ self.key_value_proj_dim = config.d_kv
172
+ self.n_heads = config.num_heads
173
+ self.dropout = config.dropout_rate
174
+ self.inner_dim = self.n_heads * self.key_value_proj_dim
175
+ self.layer_idx = layer_idx
176
+ if layer_idx is None and self.is_decoder:
177
+ logger.warning_once(
178
+ f"Instantiating a decoder {self.__class__.__name__} without passing `layer_idx` is not recommended and "
179
+ "will to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
180
+ "when creating this class."
181
+ )
182
+
183
+ # Mesh TensorFlow initialization to avoid scaling before softmax
184
+ self.q = nn.Linear(self.d_model, self.inner_dim, bias=False)
185
+ self.k = nn.Linear(self.d_model, self.inner_dim, bias=False)
186
+ self.v = nn.Linear(self.d_model, self.inner_dim, bias=False)
187
+ self.o = nn.Linear(self.inner_dim, self.d_model, bias=False)
188
+
189
+ if self.has_relative_attention_bias:
190
+ self.relative_attention_bias = nn.Embedding(self.relative_attention_num_buckets, self.n_heads)
191
+ self.pruned_heads = set()
192
+
193
+ def _shape(self, projection: torch.Tensor) -> torch.Tensor:
194
+ new_projection_shape = projection.size()[:-1] + (self.n_heads, self.key_value_proj_dim)
195
+ # move heads to 2nd position (B, T, H * D) -> (B, T, H, D) -> (B, H, T, D)
196
+ new_projection = projection.view(new_projection_shape).permute(0, 2, 1, 3)
197
+ return new_projection
198
+
199
+ def _relative_position_bucket(self, relative_position):
200
+ """
201
+ Adapted from Mesh Tensorflow:
202
+ https://github.com/tensorflow/mesh/blob/0cb87fe07da627bf0b7e60475d59f95ed6b5be3d/mesh_tensorflow/transformer/transformer_layers.py#L593
203
+
204
+ Translate relative position to a bucket number for relative attention. The relative position is defined as
205
+ memory_position - query_position, i.e. the distance in tokens from the attending position to the attended-to
206
+ position. If bidirectional=False, then positive relative positions are invalid. We use smaller buckets for
207
+ small absolute relative_position and larger buckets for larger absolute relative_positions. All relative
208
+ positions >=max_distance map to the same bucket. All relative positions <=-max_distance map to the same bucket.
209
+ This should allow for more graceful generalization to longer sequences than the model has been trained on
210
+
211
+ Args:
212
+ relative_position: an int32 Tensor
213
+ bidirectional: a boolean - whether the attention is bidirectional
214
+ num_buckets: an integer
215
+ max_distance: an integer
216
+
217
+ Returns:
218
+ a Tensor with the same shape as relative_position, containing int32 values in the range [0, num_buckets)
219
+ """
220
+ relative_buckets = 0
221
+ num_buckets = self.relative_attention_num_buckets
222
+ max_distance = self.relative_attention_max_distance
223
+ if not self.is_decoder:
224
+ num_buckets //= 2
225
+ relative_buckets += (relative_position > 0).to(torch.long) * num_buckets
226
+ relative_position = torch.abs(relative_position)
227
+ else:
228
+ relative_position = -torch.min(relative_position, torch.zeros_like(relative_position))
229
+ # now relative_position is in the range [0, inf)
230
+
231
+ # half of the buckets are for exact increments in positions
232
+ max_exact = num_buckets // 2
233
+ is_small = relative_position < max_exact
234
+
235
+ # The other half of the buckets are for logarithmically bigger bins in positions up to max_distance
236
+ log_ratio = torch.log(relative_position.float() / max_exact) / math.log(max_distance / max_exact)
237
+ log_ratio = log_ratio * (num_buckets - max_exact)
238
+ relative_position_if_large = max_exact + log_ratio.to(torch.long)
239
+ relative_position_if_large = torch.min(
240
+ relative_position_if_large, torch.full_like(relative_position_if_large, num_buckets - 1)
241
+ )
242
+
243
+ relative_buckets += torch.where(is_small, relative_position, relative_position_if_large)
244
+ return relative_buckets
245
+
246
+ def compute_bias(self, query_length, key_length, device=None, cache_position=None):
247
+ """Compute binned relative position bias"""
248
+ if device is None:
249
+ device = self.relative_attention_bias.weight.device
250
+ if cache_position is None:
251
+ context_position = torch.arange(query_length, dtype=torch.long, device=device)[:, None]
252
+ else:
253
+ context_position = cache_position[:, None]
254
+ memory_position = torch.arange(key_length, dtype=torch.long, device=device)[None, :]
255
+ relative_position = memory_position - context_position # shape (query_length, key_length)
256
+ relative_position_bucket = self._relative_position_bucket(relative_position)
257
+ values = self.relative_attention_bias(relative_position_bucket) # shape (query_length, key_length, num_heads)
258
+ values = values.permute([2, 0, 1]).unsqueeze(0) # shape (1, num_heads, query_length, key_length)
259
+ return values
260
+
261
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
262
+ def forward(
263
+ self,
264
+ hidden_states: torch.Tensor,
265
+ encoder_hidden_states: Optional[torch.Tensor] = None,
266
+ past_key_values: Optional[tuple[torch.Tensor]] = None,
267
+ attention_mask: Optional[torch.Tensor] = None,
268
+ layer_head_mask: Optional[torch.Tensor] = None,
269
+ cache_position: Optional[torch.Tensor] = None,
270
+ ):
271
+ batch_size, seq_length = hidden_states.shape[:2]
272
+
273
+ # if encoder_hidden_states are provided this layer is used as a cross-attention layer for the decoder
274
+ is_cross_attention = encoder_hidden_states is not None
275
+
276
+ query_states = self.q(hidden_states)
277
+ query_states = query_states.view(batch_size, -1, self.n_heads, self.key_value_proj_dim).transpose(1, 2)
278
+
279
+ # Check is encoder-decoder model is being used. Otherwise we'll get `DynamicCache`
280
+ if past_key_values is not None and isinstance(past_key_values, EncoderDecoderCache):
281
+ is_updated = past_key_values.is_updated.get(self.layer_idx)
282
+ if is_cross_attention:
283
+ # after the first generated id, we can subsequently re-use all key/value_states from cache
284
+ curr_past_key_value = past_key_values.cross_attention_cache
285
+ else:
286
+ curr_past_key_value = past_key_values.self_attention_cache
287
+ else:
288
+ curr_past_key_value = past_key_values
289
+
290
+ current_states = encoder_hidden_states if is_cross_attention else hidden_states
291
+ if is_cross_attention and past_key_values is not None and is_updated:
292
+ # reuse k,v, cross_attentions
293
+ key_states = curr_past_key_value.layers[self.layer_idx].keys
294
+ value_states = curr_past_key_value.layers[self.layer_idx].values
295
+ else:
296
+ key_states = self.k(current_states)
297
+ value_states = self.v(current_states)
298
+ key_states = key_states.view(batch_size, -1, self.n_heads, self.key_value_proj_dim).transpose(1, 2)
299
+ value_states = value_states.view(batch_size, -1, self.n_heads, self.key_value_proj_dim).transpose(1, 2)
300
+
301
+ if past_key_values is not None:
302
+ # save all key/value_states to cache to be re-used for fast auto-regressive generation
303
+ cache_position = cache_position if not is_cross_attention else None
304
+ key_states, value_states = curr_past_key_value.update(
305
+ key_states, value_states, self.layer_idx, {"cache_position": cache_position}
306
+ )
307
+ # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
308
+ if is_cross_attention:
309
+ past_key_values.is_updated[self.layer_idx] = True
310
+
311
+ # compute scores, equivalent of torch.einsum("bnqd,bnkd->bnqk", query_states, key_states), compatible with onnx op>9
312
+ scores = torch.matmul(query_states, key_states.transpose(3, 2))
313
+
314
+ # cache position is 0-indexed so we add 1 to get the real length of queries (aka with past)
315
+ real_seq_length = seq_length + past_key_values.get_seq_length() if past_key_values is not None else seq_length
316
+ key_length = key_states.shape[-2]
317
+ if not self.has_relative_attention_bias:
318
+ position_bias = torch.zeros(
319
+ (1, self.n_heads, seq_length, key_length), device=scores.device, dtype=scores.dtype
320
+ )
321
+ else:
322
+ position_bias = self.compute_bias(
323
+ real_seq_length, key_length, device=scores.device, cache_position=cache_position
324
+ )
325
+ position_bias = position_bias[:, :, -seq_length:, :]
326
+
327
+ if attention_mask is not None:
328
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
329
+ position_bias = position_bias + causal_mask
330
+
331
+ if self.pruned_heads:
332
+ mask = torch.ones(position_bias.shape[1])
333
+ mask[list(self.pruned_heads)] = 0
334
+ position_bias_masked = position_bias[:, mask.bool()]
335
+ else:
336
+ position_bias_masked = position_bias
337
+
338
+ scores += position_bias_masked
339
+
340
+ # (batch_size, n_heads, seq_length, key_length)
341
+ attn_weights = nn.functional.softmax(scores.float(), dim=-1).type_as(scores)
342
+ attn_weights = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
343
+
344
+ # Mask heads if we want to
345
+ if layer_head_mask is not None:
346
+ attn_weights = attn_weights * layer_head_mask
347
+
348
+ attn_output = torch.matmul(attn_weights, value_states)
349
+
350
+ attn_output = attn_output.transpose(1, 2).contiguous()
351
+ attn_output = attn_output.view(batch_size, seq_length, -1)
352
+
353
+ attn_output = self.o(attn_output)
354
+ return attn_output, attn_weights
355
+
356
+
357
+ class UMT5LayerSelfAttention(nn.Module):
358
+ def __init__(self, config, layer_idx: Optional[int] = None):
359
+ super().__init__()
360
+ self.SelfAttention = UMT5Attention(config, has_relative_attention_bias=True, layer_idx=layer_idx)
361
+ self.layer_norm = UMT5LayerNorm(config.d_model, eps=config.layer_norm_epsilon)
362
+ self.dropout = nn.Dropout(config.dropout_rate)
363
+
364
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
365
+ def forward(
366
+ self,
367
+ hidden_states,
368
+ attention_mask=None,
369
+ layer_head_mask=None,
370
+ past_key_values=None,
371
+ cache_position=None,
372
+ ):
373
+ normed_hidden_states = self.layer_norm(hidden_states)
374
+ attention_output = self.SelfAttention(
375
+ normed_hidden_states,
376
+ attention_mask=attention_mask,
377
+ layer_head_mask=layer_head_mask,
378
+ past_key_values=past_key_values,
379
+ cache_position=cache_position,
380
+ )
381
+ hidden_states = hidden_states + self.dropout(attention_output[0])
382
+ outputs = (hidden_states,) + attention_output[1:] # add attentions if we output them
383
+ return outputs
384
+
385
+
386
+ class UMT5LayerCrossAttention(nn.Module):
387
+ def __init__(self, config, layer_idx: Optional[int] = None):
388
+ super().__init__()
389
+ self.EncDecAttention = UMT5Attention(config, has_relative_attention_bias=False, layer_idx=layer_idx)
390
+ self.layer_norm = UMT5LayerNorm(config.d_model, eps=config.layer_norm_epsilon)
391
+ self.dropout = nn.Dropout(config.dropout_rate)
392
+
393
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
394
+ def forward(
395
+ self,
396
+ hidden_states,
397
+ encoder_hidden_states=None,
398
+ attention_mask=None,
399
+ layer_head_mask=None,
400
+ past_key_values=None,
401
+ cache_position=None,
402
+ ):
403
+ normed_hidden_states = self.layer_norm(hidden_states)
404
+ attention_output = self.EncDecAttention(
405
+ normed_hidden_states,
406
+ encoder_hidden_states=encoder_hidden_states,
407
+ attention_mask=attention_mask,
408
+ layer_head_mask=layer_head_mask,
409
+ past_key_values=past_key_values,
410
+ cache_position=cache_position,
411
+ )
412
+ layer_output = hidden_states + self.dropout(attention_output[0])
413
+ outputs = (layer_output,) + attention_output[1:] # add attentions if we output them
414
+ return outputs
415
+
416
+
417
+ class UMT5Block(GradientCheckpointingLayer):
418
+ def __init__(self, config, layer_idx: Optional[int] = None):
419
+ super().__init__()
420
+ self.is_decoder = config.is_decoder
421
+ self.layer = nn.ModuleList()
422
+ self.layer.append(UMT5LayerSelfAttention(config, layer_idx=layer_idx))
423
+ if self.is_decoder:
424
+ self.layer.append(UMT5LayerCrossAttention(config, layer_idx=layer_idx))
425
+
426
+ self.layer.append(UMT5LayerFF(config))
427
+
428
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
429
+ def forward(
430
+ self,
431
+ hidden_states,
432
+ attention_mask=None,
433
+ encoder_hidden_states=None,
434
+ encoder_attention_mask=None,
435
+ layer_head_mask=None,
436
+ cross_attn_layer_head_mask=None,
437
+ past_key_values=None,
438
+ use_cache=False,
439
+ output_attentions=False,
440
+ cache_position=None,
441
+ ):
442
+ hidden_states, self_attn_weights = self.layer[0](
443
+ hidden_states,
444
+ attention_mask=attention_mask,
445
+ layer_head_mask=layer_head_mask,
446
+ past_key_values=past_key_values,
447
+ cache_position=cache_position,
448
+ )
449
+
450
+ # clamp inf values to enable fp16 training
451
+ if hidden_states.dtype == torch.float16:
452
+ max_dtype = torch.finfo(hidden_states.dtype).max
453
+ clamp_value = torch.where(torch.isinf(hidden_states).any(), max_dtype - 1000, max_dtype)
454
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
455
+
456
+ # Cross-Attention Block
457
+ cross_attn_weights = None
458
+ do_cross_attention = self.is_decoder and encoder_hidden_states is not None
459
+ if do_cross_attention:
460
+ hidden_states, cross_attn_weights = self.layer[1](
461
+ hidden_states,
462
+ encoder_hidden_states=encoder_hidden_states,
463
+ attention_mask=encoder_attention_mask,
464
+ layer_head_mask=cross_attn_layer_head_mask,
465
+ past_key_values=past_key_values,
466
+ cache_position=cache_position,
467
+ )
468
+ # clamp inf values to enable fp16 training
469
+ if hidden_states.dtype == torch.float16:
470
+ max_dtype = torch.finfo(hidden_states.dtype).max
471
+ clamp_value = torch.where(torch.isinf(hidden_states).any(), max_dtype - 1000, max_dtype)
472
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
473
+
474
+ # Apply Feed Forward layer
475
+ hidden_states = self.layer[-1](hidden_states)
476
+
477
+ # clamp inf values to enable fp16 training
478
+ if hidden_states.dtype == torch.float16:
479
+ max_dtype = torch.finfo(hidden_states.dtype).max
480
+ clamp_value = torch.where(torch.isinf(hidden_states).any(), max_dtype - 1000, max_dtype)
481
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
482
+
483
+ outputs = (hidden_states,)
484
+
485
+ if output_attentions:
486
+ outputs += (self_attn_weights, cross_attn_weights)
487
+
488
+ return outputs
489
+
490
+
491
+ # Copied from transformers.models.t5.modeling_t5.T5ClassificationHead with T5->UMT5
492
+ class UMT5ClassificationHead(nn.Module):
493
+ """Head for sentence-level classification tasks."""
494
+
495
+ def __init__(self, config: UMT5Config):
496
+ super().__init__()
497
+ self.dense = nn.Linear(config.d_model, config.d_model)
498
+ self.dropout = nn.Dropout(p=config.classifier_dropout)
499
+ self.out_proj = nn.Linear(config.d_model, config.num_labels)
500
+
501
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
502
+ hidden_states = self.dropout(hidden_states)
503
+ hidden_states = self.dense(hidden_states)
504
+ hidden_states = torch.tanh(hidden_states)
505
+ hidden_states = self.dropout(hidden_states)
506
+ hidden_states = self.out_proj(hidden_states)
507
+ return hidden_states
508
+
509
+
510
+ @auto_docstring
511
+ class UMT5PreTrainedModel(PreTrainedModel):
512
+ config: UMT5Config
513
+ base_model_prefix = "transformer"
514
+ supports_gradient_checkpointing = True
515
+
516
+ _can_compile_fullgraph = True
517
+ _no_split_modules = ["UMT5Block"]
518
+ _keep_in_fp32_modules = ["wo"]
519
+
520
+ @property
521
+ def dummy_inputs(self):
522
+ input_ids = torch.tensor(DUMMY_INPUTS)
523
+ input_mask = torch.tensor(DUMMY_MASK)
524
+ dummy_inputs = {
525
+ "decoder_input_ids": input_ids,
526
+ "input_ids": input_ids,
527
+ "decoder_attention_mask": input_mask,
528
+ }
529
+ return dummy_inputs
530
+
531
+ def _init_weights(self, module):
532
+ """Initialize the weights"""
533
+ factor = self.config.initializer_factor # Used for testing weights initialization
534
+ if isinstance(module, UMT5LayerNorm):
535
+ module.weight.data.fill_(factor * 1.0)
536
+ elif isinstance(
537
+ module,
538
+ (
539
+ UMT5Model,
540
+ UMT5ForConditionalGeneration,
541
+ UMT5EncoderModel,
542
+ UMT5ForQuestionAnswering,
543
+ ),
544
+ ):
545
+ # Mesh TensorFlow embeddings initialization
546
+ # See https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/layers.py#L1624
547
+ module.shared.weight.data.normal_(mean=0.0, std=factor * 1.0)
548
+ if hasattr(module, "lm_head") and not self.config.tie_word_embeddings:
549
+ module.lm_head.weight.data.normal_(mean=0.0, std=factor * 1.0)
550
+ if hasattr(module, "qa_outputs"):
551
+ module.qa_outputs.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
552
+ module.qa_outputs.bias.data.zero_()
553
+ elif isinstance(module, UMT5ForTokenClassification):
554
+ if hasattr(module, "classifier"):
555
+ module.classifier.weight.data.normal_(mean=0.0, std=factor * 1.0)
556
+ module.classifier.bias.data.zero_()
557
+ elif isinstance(module, UMT5ClassificationHead):
558
+ module.dense.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
559
+ if hasattr(module.dense, "bias") and module.dense.bias is not None:
560
+ module.dense.bias.data.zero_()
561
+ module.out_proj.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
562
+ if hasattr(module.out_proj, "bias") and module.out_proj.bias is not None:
563
+ module.out_proj.bias.data.zero_()
564
+ elif isinstance(module, UMT5DenseActDense):
565
+ # Mesh TensorFlow FF initialization
566
+ # See https://github.com/tensorflow/mesh/blob/master/mesh_tensorflow/transformer/transformer_layers.py#L56
567
+ # and https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/layers.py#L89
568
+ module.wi.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
569
+ if hasattr(module.wi, "bias") and module.wi.bias is not None:
570
+ module.wi.bias.data.zero_()
571
+ module.wo.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_ff) ** -0.5))
572
+ if hasattr(module.wo, "bias") and module.wo.bias is not None:
573
+ module.wo.bias.data.zero_()
574
+ elif isinstance(module, UMT5DenseGatedActDense):
575
+ module.wi_0.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
576
+ if hasattr(module.wi_0, "bias") and module.wi_0.bias is not None:
577
+ module.wi_0.bias.data.zero_()
578
+ module.wi_1.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
579
+ if hasattr(module.wi_1, "bias") and module.wi_1.bias is not None:
580
+ module.wi_1.bias.data.zero_()
581
+ module.wo.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_ff) ** -0.5))
582
+ if hasattr(module.wo, "bias") and module.wo.bias is not None:
583
+ module.wo.bias.data.zero_()
584
+ elif isinstance(module, UMT5Attention):
585
+ # Mesh TensorFlow attention initialization to avoid scaling before softmax
586
+ # See https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/transformer/attention.py#L136
587
+ d_model = self.config.d_model
588
+ key_value_proj_dim = self.config.d_kv
589
+ n_heads = self.config.num_heads
590
+ module.q.weight.data.normal_(mean=0.0, std=factor * ((d_model * key_value_proj_dim) ** -0.5))
591
+ module.k.weight.data.normal_(mean=0.0, std=factor * (d_model**-0.5))
592
+ module.v.weight.data.normal_(mean=0.0, std=factor * (d_model**-0.5))
593
+ module.o.weight.data.normal_(mean=0.0, std=factor * ((n_heads * key_value_proj_dim) ** -0.5))
594
+ if module.has_relative_attention_bias:
595
+ module.relative_attention_bias.weight.data.normal_(mean=0.0, std=factor * ((d_model) ** -0.5))
596
+
597
+ def _shift_right(self, input_ids):
598
+ decoder_start_token_id = self.config.decoder_start_token_id
599
+ pad_token_id = self.config.pad_token_id
600
+
601
+ if decoder_start_token_id is None:
602
+ raise ValueError(
603
+ "self.model.config.decoder_start_token_id has to be defined. In UMT5 it is usually set to the pad_token_id. "
604
+ "See UMT5 docs for more information."
605
+ )
606
+
607
+ # shift inputs to the right
608
+ if is_torch_fx_proxy(input_ids):
609
+ # Item assignment is not supported natively for proxies.
610
+ shifted_input_ids = torch.full(input_ids.shape[:-1] + (1,), decoder_start_token_id)
611
+ shifted_input_ids = torch.cat([shifted_input_ids, input_ids[..., :-1]], dim=-1)
612
+ else:
613
+ shifted_input_ids = input_ids.new_zeros(input_ids.shape)
614
+ shifted_input_ids[..., 1:] = input_ids[..., :-1].clone()
615
+ shifted_input_ids[..., 0] = decoder_start_token_id
616
+
617
+ if pad_token_id is None:
618
+ raise ValueError("self.model.config.pad_token_id has to be defined.")
619
+ # replace possible -100 values in labels by `pad_token_id`
620
+ shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
621
+
622
+ return shifted_input_ids
623
+
624
+
625
+ class UMT5Stack(UMT5PreTrainedModel):
626
+ def __init__(self, config, embed_tokens=None):
627
+ super().__init__(config)
628
+ self.embed_tokens = embed_tokens
629
+ self.is_decoder = config.is_decoder
630
+ self.block = nn.ModuleList([UMT5Block(config, layer_idx=i) for i in range(config.num_layers)])
631
+ self.final_layer_norm = UMT5LayerNorm(config.d_model, eps=config.layer_norm_epsilon)
632
+ self.dropout = nn.Dropout(config.dropout_rate)
633
+
634
+ # Initialize weights and apply final processing
635
+ self.gradient_checkpointing = False
636
+ self.post_init()
637
+
638
+ def set_input_embeddings(self, new_embeddings):
639
+ self.embed_tokens = new_embeddings
640
+
641
+ def forward(
642
+ self,
643
+ input_ids=None,
644
+ attention_mask=None,
645
+ encoder_hidden_states=None,
646
+ encoder_attention_mask=None,
647
+ inputs_embeds=None,
648
+ head_mask=None,
649
+ cross_attn_head_mask=None,
650
+ past_key_values=None,
651
+ use_cache=None,
652
+ output_attentions=None,
653
+ output_hidden_states=None,
654
+ return_dict=None,
655
+ cache_position=None,
656
+ ):
657
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
658
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
659
+ output_hidden_states = (
660
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
661
+ )
662
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
663
+
664
+ if input_ids is not None and inputs_embeds is not None:
665
+ err_msg_prefix = "decoder_" if self.is_decoder else ""
666
+ raise ValueError(
667
+ f"You cannot specify both {err_msg_prefix}input_ids and {err_msg_prefix}inputs_embeds at the same time"
668
+ )
669
+ elif input_ids is not None:
670
+ input_shape = input_ids.size()
671
+ input_ids = input_ids.view(-1, input_shape[-1])
672
+ elif inputs_embeds is not None:
673
+ input_shape = inputs_embeds.size()[:-1]
674
+ else:
675
+ err_msg_prefix = "decoder_" if self.is_decoder else ""
676
+ raise ValueError(f"You have to specify either {err_msg_prefix}input_ids or {err_msg_prefix}inputs_embeds")
677
+
678
+ if self.gradient_checkpointing and self.training:
679
+ if use_cache:
680
+ logger.warning_once(
681
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
682
+ )
683
+ use_cache = False
684
+
685
+ if inputs_embeds is None:
686
+ if self.embed_tokens is None:
687
+ raise ValueError("You have to initialize the model with valid token embeddings")
688
+ inputs_embeds = self.embed_tokens(input_ids)
689
+
690
+ batch_size, seq_length = input_shape
691
+
692
+ if use_cache is True:
693
+ if not self.is_decoder:
694
+ raise ValueError(f"`use_cache` can only be set to `True` if {self} is used as a decoder")
695
+
696
+ # initialize past_key_values
697
+ if self.is_decoder:
698
+ if use_cache and past_key_values is None:
699
+ if self.config.is_encoder_decoder:
700
+ past_key_values = EncoderDecoderCache(DynamicCache(), DynamicCache())
701
+ else:
702
+ past_key_values = DynamicCache()
703
+ elif not self.is_decoder:
704
+ # do not pass cache object down the line for encoder stack
705
+ # it messes indexing later in decoder-stack because cache object is modified in-place
706
+ past_key_values = None
707
+
708
+ past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
709
+ if cache_position is None:
710
+ cache_position = torch.arange(
711
+ past_key_values_length, past_key_values_length + seq_length, device=inputs_embeds.device
712
+ )
713
+
714
+ if attention_mask is None and not is_torchdynamo_compiling():
715
+ # required mask seq length can be calculated via length of past cache
716
+ mask_seq_length = past_key_values_length + seq_length
717
+ attention_mask = torch.ones(batch_size, mask_seq_length, device=inputs_embeds.device)
718
+
719
+ if self.is_decoder:
720
+ causal_mask = self._update_causal_mask(
721
+ attention_mask,
722
+ inputs_embeds,
723
+ cache_position,
724
+ past_key_values.self_attention_cache
725
+ if isinstance(past_key_values, EncoderDecoderCache)
726
+ else past_key_values,
727
+ output_attentions,
728
+ )
729
+ elif attention_mask is not None:
730
+ causal_mask = attention_mask[:, None, None, :]
731
+ causal_mask = causal_mask.to(dtype=inputs_embeds.dtype)
732
+ causal_mask = (1.0 - causal_mask) * torch.finfo(inputs_embeds.dtype).min
733
+ else:
734
+ causal_mask = None
735
+
736
+ # If a 2D or 3D attention mask is provided for the cross-attention
737
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
738
+ if self.is_decoder and encoder_hidden_states is not None:
739
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
740
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
741
+ if encoder_attention_mask is None:
742
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=inputs_embeds.device)
743
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
744
+ else:
745
+ encoder_extended_attention_mask = None
746
+
747
+ # Prepare head mask if needed
748
+ head_mask = self.get_head_mask(head_mask, self.config.num_layers)
749
+ cross_attn_head_mask = self.get_head_mask(cross_attn_head_mask, self.config.num_layers)
750
+ all_hidden_states = () if output_hidden_states else None
751
+ all_attentions = () if output_attentions else None
752
+ all_cross_attentions = () if output_attentions and self.is_decoder else None
753
+
754
+ hidden_states = self.dropout(inputs_embeds)
755
+
756
+ for i, layer_module in enumerate(self.block):
757
+ layer_head_mask = head_mask[i]
758
+ cross_attn_layer_head_mask = cross_attn_head_mask[i]
759
+
760
+ if output_hidden_states:
761
+ all_hidden_states = all_hidden_states + (hidden_states,)
762
+
763
+ layer_outputs = layer_module(
764
+ hidden_states,
765
+ causal_mask,
766
+ encoder_hidden_states, # as a positional argument for gradient checkpointing
767
+ encoder_attention_mask=encoder_extended_attention_mask,
768
+ layer_head_mask=layer_head_mask,
769
+ cross_attn_layer_head_mask=cross_attn_layer_head_mask,
770
+ past_key_values=past_key_values,
771
+ use_cache=use_cache,
772
+ output_attentions=output_attentions,
773
+ cache_position=cache_position,
774
+ )
775
+
776
+ hidden_states = layer_outputs[0]
777
+
778
+ if output_attentions:
779
+ all_attentions += (layer_outputs[1],)
780
+ if self.is_decoder:
781
+ all_cross_attentions += (layer_outputs[2],)
782
+
783
+ hidden_states = self.final_layer_norm(hidden_states)
784
+ hidden_states = self.dropout(hidden_states)
785
+
786
+ # Add last layer
787
+ if output_hidden_states:
788
+ all_hidden_states = all_hidden_states + (hidden_states,)
789
+
790
+ if not return_dict:
791
+ return tuple(
792
+ v
793
+ for v in [
794
+ hidden_states,
795
+ past_key_values,
796
+ all_hidden_states,
797
+ all_attentions,
798
+ all_cross_attentions,
799
+ ]
800
+ if v is not None
801
+ )
802
+ return BaseModelOutputWithPastAndCrossAttentions(
803
+ last_hidden_state=hidden_states,
804
+ past_key_values=past_key_values,
805
+ hidden_states=all_hidden_states,
806
+ attentions=all_attentions,
807
+ cross_attentions=all_cross_attentions,
808
+ )
809
+
810
+ # Copied from transformers.models.gptj.modeling_gptj.GPTJModel._update_causal_mask
811
+ def _update_causal_mask(
812
+ self,
813
+ attention_mask: Union[torch.Tensor, "BlockMask"],
814
+ input_tensor: torch.Tensor,
815
+ cache_position: torch.Tensor,
816
+ past_key_values: Cache,
817
+ output_attentions: bool = False,
818
+ ):
819
+ if self.config._attn_implementation == "flash_attention_2":
820
+ if attention_mask is not None and (attention_mask == 0.0).any():
821
+ return attention_mask
822
+ return None
823
+ if self.config._attn_implementation == "flex_attention":
824
+ if isinstance(attention_mask, torch.Tensor):
825
+ attention_mask = make_flex_block_causal_mask(attention_mask)
826
+ return attention_mask
827
+
828
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
829
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
830
+ # to infer the attention mask.
831
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
832
+ using_compilable_cache = past_key_values.is_compileable if past_key_values is not None else False
833
+
834
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
835
+ if self.config._attn_implementation == "sdpa" and not using_compilable_cache and not output_attentions:
836
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
837
+ attention_mask,
838
+ inputs_embeds=input_tensor,
839
+ past_key_values_length=past_seen_tokens,
840
+ is_training=self.training,
841
+ ):
842
+ return None
843
+
844
+ dtype = input_tensor.dtype
845
+ sequence_length = input_tensor.shape[1]
846
+ if using_compilable_cache:
847
+ target_length = past_key_values.get_max_cache_shape()
848
+ else:
849
+ target_length = (
850
+ attention_mask.shape[-1]
851
+ if isinstance(attention_mask, torch.Tensor)
852
+ else past_seen_tokens + sequence_length + 1
853
+ )
854
+
855
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
856
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
857
+ attention_mask,
858
+ sequence_length=sequence_length,
859
+ target_length=target_length,
860
+ dtype=dtype,
861
+ cache_position=cache_position,
862
+ batch_size=input_tensor.shape[0],
863
+ )
864
+
865
+ if (
866
+ self.config._attn_implementation == "sdpa"
867
+ and attention_mask is not None
868
+ and attention_mask.device.type in ["cuda", "xpu", "npu"]
869
+ and not output_attentions
870
+ ):
871
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
872
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
873
+ # Details: https://github.com/pytorch/pytorch/issues/110213
874
+ min_dtype = torch.finfo(dtype).min
875
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
876
+
877
+ return causal_mask
878
+
879
+ @staticmethod
880
+ # Copied from transformers.models.gptj.modeling_gptj.GPTJModel._prepare_4d_causal_attention_mask_with_cache_position
881
+ def _prepare_4d_causal_attention_mask_with_cache_position(
882
+ attention_mask: torch.Tensor,
883
+ sequence_length: int,
884
+ target_length: int,
885
+ dtype: torch.dtype,
886
+ cache_position: torch.Tensor,
887
+ batch_size: int,
888
+ **kwargs,
889
+ ):
890
+ """
891
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
892
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
893
+
894
+ Args:
895
+ attention_mask (`torch.Tensor`):
896
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
897
+ `(batch_size, 1, query_length, key_value_length)`.
898
+ sequence_length (`int`):
899
+ The sequence length being processed.
900
+ target_length (`int`):
901
+ The target length: when generating with static cache, the mask should be as long as the static cache,
902
+ to account for the 0 padding, the part of the cache that is not filled yet.
903
+ dtype (`torch.dtype`):
904
+ The dtype to use for the 4D attention mask.
905
+ cache_position (`torch.Tensor`):
906
+ Indices depicting the position of the input sequence tokens in the sequence.
907
+ batch_size (`torch.Tensor`):
908
+ Batch size.
909
+ """
910
+ if attention_mask is not None and attention_mask.dim() == 4:
911
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
912
+ causal_mask = attention_mask
913
+ else:
914
+ min_dtype = torch.finfo(dtype).min
915
+ causal_mask = torch.full(
916
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=cache_position.device
917
+ )
918
+ if sequence_length != 1:
919
+ causal_mask = torch.triu(causal_mask, diagonal=1)
920
+ causal_mask *= torch.arange(target_length, device=cache_position.device) > cache_position.reshape(-1, 1)
921
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
922
+ if attention_mask is not None:
923
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
924
+ mask_length = attention_mask.shape[-1]
925
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
926
+ causal_mask.device
927
+ )
928
+ padding_mask = padding_mask == 0
929
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
930
+ padding_mask, min_dtype
931
+ )
932
+
933
+ return causal_mask
934
+
935
+
936
+ @auto_docstring
937
+ class UMT5Model(UMT5PreTrainedModel):
938
+ r"""
939
+ Examples:
940
+
941
+ ```python
942
+ >>> from transformers import UMT5Model, AutoTokenizer
943
+
944
+ >>> model = UMT5Model.from_pretrained("google/umt5-small")
945
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/umt5-small")
946
+ >>> noisy_text = "UN Offizier sagt, dass weiter <extra_id_0> werden muss in Syrien."
947
+ >>> label = "<extra_id_0> verhandelt"
948
+ >>> inputs = tokenizer(inputs, return_tensors="pt")
949
+ >>> labels = tokenizer(label=label, return_tensors="pt")
950
+
951
+ >>> outputs = model(input_ids=inputs["input_ids"], decoder_input_ids=labels["input_ids"])
952
+ >>> hidden_states = outputs.last_hidden_state
953
+ ```"""
954
+
955
+ model_type = "umt5"
956
+ config: UMT5Config
957
+ _tied_weights_keys = ["encoder.embed_tokens.weight", "decoder.embed_tokens.weight"]
958
+
959
+ def __init__(self, config):
960
+ super().__init__(config)
961
+ self.shared = nn.Embedding(config.vocab_size, config.d_model)
962
+
963
+ encoder_config = copy.deepcopy(config)
964
+ encoder_config.is_decoder = False
965
+ encoder_config.use_cache = False
966
+ encoder_config.tie_encoder_decoder = False
967
+ self.encoder = UMT5Stack(encoder_config, self.shared)
968
+
969
+ decoder_config = copy.deepcopy(config)
970
+ decoder_config.is_decoder = True
971
+ decoder_config.tie_encoder_decoder = False
972
+ decoder_config.num_layers = config.num_decoder_layers
973
+ self.decoder = UMT5Stack(decoder_config, self.shared)
974
+
975
+ # Initialize weights and apply final processing
976
+ self.post_init()
977
+
978
+ # Copied from transformers.models.t5.modeling_t5.T5Model.get_input_embeddings
979
+ def get_input_embeddings(self):
980
+ return self.shared
981
+
982
+ # Copied from transformers.models.t5.modeling_t5.T5Model.set_input_embeddings
983
+ def set_input_embeddings(self, new_embeddings):
984
+ self.shared = new_embeddings
985
+ self.encoder.set_input_embeddings(new_embeddings)
986
+ self.decoder.set_input_embeddings(new_embeddings)
987
+
988
+ # Copied from transformers.models.t5.modeling_t5.T5Model._tie_weights
989
+ def _tie_weights(self):
990
+ if self.config.tie_word_embeddings:
991
+ self._tie_or_clone_weights(self.encoder.embed_tokens, self.shared)
992
+ self._tie_or_clone_weights(self.decoder.embed_tokens, self.shared)
993
+
994
+ # Copied from transformers.models.t5.modeling_t5.T5Model.get_encoder
995
+ def get_encoder(self):
996
+ return self.encoder
997
+
998
+ # Copied from transformers.models.t5.modeling_t5.T5Model.get_decoder
999
+ def get_decoder(self):
1000
+ return self.decoder
1001
+
1002
+ # Copied from transformers.models.t5.modeling_t5.T5Model._prune_heads
1003
+ def _prune_heads(self, heads_to_prune):
1004
+ """
1005
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
1006
+ class PreTrainedModel
1007
+ """
1008
+ for layer, heads in heads_to_prune.items():
1009
+ self.encoder.layer[layer].attention.prune_heads(heads)
1010
+
1011
+ @auto_docstring
1012
+ def forward(
1013
+ self,
1014
+ input_ids: Optional[torch.LongTensor] = None,
1015
+ attention_mask: Optional[torch.FloatTensor] = None,
1016
+ decoder_input_ids: Optional[torch.LongTensor] = None,
1017
+ decoder_attention_mask: Optional[torch.BoolTensor] = None,
1018
+ head_mask: Optional[torch.FloatTensor] = None,
1019
+ decoder_head_mask: Optional[torch.FloatTensor] = None,
1020
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1021
+ encoder_outputs: Optional[tuple[tuple[torch.FloatTensor]]] = None,
1022
+ past_key_values: Optional[Cache] = None,
1023
+ inputs_embeds: Optional[torch.Tensor] = None,
1024
+ decoder_inputs_embeds: Optional[torch.Tensor] = None,
1025
+ use_cache: Optional[bool] = None,
1026
+ output_attentions: Optional[bool] = None,
1027
+ output_hidden_states: Optional[bool] = None,
1028
+ return_dict: Optional[bool] = None,
1029
+ cache_position: Optional[torch.LongTensor] = None,
1030
+ ) -> Union[tuple[torch.FloatTensor], Seq2SeqModelOutput]:
1031
+ r"""
1032
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1033
+ Indices of input sequence tokens in the vocabulary. UMT5 is a model with relative position embeddings so
1034
+ you should be able to pad the inputs on both the right and the left.
1035
+
1036
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1037
+ [`PreTrainedTokenizer.__call__`] for detail.
1038
+
1039
+ [What are input IDs?](../glossary#input-ids)
1040
+
1041
+ To know more on how to prepare `input_ids` for pretraining take a look a [UMT5 Training](./umt5#training).
1042
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
1043
+ Indices of decoder input sequence tokens in the vocabulary.
1044
+
1045
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1046
+ [`PreTrainedTokenizer.__call__`] for details.
1047
+
1048
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
1049
+
1050
+ UMT5 uses the `pad_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
1051
+ is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
1052
+
1053
+ To know more on how to prepare `decoder_input_ids` for pretraining take a look at [UMT5
1054
+ Training](./umt5#training).
1055
+ decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
1056
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
1057
+ be used by default.
1058
+ decoder_head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
1059
+ Mask to nullify selected heads of the self-attention modules in the decoder. Mask values selected in `[0,
1060
+ 1]`:
1061
+
1062
+ - 1 indicates the head is **not masked**,
1063
+ - 0 indicates the head is **masked**.
1064
+ cross_attn_head_mask (`torch.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
1065
+ Mask to nullify selected heads of the cross-attention modules in the decoder. Mask values selected in
1066
+ `[0, 1]`:
1067
+
1068
+ - 1 indicates the head is **not masked**,
1069
+ - 0 indicates the head is **masked**.
1070
+
1071
+ Example:
1072
+
1073
+ ```python
1074
+ >>> from transformers import AutoTokenizer, UMT5Model
1075
+
1076
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/umt5-small")
1077
+ >>> model = UMT5Model.from_pretrained("google/umt5-small")
1078
+
1079
+ >>> input_ids = tokenizer(
1080
+ ... "Studies have been shown that owning a dog is good for you", return_tensors="pt"
1081
+ ... ).input_ids # Batch size 1
1082
+ >>> decoder_input_ids = tokenizer("Studies show that", return_tensors="pt").input_ids # Batch size 1
1083
+
1084
+ >>> # preprocess: Prepend decoder_input_ids with start token which is pad token for UMT5Model.
1085
+ >>> # This is not needed for torch's UMT5ForConditionalGeneration as it does this internally using labels arg.
1086
+ >>> decoder_input_ids = model._shift_right(decoder_input_ids)
1087
+
1088
+ >>> # forward pass
1089
+ >>> outputs = model(input_ids=input_ids, decoder_input_ids=decoder_input_ids)
1090
+ >>> last_hidden_states = outputs.last_hidden_state
1091
+ ```"""
1092
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1093
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1094
+
1095
+ # Encode if needed (training, first prediction pass)
1096
+ if encoder_outputs is None:
1097
+ encoder_outputs = self.encoder(
1098
+ input_ids=input_ids,
1099
+ attention_mask=attention_mask,
1100
+ inputs_embeds=inputs_embeds,
1101
+ head_mask=head_mask,
1102
+ output_attentions=output_attentions,
1103
+ output_hidden_states=output_hidden_states,
1104
+ return_dict=return_dict,
1105
+ )
1106
+ elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
1107
+ encoder_outputs = BaseModelOutput(
1108
+ last_hidden_state=encoder_outputs[0],
1109
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
1110
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
1111
+ )
1112
+
1113
+ hidden_states = encoder_outputs[0]
1114
+
1115
+ # Decode
1116
+ decoder_outputs = self.decoder(
1117
+ input_ids=decoder_input_ids,
1118
+ attention_mask=decoder_attention_mask,
1119
+ inputs_embeds=decoder_inputs_embeds,
1120
+ past_key_values=past_key_values,
1121
+ encoder_hidden_states=hidden_states,
1122
+ encoder_attention_mask=attention_mask,
1123
+ head_mask=decoder_head_mask,
1124
+ cross_attn_head_mask=cross_attn_head_mask,
1125
+ use_cache=use_cache,
1126
+ output_attentions=output_attentions,
1127
+ output_hidden_states=output_hidden_states,
1128
+ return_dict=return_dict,
1129
+ cache_position=cache_position,
1130
+ )
1131
+
1132
+ if not return_dict:
1133
+ return decoder_outputs + encoder_outputs
1134
+
1135
+ return Seq2SeqModelOutput(
1136
+ last_hidden_state=decoder_outputs.last_hidden_state,
1137
+ past_key_values=decoder_outputs.past_key_values,
1138
+ decoder_hidden_states=decoder_outputs.hidden_states,
1139
+ decoder_attentions=decoder_outputs.attentions,
1140
+ cross_attentions=decoder_outputs.cross_attentions,
1141
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
1142
+ encoder_hidden_states=encoder_outputs.hidden_states,
1143
+ encoder_attentions=encoder_outputs.attentions,
1144
+ )
1145
+
1146
+
1147
+ @auto_docstring(
1148
+ custom_intro="""
1149
+ UMT5 Model with a `language modeling` head on top.
1150
+ """
1151
+ )
1152
+ class UMT5ForConditionalGeneration(UMT5PreTrainedModel, GenerationMixin):
1153
+ r"""
1154
+ Examples:
1155
+
1156
+ ```python
1157
+ >>> from transformers import UMT5ForConditionalGeneration, AutoTokenizer
1158
+
1159
+ >>> model = UMT5ForConditionalGeneration.from_pretrained("google/umt5-small")
1160
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/umt5-small")
1161
+ >>> article = "UN Offizier sagt, dass weiter verhandelt werden muss in Syrien."
1162
+ >>> summary = "Weiter Verhandlung in Syrien."
1163
+ >>> inputs = tokenizer(article, text_target=summary, return_tensors="pt")
1164
+
1165
+ >>> outputs = model(**inputs)
1166
+ >>> loss = outputs.loss
1167
+ ```"""
1168
+
1169
+ model_type = "umt5"
1170
+ _tied_weights_keys = ["encoder.embed_tokens.weight", "decoder.embed_tokens.weight", "lm_head.weight"]
1171
+
1172
+ def __init__(self, config):
1173
+ super().__init__(config)
1174
+ self.model_dim = config.d_model
1175
+
1176
+ self.shared = nn.Embedding(config.vocab_size, config.d_model)
1177
+
1178
+ encoder_config = copy.deepcopy(config)
1179
+ encoder_config.is_decoder = False
1180
+ encoder_config.use_cache = False
1181
+ encoder_config.tie_encoder_decoder = False
1182
+ self.encoder = UMT5Stack(encoder_config, self.shared)
1183
+
1184
+ decoder_config = copy.deepcopy(config)
1185
+ decoder_config.is_decoder = True
1186
+ decoder_config.tie_encoder_decoder = False
1187
+ decoder_config.num_layers = config.num_decoder_layers
1188
+ self.decoder = UMT5Stack(decoder_config, self.shared)
1189
+
1190
+ self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)
1191
+
1192
+ # Initialize weights and apply final processing
1193
+ self.post_init()
1194
+
1195
+ # Copied from transformers.models.t5.modeling_t5.T5ForConditionalGeneration.get_input_embeddings
1196
+ def get_input_embeddings(self):
1197
+ return self.shared
1198
+
1199
+ # Copied from transformers.models.t5.modeling_t5.T5ForConditionalGeneration.set_input_embeddings
1200
+ def set_input_embeddings(self, new_embeddings):
1201
+ self.shared = new_embeddings
1202
+ self.encoder.set_input_embeddings(new_embeddings)
1203
+ self.decoder.set_input_embeddings(new_embeddings)
1204
+
1205
+ # Copied from transformers.models.t5.modeling_t5.T5ForConditionalGeneration._tie_weights
1206
+ def _tie_weights(self):
1207
+ if self.config.tie_word_embeddings:
1208
+ self._tie_or_clone_weights(self.encoder.embed_tokens, self.shared)
1209
+ self._tie_or_clone_weights(self.decoder.embed_tokens, self.shared)
1210
+
1211
+ # Copied from transformers.models.t5.modeling_t5.T5ForConditionalGeneration.get_encoder
1212
+ def get_encoder(self):
1213
+ return self.encoder
1214
+
1215
+ # Copied from transformers.models.t5.modeling_t5.T5ForConditionalGeneration.get_decoder
1216
+ def get_decoder(self):
1217
+ return self.decoder
1218
+
1219
+ @auto_docstring
1220
+ def forward(
1221
+ self,
1222
+ input_ids: Optional[torch.LongTensor] = None,
1223
+ attention_mask: Optional[torch.FloatTensor] = None,
1224
+ decoder_input_ids: Optional[torch.LongTensor] = None,
1225
+ decoder_attention_mask: Optional[torch.BoolTensor] = None,
1226
+ head_mask: Optional[torch.FloatTensor] = None,
1227
+ decoder_head_mask: Optional[torch.FloatTensor] = None,
1228
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1229
+ encoder_outputs: Optional[tuple[tuple[torch.Tensor]]] = None,
1230
+ past_key_values: Optional[Cache] = None,
1231
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1232
+ decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
1233
+ labels: Optional[torch.LongTensor] = None,
1234
+ use_cache: Optional[bool] = None,
1235
+ output_attentions: Optional[bool] = None,
1236
+ output_hidden_states: Optional[bool] = None,
1237
+ return_dict: Optional[bool] = None,
1238
+ cache_position: Optional[torch.LongTensor] = None,
1239
+ ) -> Union[tuple[torch.FloatTensor], Seq2SeqLMOutput]:
1240
+ r"""
1241
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1242
+ Indices of input sequence tokens in the vocabulary. UMT5 is a model with relative position embeddings so
1243
+ you should be able to pad the inputs on both the right and the left.
1244
+
1245
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1246
+ [`PreTrainedTokenizer.__call__`] for detail.
1247
+
1248
+ [What are input IDs?](../glossary#input-ids)
1249
+
1250
+ To know more on how to prepare `input_ids` for pretraining take a look a [UMT5 Training](./umt5#training).
1251
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
1252
+ Indices of decoder input sequence tokens in the vocabulary.
1253
+
1254
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1255
+ [`PreTrainedTokenizer.__call__`] for details.
1256
+
1257
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
1258
+
1259
+ UMT5 uses the `pad_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
1260
+ is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
1261
+
1262
+ To know more on how to prepare `decoder_input_ids` for pretraining take a look at [UMT5
1263
+ Training](./umt5#training).
1264
+ decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
1265
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
1266
+ be used by default.
1267
+ decoder_head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
1268
+ Mask to nullify selected heads of the self-attention modules in the decoder. Mask values selected in `[0,
1269
+ 1]`:
1270
+
1271
+ - 1 indicates the head is **not masked**,
1272
+ - 0 indicates the head is **masked**.
1273
+ cross_attn_head_mask (`torch.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
1274
+ Mask to nullify selected heads of the cross-attention modules in the decoder. Mask values selected in
1275
+ `[0, 1]`:
1276
+
1277
+ - 1 indicates the head is **not masked**,
1278
+ - 0 indicates the head is **masked**.
1279
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1280
+ Labels for computing the sequence classification/regression loss. Indices should be in `[-100, 0, ...,
1281
+ config.vocab_size - 1]`. All labels set to `-100` are ignored (masked), the loss is only computed for
1282
+ labels in `[0, ..., config.vocab_size]`
1283
+
1284
+ Examples:
1285
+
1286
+ ```python
1287
+ >>> from transformers import AutoTokenizer, UMT5ForConditionalGeneration
1288
+
1289
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/umt5-small")
1290
+ >>> model = UMT5ForConditionalGeneration.from_pretrained("google/umt5-small")
1291
+
1292
+ >>> # training
1293
+ >>> input_ids = tokenizer("The <extra_id_0> walks in <extra_id_1> park", return_tensors="pt").input_ids
1294
+ >>> labels = tokenizer("<extra_id_0> cute dog <extra_id_1> the <extra_id_2>", return_tensors="pt").input_ids
1295
+ >>> outputs = model(input_ids=input_ids, labels=labels)
1296
+ >>> loss = outputs.loss
1297
+ >>> logits = outputs.logits
1298
+
1299
+ >>> # inference
1300
+ >>> input_ids = tokenizer("Studies have shown that <extra_id_0> good for you", return_tensors="pt").input_ids
1301
+ >>> outputs = model.generate(input_ids)
1302
+ >>> tokenizer.decode(outputs[0], skip_special_tokens=True)
1303
+ ```"""
1304
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1305
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1306
+
1307
+ # Encode if needed (training, first prediction pass)
1308
+ if encoder_outputs is None:
1309
+ # Convert encoder inputs in embeddings if needed
1310
+ encoder_outputs = self.encoder(
1311
+ input_ids=input_ids,
1312
+ attention_mask=attention_mask,
1313
+ inputs_embeds=inputs_embeds,
1314
+ head_mask=head_mask,
1315
+ output_attentions=output_attentions,
1316
+ output_hidden_states=output_hidden_states,
1317
+ return_dict=return_dict,
1318
+ )
1319
+ elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
1320
+ encoder_outputs = BaseModelOutput(
1321
+ last_hidden_state=encoder_outputs[0],
1322
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
1323
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
1324
+ )
1325
+
1326
+ hidden_states = encoder_outputs[0]
1327
+
1328
+ if labels is not None and decoder_input_ids is None and decoder_inputs_embeds is None:
1329
+ # get decoder inputs from shifting lm labels to the right
1330
+ decoder_input_ids = self._shift_right(labels)
1331
+
1332
+ # Decode
1333
+ decoder_outputs = self.decoder(
1334
+ input_ids=decoder_input_ids,
1335
+ attention_mask=decoder_attention_mask,
1336
+ inputs_embeds=decoder_inputs_embeds,
1337
+ past_key_values=past_key_values,
1338
+ encoder_hidden_states=hidden_states,
1339
+ encoder_attention_mask=attention_mask,
1340
+ head_mask=decoder_head_mask,
1341
+ cross_attn_head_mask=cross_attn_head_mask,
1342
+ use_cache=use_cache,
1343
+ output_attentions=output_attentions,
1344
+ output_hidden_states=output_hidden_states,
1345
+ return_dict=return_dict,
1346
+ cache_position=cache_position,
1347
+ )
1348
+
1349
+ sequence_output = decoder_outputs[0]
1350
+
1351
+ if self.config.tie_word_embeddings:
1352
+ # Rescale output before projecting on vocab
1353
+ # See https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/transformer/transformer.py#L586
1354
+ sequence_output = sequence_output * (self.model_dim**-0.5)
1355
+
1356
+ lm_logits = self.lm_head(sequence_output)
1357
+
1358
+ loss = None
1359
+ if labels is not None:
1360
+ loss_fct = CrossEntropyLoss(ignore_index=-100)
1361
+ # move labels to correct device to enable PP
1362
+ labels = labels.to(lm_logits.device)
1363
+ loss = loss_fct(lm_logits.view(-1, lm_logits.size(-1)), labels.view(-1))
1364
+
1365
+ if not return_dict:
1366
+ output = (lm_logits,) + decoder_outputs[1:] + encoder_outputs
1367
+ return ((loss,) + output) if loss is not None else output
1368
+
1369
+ return Seq2SeqLMOutput(
1370
+ loss=loss,
1371
+ logits=lm_logits,
1372
+ past_key_values=decoder_outputs.past_key_values,
1373
+ decoder_hidden_states=decoder_outputs.hidden_states,
1374
+ decoder_attentions=decoder_outputs.attentions,
1375
+ cross_attentions=decoder_outputs.cross_attentions,
1376
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
1377
+ encoder_hidden_states=encoder_outputs.hidden_states,
1378
+ encoder_attentions=encoder_outputs.attentions,
1379
+ )
1380
+
1381
+ # Copied from transformers.models.t5.modeling_t5.T5ForConditionalGeneration.prepare_decoder_input_ids_from_labels
1382
+ def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor):
1383
+ return self._shift_right(labels)
1384
+
1385
+
1386
+ @auto_docstring
1387
+ class UMT5EncoderModel(UMT5PreTrainedModel):
1388
+ r"""
1389
+ Examples:
1390
+
1391
+ ```python
1392
+ >>> from transformers import UMT5EncoderModel, AutoTokenizer
1393
+
1394
+ >>> model = UMT5EncoderModel.from_pretrained("google/umt5-small")
1395
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/umt5-small")
1396
+ >>> article = "UN Offizier sagt, dass weiter verhandelt werden muss in Syrien."
1397
+ >>> input_ids = tokenizer(article, return_tensors="pt").input_ids
1398
+ >>> outputs = model(input_ids)
1399
+ >>> hidden_state = outputs.last_hidden_state
1400
+ ```"""
1401
+
1402
+ model_type = "umt5"
1403
+ # config_class = UMT5Config
1404
+ _tied_weights_keys = ["encoder.embed_tokens.weight"]
1405
+
1406
+ def __init__(self, config):
1407
+ super().__init__(config)
1408
+ self.shared = nn.Embedding(config.vocab_size, config.d_model)
1409
+
1410
+ encoder_config = copy.deepcopy(config)
1411
+ encoder_config.use_cache = False
1412
+ encoder_config.is_encoder_decoder = False
1413
+ self.encoder = UMT5Stack(encoder_config, self.shared)
1414
+
1415
+ # Initialize weights and apply final processing
1416
+ self.post_init()
1417
+
1418
+ # Copied from transformers.models.t5.modeling_t5.T5EncoderModel.get_input_embeddings
1419
+ def get_input_embeddings(self):
1420
+ return self.shared
1421
+
1422
+ # Copied from transformers.models.t5.modeling_t5.T5EncoderModel.set_input_embeddings
1423
+ def set_input_embeddings(self, new_embeddings):
1424
+ self.shared = new_embeddings
1425
+ self.encoder.set_input_embeddings(new_embeddings)
1426
+
1427
+ # Copied from transformers.models.t5.modeling_t5.T5EncoderModel._tie_weights
1428
+ def _tie_weights(self):
1429
+ if self.config.tie_word_embeddings:
1430
+ self._tie_or_clone_weights(self.encoder.embed_tokens, self.shared)
1431
+
1432
+ # Copied from transformers.models.t5.modeling_t5.T5EncoderModel.get_encoder
1433
+ def get_encoder(self):
1434
+ return self.encoder
1435
+
1436
+ # Copied from transformers.models.t5.modeling_t5.T5EncoderModel._prune_heads
1437
+ def _prune_heads(self, heads_to_prune):
1438
+ """
1439
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
1440
+ class PreTrainedModel
1441
+ """
1442
+ for layer, heads in heads_to_prune.items():
1443
+ self.encoder.block[layer].layer[0].SelfAttention.prune_heads(heads)
1444
+
1445
+ @auto_docstring
1446
+ # Copied from transformers.models.t5.modeling_t5.T5EncoderModel.forward with T5->UMT5, google-t5/t5-small->google/umt5-small, t5#training->umt5#training
1447
+ def forward(
1448
+ self,
1449
+ input_ids: Optional[torch.LongTensor] = None,
1450
+ attention_mask: Optional[torch.FloatTensor] = None,
1451
+ head_mask: Optional[torch.FloatTensor] = None,
1452
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1453
+ output_attentions: Optional[bool] = None,
1454
+ output_hidden_states: Optional[bool] = None,
1455
+ return_dict: Optional[bool] = None,
1456
+ ) -> Union[tuple[torch.FloatTensor], BaseModelOutput]:
1457
+ r"""
1458
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1459
+ Indices of input sequence tokens in the vocabulary. UMT5 is a model with relative position embeddings so you
1460
+ should be able to pad the inputs on both the right and the left.
1461
+
1462
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1463
+ [`PreTrainedTokenizer.__call__`] for detail.
1464
+
1465
+ To know more on how to prepare `input_ids` for pretraining take a look a [UMT5 Training](./umt5#training).
1466
+
1467
+ Example:
1468
+
1469
+ ```python
1470
+ >>> from transformers import AutoTokenizer, UMT5EncoderModel
1471
+
1472
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/umt5-small")
1473
+ >>> model = UMT5EncoderModel.from_pretrained("google/umt5-small")
1474
+ >>> input_ids = tokenizer(
1475
+ ... "Studies have been shown that owning a dog is good for you", return_tensors="pt"
1476
+ ... ).input_ids # Batch size 1
1477
+ >>> outputs = model(input_ids=input_ids)
1478
+ >>> last_hidden_states = outputs.last_hidden_state
1479
+ ```"""
1480
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1481
+
1482
+ encoder_outputs = self.encoder(
1483
+ input_ids=input_ids,
1484
+ attention_mask=attention_mask,
1485
+ inputs_embeds=inputs_embeds,
1486
+ head_mask=head_mask,
1487
+ output_attentions=output_attentions,
1488
+ output_hidden_states=output_hidden_states,
1489
+ return_dict=return_dict,
1490
+ )
1491
+
1492
+ return encoder_outputs
1493
+
1494
+
1495
+ @auto_docstring(
1496
+ custom_intro="""
1497
+ UMT5 model with a sequence classification/head on top (a linear layer on top of the pooled output) e.g. for GLUE
1498
+ tasks.
1499
+ """
1500
+ )
1501
+ class UMT5ForSequenceClassification(UMT5PreTrainedModel):
1502
+ _keys_to_ignore_on_load_unexpected = ["decoder.block.0.layer.1.EncDecAttention.relative_attention_bias.weight"]
1503
+ _tied_weights_keys = ["encoder.embed_tokens.weight", "decoder.embed_tokens.weight"]
1504
+
1505
+ # Copied from transformers.models.t5.modeling_t5.T5ForSequenceClassification.__init__ with T5->UMT5
1506
+ def __init__(self, config: UMT5Config):
1507
+ super().__init__(config)
1508
+ self.transformer = UMT5Model(config)
1509
+ self.classification_head = UMT5ClassificationHead(config)
1510
+
1511
+ # Initialize weights and apply final processing
1512
+ self.post_init()
1513
+
1514
+ self.model_parallel = False
1515
+
1516
+ @auto_docstring
1517
+ def forward(
1518
+ self,
1519
+ input_ids: Optional[torch.LongTensor] = None,
1520
+ attention_mask: Optional[torch.Tensor] = None,
1521
+ decoder_input_ids: Optional[torch.LongTensor] = None,
1522
+ decoder_attention_mask: Optional[torch.LongTensor] = None,
1523
+ head_mask: Optional[torch.Tensor] = None,
1524
+ decoder_head_mask: Optional[torch.Tensor] = None,
1525
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1526
+ encoder_outputs: Optional[list[torch.FloatTensor]] = None,
1527
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1528
+ decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
1529
+ labels: Optional[torch.LongTensor] = None,
1530
+ use_cache: Optional[bool] = None,
1531
+ output_attentions: Optional[bool] = None,
1532
+ output_hidden_states: Optional[bool] = None,
1533
+ return_dict: Optional[bool] = None,
1534
+ ) -> Union[tuple, Seq2SeqSequenceClassifierOutput]:
1535
+ r"""
1536
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1537
+ Indices of input sequence tokens in the vocabulary. UMT5 is a model with relative position embeddings so
1538
+ you should be able to pad the inputs on both the right and the left.
1539
+
1540
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1541
+ [`PreTrainedTokenizer.__call__`] for detail.
1542
+
1543
+ [What are input IDs?](../glossary#input-ids)
1544
+
1545
+ To know more on how to prepare `input_ids` for pretraining take a look a [UMT5 Training](./umt5#training).
1546
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
1547
+ Indices of decoder input sequence tokens in the vocabulary.
1548
+
1549
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1550
+ [`PreTrainedTokenizer.__call__`] for details.
1551
+
1552
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
1553
+
1554
+ UMT5 uses the `pad_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
1555
+ is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
1556
+
1557
+ To know more on how to prepare `decoder_input_ids` for pretraining take a look at [UMT5
1558
+ Training](./umt5#training).
1559
+ decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
1560
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
1561
+ be used by default.
1562
+ decoder_head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
1563
+ Mask to nullify selected heads of the self-attention modules in the decoder. Mask values selected in `[0,
1564
+ 1]`:
1565
+
1566
+ - 1 indicates the head is **not masked**,
1567
+ - 0 indicates the head is **masked**.
1568
+ cross_attn_head_mask (`torch.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
1569
+ Mask to nullify selected heads of the cross-attention modules in the decoder. Mask values selected in
1570
+ `[0, 1]`:
1571
+
1572
+ - 1 indicates the head is **not masked**,
1573
+ - 0 indicates the head is **masked**.
1574
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1575
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1576
+ config.num_labels - 1]`. If `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1577
+ """
1578
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1579
+ if labels is not None:
1580
+ use_cache = False
1581
+
1582
+ if input_ids is None and inputs_embeds is not None:
1583
+ raise NotImplementedError(
1584
+ f"Passing input embeddings is currently not supported for {self.__class__.__name__}"
1585
+ )
1586
+
1587
+ # Copied from models.bart.modeling_bart.BartModel.forward different to other models, T5 automatically creates
1588
+ # decoder_input_ids from input_ids if no decoder_input_ids are provided
1589
+ if decoder_input_ids is None and decoder_inputs_embeds is None:
1590
+ if input_ids is None:
1591
+ raise ValueError(
1592
+ "If no `decoder_input_ids` or `decoder_inputs_embeds` are "
1593
+ "passed, `input_ids` cannot be `None`. Please pass either "
1594
+ "`input_ids` or `decoder_input_ids` or `decoder_inputs_embeds`."
1595
+ )
1596
+ decoder_input_ids = self._shift_right(input_ids)
1597
+
1598
+ outputs = self.transformer(
1599
+ input_ids,
1600
+ attention_mask=attention_mask,
1601
+ decoder_input_ids=decoder_input_ids,
1602
+ decoder_attention_mask=decoder_attention_mask,
1603
+ head_mask=head_mask,
1604
+ decoder_head_mask=decoder_head_mask,
1605
+ cross_attn_head_mask=cross_attn_head_mask,
1606
+ encoder_outputs=encoder_outputs,
1607
+ inputs_embeds=inputs_embeds,
1608
+ decoder_inputs_embeds=decoder_inputs_embeds,
1609
+ use_cache=use_cache,
1610
+ output_attentions=output_attentions,
1611
+ output_hidden_states=output_hidden_states,
1612
+ return_dict=return_dict,
1613
+ )
1614
+ sequence_output = outputs[0]
1615
+
1616
+ eos_mask = input_ids.eq(self.config.eos_token_id).to(sequence_output.device)
1617
+
1618
+ if len(torch.unique_consecutive(eos_mask.sum(1))) > 1:
1619
+ raise ValueError("All examples must have the same number of <eos> tokens.")
1620
+ batch_size, _, hidden_size = sequence_output.shape
1621
+ sentence_representation = sequence_output[eos_mask, :].view(batch_size, -1, hidden_size)[:, -1, :]
1622
+ logits = self.classification_head(sentence_representation)
1623
+
1624
+ loss = None
1625
+ if labels is not None:
1626
+ labels = labels.to(logits.device)
1627
+ if self.config.problem_type is None:
1628
+ if self.config.num_labels == 1:
1629
+ self.config.problem_type = "regression"
1630
+ elif self.config.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1631
+ self.config.problem_type = "single_label_classification"
1632
+ else:
1633
+ self.config.problem_type = "multi_label_classification"
1634
+
1635
+ if self.config.problem_type == "regression":
1636
+ loss_fct = MSELoss()
1637
+ if self.config.num_labels == 1:
1638
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1639
+ else:
1640
+ loss = loss_fct(logits, labels)
1641
+ elif self.config.problem_type == "single_label_classification":
1642
+ loss_fct = CrossEntropyLoss()
1643
+ loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
1644
+ elif self.config.problem_type == "multi_label_classification":
1645
+ loss_fct = BCEWithLogitsLoss()
1646
+ loss = loss_fct(logits, labels)
1647
+ if not return_dict:
1648
+ output = (logits,) + outputs[1:]
1649
+ return ((loss,) + output) if loss is not None else output
1650
+
1651
+ return Seq2SeqSequenceClassifierOutput(
1652
+ loss=loss,
1653
+ logits=logits,
1654
+ past_key_values=outputs.past_key_values,
1655
+ decoder_hidden_states=outputs.decoder_hidden_states,
1656
+ decoder_attentions=outputs.decoder_attentions,
1657
+ cross_attentions=outputs.cross_attentions,
1658
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
1659
+ encoder_hidden_states=outputs.encoder_hidden_states,
1660
+ encoder_attentions=outputs.encoder_attentions,
1661
+ )
1662
+
1663
+
1664
+ @auto_docstring
1665
+ class UMT5ForTokenClassification(UMT5PreTrainedModel):
1666
+ _keys_to_ignore_on_load_unexpected = ["decoder.block.0.layer.1.EncDecAttention.relative_attention_bias.weight"]
1667
+ _tied_weights_keys = ["transformer.encoder.embed_tokens.weight"]
1668
+
1669
+ # Copied from transformers.models.t5.modeling_t5.T5ForTokenClassification.__init__ with T5->UMT5
1670
+ def __init__(self, config: UMT5Config):
1671
+ super().__init__(config)
1672
+ self.num_labels = config.num_labels
1673
+
1674
+ self.transformer = UMT5EncoderModel(config)
1675
+ self.dropout = nn.Dropout(config.classifier_dropout)
1676
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1677
+
1678
+ # Initialize weights and apply final processing
1679
+ self.post_init()
1680
+
1681
+ @auto_docstring
1682
+ # Copied from transformers.models.t5.modeling_t5.T5ForTokenClassification.forward with T5->UMT5, t5->umt5
1683
+ def forward(
1684
+ self,
1685
+ input_ids: Optional[torch.Tensor] = None,
1686
+ attention_mask: Optional[torch.Tensor] = None,
1687
+ head_mask: Optional[torch.Tensor] = None,
1688
+ inputs_embeds: Optional[torch.Tensor] = None,
1689
+ labels: Optional[torch.Tensor] = None,
1690
+ output_attentions: Optional[bool] = None,
1691
+ output_hidden_states: Optional[bool] = None,
1692
+ return_dict: Optional[bool] = None,
1693
+ ) -> Union[tuple[torch.Tensor], TokenClassifierOutput]:
1694
+ r"""
1695
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1696
+ Indices of input sequence tokens in the vocabulary. UMT5 is a model with relative position embeddings so you
1697
+ should be able to pad the inputs on both the right and the left.
1698
+
1699
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1700
+ [`PreTrainedTokenizer.__call__`] for detail.
1701
+
1702
+ [What are input IDs?](../glossary#input-ids)
1703
+
1704
+ To know more on how to prepare `input_ids` for pretraining take a look a [UMT5 Training](./umt5#training).
1705
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1706
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1707
+ """
1708
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1709
+
1710
+ outputs = self.transformer(
1711
+ input_ids,
1712
+ attention_mask=attention_mask,
1713
+ head_mask=head_mask,
1714
+ inputs_embeds=inputs_embeds,
1715
+ output_attentions=output_attentions,
1716
+ output_hidden_states=output_hidden_states,
1717
+ return_dict=return_dict,
1718
+ )
1719
+
1720
+ hidden_states = outputs[0]
1721
+ hidden_states = self.dropout(hidden_states)
1722
+ logits = self.classifier(hidden_states)
1723
+
1724
+ loss = None
1725
+ if labels is not None:
1726
+ loss_fct = CrossEntropyLoss()
1727
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1728
+
1729
+ if not return_dict:
1730
+ output = (logits, outputs[2:-1])
1731
+ return ((loss,) + output) if loss is not None else output
1732
+
1733
+ return TokenClassifierOutput(
1734
+ loss=loss,
1735
+ logits=logits,
1736
+ hidden_states=outputs.hidden_states,
1737
+ attentions=outputs.attentions,
1738
+ )
1739
+
1740
+
1741
+ @auto_docstring
1742
+ class UMT5ForQuestionAnswering(UMT5PreTrainedModel):
1743
+ _tied_weights_keys = ["encoder.embed_tokens.weight", "decoder.embed_tokens.weight"]
1744
+
1745
+ def __init__(self, config):
1746
+ super().__init__(config)
1747
+ self.model_dim = config.d_model
1748
+
1749
+ self.shared = nn.Embedding(config.vocab_size, config.d_model)
1750
+
1751
+ encoder_config = copy.deepcopy(config)
1752
+ encoder_config.is_decoder = False
1753
+ encoder_config.use_cache = False
1754
+ encoder_config.tie_encoder_decoder = False
1755
+ self.encoder = UMT5Stack(encoder_config, self.shared)
1756
+
1757
+ decoder_config = copy.deepcopy(config)
1758
+ decoder_config.is_decoder = True
1759
+ decoder_config.tie_encoder_decoder = False
1760
+ decoder_config.num_layers = config.num_decoder_layers
1761
+ self.decoder = UMT5Stack(decoder_config, self.shared)
1762
+
1763
+ self.num_labels = config.num_labels
1764
+ self.qa_outputs = nn.Linear(config.d_model, config.num_labels)
1765
+
1766
+ # Initialize weights and apply final processing
1767
+ self.post_init()
1768
+
1769
+ # Copied from transformers.models.t5.modeling_t5.T5ForQuestionAnswering.get_input_embeddings
1770
+ def get_input_embeddings(self):
1771
+ return self.shared
1772
+
1773
+ # Copied from transformers.models.t5.modeling_t5.T5ForQuestionAnswering.set_input_embeddings
1774
+ def set_input_embeddings(self, new_embeddings):
1775
+ self.shared = new_embeddings
1776
+ self.encoder.set_input_embeddings(new_embeddings)
1777
+ self.decoder.set_input_embeddings(new_embeddings)
1778
+
1779
+ # Copied from transformers.models.t5.modeling_t5.T5ForQuestionAnswering._tie_weights
1780
+ def _tie_weights(self):
1781
+ if self.config.tie_word_embeddings:
1782
+ self._tie_or_clone_weights(self.encoder.embed_tokens, self.shared)
1783
+ self._tie_or_clone_weights(self.decoder.embed_tokens, self.shared)
1784
+
1785
+ # Copied from transformers.models.t5.modeling_t5.T5ForQuestionAnswering.get_encoder
1786
+ def get_encoder(self):
1787
+ return self.encoder
1788
+
1789
+ # Copied from transformers.models.t5.modeling_t5.T5ForQuestionAnswering.get_decoder
1790
+ def get_decoder(self):
1791
+ return self.decoder
1792
+
1793
+ @auto_docstring
1794
+ def forward(
1795
+ self,
1796
+ input_ids: Optional[torch.LongTensor] = None,
1797
+ attention_mask: Optional[torch.FloatTensor] = None,
1798
+ decoder_input_ids: Optional[torch.LongTensor] = None,
1799
+ decoder_attention_mask: Optional[torch.BoolTensor] = None,
1800
+ head_mask: Optional[torch.FloatTensor] = None,
1801
+ decoder_head_mask: Optional[torch.FloatTensor] = None,
1802
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1803
+ encoder_outputs: Optional[tuple[tuple[torch.Tensor]]] = None,
1804
+ start_positions: Optional[torch.LongTensor] = None,
1805
+ end_positions: Optional[torch.LongTensor] = None,
1806
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1807
+ decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
1808
+ use_cache: Optional[bool] = None,
1809
+ output_attentions: Optional[bool] = None,
1810
+ output_hidden_states: Optional[bool] = None,
1811
+ return_dict: Optional[bool] = None,
1812
+ ) -> Union[tuple[torch.FloatTensor], Seq2SeqQuestionAnsweringModelOutput]:
1813
+ r"""
1814
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1815
+ Indices of input sequence tokens in the vocabulary. UMT5 is a model with relative position embeddings so
1816
+ you should be able to pad the inputs on both the right and the left.
1817
+
1818
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1819
+ [`PreTrainedTokenizer.__call__`] for detail.
1820
+
1821
+ [What are input IDs?](../glossary#input-ids)
1822
+
1823
+ To know more on how to prepare `input_ids` for pretraining take a look a [UMT5 Training](./umt5#training).
1824
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
1825
+ Indices of decoder input sequence tokens in the vocabulary.
1826
+
1827
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1828
+ [`PreTrainedTokenizer.__call__`] for details.
1829
+
1830
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
1831
+
1832
+ UMT5 uses the `pad_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
1833
+ is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
1834
+
1835
+ To know more on how to prepare `decoder_input_ids` for pretraining take a look at [UMT5
1836
+ Training](./umt5#training).
1837
+ decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
1838
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
1839
+ be used by default.
1840
+ decoder_head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
1841
+ Mask to nullify selected heads of the self-attention modules in the decoder. Mask values selected in `[0,
1842
+ 1]`:
1843
+
1844
+ - 1 indicates the head is **not masked**,
1845
+ - 0 indicates the head is **masked**.
1846
+ cross_attn_head_mask (`torch.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
1847
+ Mask to nullify selected heads of the cross-attention modules in the decoder. Mask values selected in
1848
+ `[0, 1]`:
1849
+
1850
+ - 1 indicates the head is **not masked**,
1851
+ - 0 indicates the head is **masked**.
1852
+ """
1853
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1854
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1855
+ if start_positions is not None and end_positions is not None:
1856
+ use_cache = False
1857
+
1858
+ # Copied from models.bart.modeling_bart.BartModel.forward
1859
+ # different to other models, T5 automatically creates decoder_input_ids from
1860
+ # input_ids if no decoder_input_ids are provided
1861
+ if decoder_input_ids is None and decoder_inputs_embeds is None:
1862
+ if input_ids is None:
1863
+ raise ValueError(
1864
+ "If no `decoder_input_ids` or `decoder_inputs_embeds` are "
1865
+ "passed, `input_ids` cannot be `None`. Please pass either "
1866
+ "`input_ids` or `decoder_input_ids` or `decoder_inputs_embeds`."
1867
+ )
1868
+ decoder_input_ids = self._shift_right(input_ids)
1869
+
1870
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1871
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1872
+
1873
+ # Encode if needed (training, first prediction pass)
1874
+ if encoder_outputs is None:
1875
+ encoder_outputs = self.encoder(
1876
+ input_ids=input_ids,
1877
+ attention_mask=attention_mask,
1878
+ inputs_embeds=inputs_embeds,
1879
+ head_mask=head_mask,
1880
+ output_attentions=output_attentions,
1881
+ output_hidden_states=output_hidden_states,
1882
+ return_dict=return_dict,
1883
+ )
1884
+ elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
1885
+ encoder_outputs = BaseModelOutput(
1886
+ last_hidden_state=encoder_outputs[0],
1887
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
1888
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
1889
+ )
1890
+
1891
+ hidden_states = encoder_outputs[0]
1892
+
1893
+ # Decode
1894
+ decoder_outputs = self.decoder(
1895
+ input_ids=decoder_input_ids,
1896
+ attention_mask=decoder_attention_mask,
1897
+ inputs_embeds=decoder_inputs_embeds,
1898
+ past_key_values=None,
1899
+ encoder_hidden_states=hidden_states,
1900
+ encoder_attention_mask=attention_mask,
1901
+ head_mask=decoder_head_mask,
1902
+ cross_attn_head_mask=cross_attn_head_mask,
1903
+ use_cache=use_cache,
1904
+ output_attentions=output_attentions,
1905
+ output_hidden_states=output_hidden_states,
1906
+ return_dict=return_dict,
1907
+ )
1908
+
1909
+ sequence_output = decoder_outputs[0]
1910
+
1911
+ logits = self.qa_outputs(sequence_output)
1912
+ start_logits, end_logits = logits.split(1, dim=-1)
1913
+ start_logits = start_logits.squeeze(-1).contiguous()
1914
+ end_logits = end_logits.squeeze(-1).contiguous()
1915
+
1916
+ total_loss = None
1917
+ if start_positions is not None and end_positions is not None:
1918
+ # If we are on multi-GPU, split add a dimension
1919
+ if len(start_positions.size()) > 1:
1920
+ start_positions = start_positions.squeeze(-1).to(start_logits.device)
1921
+ if len(end_positions.size()) > 1:
1922
+ end_positions = end_positions.squeeze(-1).to(end_logits.device)
1923
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1924
+ ignored_index = start_logits.size(1)
1925
+ start_positions = start_positions.clamp(0, ignored_index)
1926
+ end_positions = end_positions.clamp(0, ignored_index)
1927
+
1928
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1929
+ start_loss = loss_fct(start_logits, start_positions)
1930
+ end_loss = loss_fct(end_logits, end_positions)
1931
+ total_loss = (start_loss + end_loss) / 2
1932
+
1933
+ if not return_dict:
1934
+ output = (start_logits, end_logits) + decoder_outputs[1:] + encoder_outputs
1935
+ return ((total_loss,) + output) if total_loss is not None else output
1936
+
1937
+ return Seq2SeqQuestionAnsweringModelOutput(
1938
+ loss=total_loss,
1939
+ start_logits=start_logits,
1940
+ end_logits=end_logits,
1941
+ past_key_values=decoder_outputs.past_key_values,
1942
+ decoder_hidden_states=decoder_outputs.hidden_states,
1943
+ decoder_attentions=decoder_outputs.attentions,
1944
+ cross_attentions=decoder_outputs.cross_attentions,
1945
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
1946
+ encoder_hidden_states=encoder_outputs.hidden_states,
1947
+ encoder_attentions=encoder_outputs.attentions,
1948
+ )
1949
+
1950
+
1951
+ __all__ = [
1952
+ "UMT5EncoderModel",
1953
+ "UMT5ForConditionalGeneration",
1954
+ "UMT5ForQuestionAnswering",
1955
+ "UMT5ForSequenceClassification",
1956
+ "UMT5ForTokenClassification",
1957
+ "UMT5Model",
1958
+ "UMT5PreTrainedModel",
1959
+ ]
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/unispeech/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. 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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_unispeech import *
22
+ from .modeling_unispeech import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/unispeech/configuration_unispeech.py ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The Fairseq Authors and The HuggingFace Inc. team. 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
+ """UniSpeech model configuration"""
16
+
17
+ import functools
18
+ import operator
19
+
20
+ from ...configuration_utils import PretrainedConfig
21
+ from ...utils import logging
22
+
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+
27
+ class UniSpeechConfig(PretrainedConfig):
28
+ r"""
29
+ This is the configuration class to store the configuration of a [`UniSpeechModel`]. It is used to instantiate an
30
+ UniSpeech model according to the specified arguments, defining the model architecture. Instantiating a
31
+ configuration with the defaults will yield a similar configuration to that of the UniSpeech
32
+ [microsoft/unispeech-large-1500h-cv](https://huggingface.co/microsoft/unispeech-large-1500h-cv) architecture.
33
+
34
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
35
+ documentation from [`PretrainedConfig`] for more information.
36
+
37
+
38
+ Args:
39
+ vocab_size (`int`, *optional*, defaults to 32):
40
+ Vocabulary size of the UniSpeech model. Defines the number of different tokens that can be represented by
41
+ the `inputs_ids` passed when calling [`UniSpeechModel`]. Vocabulary size of the model. Defines the
42
+ different tokens that can be represented by the *inputs_ids* passed to the forward method of
43
+ [`UniSpeechModel`].
44
+ hidden_size (`int`, *optional*, defaults to 768):
45
+ Dimensionality of the encoder layers and the pooler layer.
46
+ num_hidden_layers (`int`, *optional*, defaults to 12):
47
+ Number of hidden layers in the Transformer encoder.
48
+ num_attention_heads (`int`, *optional*, defaults to 12):
49
+ Number of attention heads for each attention layer in the Transformer encoder.
50
+ intermediate_size (`int`, *optional*, defaults to 3072):
51
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
52
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
53
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
54
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
55
+ hidden_dropout (`float`, *optional*, defaults to 0.1):
56
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
57
+ activation_dropout (`float`, *optional*, defaults to 0.1):
58
+ The dropout ratio for activations inside the fully connected layer.
59
+ attention_dropout (`float`, *optional*, defaults to 0.1):
60
+ The dropout ratio for the attention probabilities.
61
+ feat_proj_dropout (`float`, *optional*, defaults to 0.0):
62
+ The dropout probability for output of the feature encoder.
63
+ feat_quantizer_dropout (`float`, *optional*, defaults to 0.0):
64
+ The dropout probability for the output of the feature encoder that's used by the quantizer.
65
+ final_dropout (`float`, *optional*, defaults to 0.1):
66
+ The dropout probability for the final projection layer of [`UniSpeechForCTC`].
67
+ layerdrop (`float`, *optional*, defaults to 0.1):
68
+ The LayerDrop probability. See the [LayerDrop paper](see https://huggingface.co/papers/1909.11556) for more
69
+ details.
70
+ initializer_range (`float`, *optional*, defaults to 0.02):
71
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
72
+ layer_norm_eps (`float`, *optional*, defaults to 1e-05):
73
+ The epsilon used by the layer normalization layers.
74
+ feat_extract_norm (`str`, *optional*, defaults to `"group"`):
75
+ The norm to be applied to 1D convolutional layers in feature encoder. One of `"group"` for group
76
+ normalization of only the first 1D convolutional layer or `"layer"` for layer normalization of all 1D
77
+ convolutional layers.
78
+ feat_extract_activation (`str, *optional*, defaults to `"gelu"`):
79
+ The non-linear activation function (function or string) in the 1D convolutional layers of the feature
80
+ extractor. If string, `"gelu"`, `"relu"`, `"selu"` and `"gelu_new"` are supported.
81
+ conv_dim (`tuple[int]` or `list[int]`, *optional*, defaults to `(512, 512, 512, 512, 512, 512, 512)`):
82
+ A tuple of integers defining the number of input and output channels of each 1D convolutional layer in the
83
+ feature encoder. The length of *conv_dim* defines the number of 1D convolutional layers.
84
+ conv_stride (`tuple[int]` or `list[int]`, *optional*, defaults to `(5, 2, 2, 2, 2, 2, 2)`):
85
+ A tuple of integers defining the stride of each 1D convolutional layer in the feature encoder. The length
86
+ of *conv_stride* defines the number of convolutional layers and has to match the length of *conv_dim*.
87
+ conv_kernel (`tuple[int]` or `list[int]`, *optional*, defaults to `(10, 3, 3, 3, 3, 2, 2)`):
88
+ A tuple of integers defining the kernel size of each 1D convolutional layer in the feature encoder. The
89
+ length of *conv_kernel* defines the number of convolutional layers and has to match the length of
90
+ *conv_dim*.
91
+ conv_bias (`bool`, *optional*, defaults to `False`):
92
+ Whether the 1D convolutional layers have a bias.
93
+ num_conv_pos_embeddings (`int`, *optional*, defaults to 128):
94
+ Number of convolutional positional embeddings. Defines the kernel size of 1D convolutional positional
95
+ embeddings layer.
96
+ num_conv_pos_embedding_groups (`int`, *optional*, defaults to 16):
97
+ Number of groups of 1D convolutional positional embeddings layer.
98
+ do_stable_layer_norm (`bool`, *optional*, defaults to `False`):
99
+ Whether to apply *stable* layer norm architecture of the Transformer encoder. `do_stable_layer_norm is
100
+ True` corresponds to applying layer norm before the attention layer, whereas `do_stable_layer_norm is
101
+ False` corresponds to applying layer norm after the attention layer.
102
+ apply_spec_augment (`bool`, *optional*, defaults to `True`):
103
+ Whether to apply *SpecAugment* data augmentation to the outputs of the feature encoder. For reference see
104
+ [SpecAugment: A Simple Data Augmentation Method for Automatic Speech
105
+ Recognition](https://huggingface.co/papers/1904.08779).
106
+ mask_time_prob (`float`, *optional*, defaults to 0.05):
107
+ Percentage (between 0 and 1) of all feature vectors along the time axis which will be masked. The masking
108
+ procedure generates ''mask_time_prob*len(time_axis)/mask_time_length'' independent masks over the axis. If
109
+ reasoning from the probability of each feature vector to be chosen as the start of the vector span to be
110
+ masked, *mask_time_prob* should be `prob_vector_start*mask_time_length`. Note that overlap may decrease the
111
+ actual percentage of masked vectors. This is only relevant if `apply_spec_augment is True`.
112
+ mask_time_length (`int`, *optional*, defaults to 10):
113
+ Length of vector span along the time axis.
114
+ mask_time_min_masks (`int`, *optional*, defaults to 2):
115
+ The minimum number of masks of length `mask_feature_length` generated along the time axis, each time step,
116
+ irrespectively of `mask_feature_prob`. Only relevant if ''mask_time_prob*len(time_axis)/mask_time_length <
117
+ mask_time_min_masks''
118
+ mask_feature_prob (`float`, *optional*, defaults to 0.0):
119
+ Percentage (between 0 and 1) of all feature vectors along the feature axis which will be masked. The
120
+ masking procedure generates ''mask_feature_prob*len(feature_axis)/mask_time_length'' independent masks over
121
+ the axis. If reasoning from the probability of each feature vector to be chosen as the start of the vector
122
+ span to be masked, *mask_feature_prob* should be `prob_vector_start*mask_feature_length`. Note that overlap
123
+ may decrease the actual percentage of masked vectors. This is only relevant if `apply_spec_augment is
124
+ True`.
125
+ mask_feature_length (`int`, *optional*, defaults to 10):
126
+ Length of vector span along the feature axis.
127
+ mask_feature_min_masks (`int`, *optional*, defaults to 0):
128
+ The minimum number of masks of length `mask_feature_length` generated along the feature axis, each time
129
+ step, irrespectively of `mask_feature_prob`. Only relevant if
130
+ ''mask_feature_prob*len(feature_axis)/mask_feature_length < mask_feature_min_masks''
131
+ num_codevectors_per_group (`int`, *optional*, defaults to 320):
132
+ Number of entries in each quantization codebook (group).
133
+ num_codevector_groups (`int`, *optional*, defaults to 2):
134
+ Number of codevector groups for product codevector quantization.
135
+ contrastive_logits_temperature (`float`, *optional*, defaults to 0.1):
136
+ The temperature *kappa* in the contrastive loss.
137
+ num_negatives (`int`, *optional*, defaults to 100):
138
+ Number of negative samples for the contrastive loss.
139
+ codevector_dim (`int`, *optional*, defaults to 256):
140
+ Dimensionality of the quantized feature vectors.
141
+ proj_codevector_dim (`int`, *optional*, defaults to 256):
142
+ Dimensionality of the final projection of both the quantized and the transformer features.
143
+ diversity_loss_weight (`int`, *optional*, defaults to 0.1):
144
+ The weight of the codebook diversity loss component.
145
+ ctc_loss_reduction (`str`, *optional*, defaults to `"mean"`):
146
+ Specifies the reduction to apply to the output of `torch.nn.CTCLoss`. Only relevant when training an
147
+ instance of [`UniSpeechForCTC`].
148
+ ctc_zero_infinity (`bool`, *optional*, defaults to `False`):
149
+ Whether to zero infinite losses and the associated gradients of `torch.nn.CTCLoss`. Infinite losses mainly
150
+ occur when the inputs are too short to be aligned to the targets. Only relevant when training an instance
151
+ of [`UniSpeechForCTC`].
152
+ use_weighted_layer_sum (`bool`, *optional*, defaults to `False`):
153
+ Whether to use a weighted average of layer outputs with learned weights. Only relevant when using an
154
+ instance of [`UniSpeechForSequenceClassification`].
155
+ classifier_proj_size (`int`, *optional*, defaults to 256):
156
+ Dimensionality of the projection before token mean-pooling for classification.
157
+ num_ctc_classes (`int`, *optional*, defaults to 80):
158
+ Specifies the number of classes (phoneme tokens and blank token) for phoneme-level CTC loss. Only relevant
159
+ when using an instance of [`UniSpeechForPreTraining`].
160
+ pad_token_id (`int`, *optional*, defaults to 0):
161
+ The id of the padding token.
162
+ bos_token_id (`int`, *optional*, defaults to 1):
163
+ The id of the "beginning-of-sequence" token.
164
+ eos_token_id (`int`, *optional*, defaults to 2):
165
+ The id of the "end-of-sequence" token.
166
+ replace_prob (`float`, *optional*, defaults to 0.5):
167
+ Probability that transformer feature is replaced by quantized feature for pretraining.
168
+
169
+ Example:
170
+
171
+ ```python
172
+ >>> from transformers import UniSpeechConfig, UniSpeechModel
173
+
174
+ >>> # Initializing a UniSpeech facebook/unispeech-base-960h style configuration
175
+ >>> configuration = UniSpeechConfig()
176
+
177
+ >>> # Initializing a model (with random weights) from the facebook/unispeech-base-960h style configuration
178
+ >>> model = UniSpeechModel(configuration)
179
+
180
+ >>> # Accessing the model configuration
181
+ >>> configuration = model.config
182
+ ```"""
183
+
184
+ model_type = "unispeech"
185
+
186
+ def __init__(
187
+ self,
188
+ vocab_size=32,
189
+ hidden_size=768,
190
+ num_hidden_layers=12,
191
+ num_attention_heads=12,
192
+ intermediate_size=3072,
193
+ hidden_act="gelu",
194
+ hidden_dropout=0.1,
195
+ activation_dropout=0.1,
196
+ attention_dropout=0.1,
197
+ feat_proj_dropout=0.0,
198
+ feat_quantizer_dropout=0.0,
199
+ final_dropout=0.1,
200
+ layerdrop=0.1,
201
+ initializer_range=0.02,
202
+ layer_norm_eps=1e-5,
203
+ feat_extract_norm="group",
204
+ feat_extract_activation="gelu",
205
+ conv_dim=(512, 512, 512, 512, 512, 512, 512),
206
+ conv_stride=(5, 2, 2, 2, 2, 2, 2),
207
+ conv_kernel=(10, 3, 3, 3, 3, 2, 2),
208
+ conv_bias=False,
209
+ num_conv_pos_embeddings=128,
210
+ num_conv_pos_embedding_groups=16,
211
+ do_stable_layer_norm=False,
212
+ apply_spec_augment=True,
213
+ mask_time_prob=0.05,
214
+ mask_time_length=10,
215
+ mask_time_min_masks=2,
216
+ mask_feature_prob=0.0,
217
+ mask_feature_length=10,
218
+ mask_feature_min_masks=0,
219
+ num_codevectors_per_group=320,
220
+ num_codevector_groups=2,
221
+ contrastive_logits_temperature=0.1,
222
+ num_negatives=100,
223
+ codevector_dim=256,
224
+ proj_codevector_dim=256,
225
+ diversity_loss_weight=0.1,
226
+ ctc_loss_reduction="mean",
227
+ ctc_zero_infinity=False,
228
+ use_weighted_layer_sum=False,
229
+ classifier_proj_size=256,
230
+ num_ctc_classes=80,
231
+ pad_token_id=0,
232
+ bos_token_id=1,
233
+ eos_token_id=2,
234
+ replace_prob=0.5,
235
+ **kwargs,
236
+ ):
237
+ super().__init__(**kwargs, pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id)
238
+ self.hidden_size = hidden_size
239
+ self.feat_extract_norm = feat_extract_norm
240
+ self.feat_extract_activation = feat_extract_activation
241
+ self.conv_dim = list(conv_dim)
242
+ self.conv_stride = list(conv_stride)
243
+ self.conv_kernel = list(conv_kernel)
244
+ self.conv_bias = conv_bias
245
+ self.num_conv_pos_embeddings = num_conv_pos_embeddings
246
+ self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups
247
+ self.num_feat_extract_layers = len(self.conv_dim)
248
+ self.num_hidden_layers = num_hidden_layers
249
+ self.intermediate_size = intermediate_size
250
+ self.hidden_act = hidden_act
251
+ self.num_attention_heads = num_attention_heads
252
+ self.hidden_dropout = hidden_dropout
253
+ self.attention_dropout = attention_dropout
254
+ self.activation_dropout = activation_dropout
255
+ self.feat_proj_dropout = feat_proj_dropout
256
+ self.final_dropout = final_dropout
257
+ self.layerdrop = layerdrop
258
+ self.layer_norm_eps = layer_norm_eps
259
+ self.initializer_range = initializer_range
260
+ self.num_ctc_classes = num_ctc_classes
261
+ self.vocab_size = vocab_size
262
+ self.do_stable_layer_norm = do_stable_layer_norm
263
+ self.use_weighted_layer_sum = use_weighted_layer_sum
264
+ self.classifier_proj_size = classifier_proj_size
265
+
266
+ if (
267
+ (len(self.conv_stride) != self.num_feat_extract_layers)
268
+ or (len(self.conv_kernel) != self.num_feat_extract_layers)
269
+ or (len(self.conv_dim) != self.num_feat_extract_layers)
270
+ ):
271
+ raise ValueError(
272
+ "Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="
273
+ " `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="
274
+ f" {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,"
275
+ f" `len(config.conv_kernel) = {len(self.conv_kernel)}`."
276
+ )
277
+
278
+ # fine-tuning config parameters for SpecAugment: https://huggingface.co/papers/1904.08779
279
+ self.apply_spec_augment = apply_spec_augment
280
+ self.mask_time_prob = mask_time_prob
281
+ self.mask_time_length = mask_time_length
282
+ self.mask_time_min_masks = mask_time_min_masks
283
+ self.mask_feature_prob = mask_feature_prob
284
+ self.mask_feature_length = mask_feature_length
285
+ self.mask_feature_min_masks = mask_feature_min_masks
286
+
287
+ # parameters for pretraining with codevector quantized representations
288
+ self.num_codevectors_per_group = num_codevectors_per_group
289
+ self.num_codevector_groups = num_codevector_groups
290
+ self.contrastive_logits_temperature = contrastive_logits_temperature
291
+ self.feat_quantizer_dropout = feat_quantizer_dropout
292
+ self.num_negatives = num_negatives
293
+ self.codevector_dim = codevector_dim
294
+ self.proj_codevector_dim = proj_codevector_dim
295
+ self.diversity_loss_weight = diversity_loss_weight
296
+
297
+ # ctc loss
298
+ self.ctc_loss_reduction = ctc_loss_reduction
299
+ self.ctc_zero_infinity = ctc_zero_infinity
300
+
301
+ # pretraining loss
302
+ self.replace_prob = replace_prob
303
+
304
+ @property
305
+ def inputs_to_logits_ratio(self):
306
+ return functools.reduce(operator.mul, self.conv_stride, 1)
307
+
308
+
309
+ __all__ = ["UniSpeechConfig"]
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/unispeech/convert_unispeech_original_pytorch_checkpoint_to_pytorch.py ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The HuggingFace Inc. team.
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
+ """Convert UniSpeech checkpoint."""
16
+
17
+ import argparse
18
+ import json
19
+ import os
20
+
21
+ import fairseq
22
+ import torch
23
+ from fairseq.data import Dictionary
24
+
25
+ from transformers import (
26
+ UniSpeechConfig,
27
+ UniSpeechForCTC,
28
+ UniSpeechForPreTraining,
29
+ Wav2Vec2FeatureExtractor,
30
+ Wav2Vec2PhonemeCTCTokenizer,
31
+ Wav2Vec2Processor,
32
+ logging,
33
+ )
34
+
35
+
36
+ logging.set_verbosity_info()
37
+ logger = logging.get_logger(__name__)
38
+
39
+ MAPPING = {
40
+ "post_extract_proj": "feature_projection.projection",
41
+ "encoder.pos_conv.0": "encoder.pos_conv_embed.conv",
42
+ "self_attn.k_proj": "encoder.layers.*.attention.k_proj",
43
+ "self_attn.v_proj": "encoder.layers.*.attention.v_proj",
44
+ "self_attn.q_proj": "encoder.layers.*.attention.q_proj",
45
+ "self_attn.out_proj": "encoder.layers.*.attention.out_proj",
46
+ "self_attn_layer_norm": "encoder.layers.*.layer_norm",
47
+ "fc1": "encoder.layers.*.feed_forward.intermediate_dense",
48
+ "fc2": "encoder.layers.*.feed_forward.output_dense",
49
+ "final_layer_norm": "encoder.layers.*.final_layer_norm",
50
+ "encoder.layer_norm": "encoder.layer_norm",
51
+ "w2v_model.layer_norm": "feature_projection.layer_norm",
52
+ "quantizer.weight_proj": "quantizer.weight_proj",
53
+ "quantizer.vars": "quantizer.codevectors",
54
+ "project_q": "project_q",
55
+ "final_proj": "project_hid",
56
+ "w2v_encoder.proj": "ctc_proj",
57
+ "mask_emb": "masked_spec_embed",
58
+ }
59
+ TOP_LEVEL_KEYS = [
60
+ "ctc_proj",
61
+ "quantizer.weight_proj",
62
+ "quantizer.codevectors",
63
+ "project_q",
64
+ "project_hid",
65
+ ]
66
+
67
+
68
+ def set_recursively(hf_pointer, key, value, full_name, weight_type, is_finetuned):
69
+ for attribute in key.split("."):
70
+ if is_finetuned:
71
+ if attribute in ["quantizer", "project_q", "project_hid"]:
72
+ # those layers are only relevant for pretraining and should be dropped
73
+ return
74
+
75
+ if attribute == "ctc_proj":
76
+ # we should rename `ctc_proj` to `lm_head` for fine-tuned phoneme models
77
+ attribute = "lm_head"
78
+
79
+ hf_pointer = getattr(hf_pointer, attribute)
80
+
81
+ if weight_type is not None:
82
+ hf_shape = getattr(hf_pointer, weight_type).shape
83
+ else:
84
+ hf_shape = hf_pointer.shape
85
+
86
+ assert hf_shape == value.shape, (
87
+ f"Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be"
88
+ f" {value.shape} for {full_name}"
89
+ )
90
+
91
+ if weight_type == "weight":
92
+ hf_pointer.weight.data = value
93
+ elif weight_type == "weight_g":
94
+ hf_pointer.weight_g.data = value
95
+ elif weight_type == "weight_v":
96
+ hf_pointer.weight_v.data = value
97
+ elif weight_type == "bias":
98
+ hf_pointer.bias.data = value
99
+ else:
100
+ hf_pointer.data = value
101
+
102
+ logger.info(f"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.")
103
+
104
+
105
+ def recursively_load_weights(fairseq_model, hf_model, is_finetuned):
106
+ unused_weights = []
107
+ fairseq_dict = fairseq_model.state_dict()
108
+
109
+ feature_extractor = hf_model.unispeech.feature_extractor
110
+
111
+ for name, value in fairseq_dict.items():
112
+ is_used = False
113
+ if "conv_layers" in name:
114
+ load_conv_layer(
115
+ name,
116
+ value,
117
+ feature_extractor,
118
+ unused_weights,
119
+ hf_model.config.feat_extract_norm == "group",
120
+ )
121
+ is_used = True
122
+ else:
123
+ for key, mapped_key in MAPPING.items():
124
+ mapped_key = "unispeech." + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key
125
+ if key in name or key.split("w2v_model.")[-1] == name.split(".")[0]:
126
+ is_used = True
127
+ if "*" in mapped_key:
128
+ layer_index = name.split(key)[0].split(".")[-2]
129
+ mapped_key = mapped_key.replace("*", layer_index)
130
+ if "weight_g" in name:
131
+ weight_type = "weight_g"
132
+ elif "weight_v" in name:
133
+ weight_type = "weight_v"
134
+ elif "bias" in name:
135
+ weight_type = "bias"
136
+ elif "weight" in name:
137
+ # TODO: don't match quantizer.weight_proj
138
+ weight_type = "weight"
139
+ else:
140
+ weight_type = None
141
+ set_recursively(hf_model, mapped_key, value, name, weight_type, is_finetuned)
142
+ continue
143
+ if not is_used:
144
+ unused_weights.append(name)
145
+
146
+ logger.warning(f"Unused weights: {unused_weights}")
147
+
148
+
149
+ def load_conv_layer(full_name, value, feature_extractor, unused_weights, use_group_norm):
150
+ name = full_name.split("conv_layers.")[-1]
151
+ items = name.split(".")
152
+ layer_id = int(items[0])
153
+ type_id = int(items[1])
154
+
155
+ if type_id == 0:
156
+ if "bias" in name:
157
+ assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, (
158
+ f"{full_name} has size {value.shape}, but"
159
+ f" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found."
160
+ )
161
+ feature_extractor.conv_layers[layer_id].conv.bias.data = value
162
+ logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}.")
163
+ elif "weight" in name:
164
+ assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, (
165
+ f"{full_name} has size {value.shape}, but"
166
+ f" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found."
167
+ )
168
+ feature_extractor.conv_layers[layer_id].conv.weight.data = value
169
+ logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}.")
170
+ elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
171
+ if "bias" in name:
172
+ assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, (
173
+ f"{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was"
174
+ " found."
175
+ )
176
+ feature_extractor.conv_layers[layer_id].layer_norm.bias.data = value
177
+ logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.")
178
+ elif "weight" in name:
179
+ assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, (
180
+ f"{full_name} has size {value.shape}, but"
181
+ f" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found."
182
+ )
183
+ feature_extractor.conv_layers[layer_id].layer_norm.weight.data = value
184
+ logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.")
185
+ else:
186
+ unused_weights.append(full_name)
187
+
188
+
189
+ @torch.no_grad()
190
+ def convert_unispeech_checkpoint(
191
+ checkpoint_path, pytorch_dump_folder_path, config_path=None, dict_path=None, is_finetuned=True
192
+ ):
193
+ """
194
+ Copy/paste/tweak model's weights to transformers design.
195
+ """
196
+ if config_path is not None:
197
+ config = UniSpeechConfig.from_pretrained(config_path)
198
+ else:
199
+ config = UniSpeechConfig()
200
+
201
+ if is_finetuned:
202
+ if dict_path:
203
+ target_dict = Dictionary.load_from_json(dict_path)
204
+
205
+ # important change bos & pad token id since CTC symbol is <pad> and
206
+ # not <s> as in fairseq
207
+ config.bos_token_id = target_dict.pad_index
208
+ config.pad_token_id = target_dict.bos_index
209
+ config.eos_token_id = target_dict.eos_index
210
+ config.vocab_size = len(target_dict.symbols)
211
+ vocab_path = os.path.join(pytorch_dump_folder_path, "vocab.json")
212
+ if not os.path.isdir(pytorch_dump_folder_path):
213
+ logger.error(f"--pytorch_dump_folder_path ({pytorch_dump_folder_path}) should be a directory")
214
+ return
215
+ os.makedirs(pytorch_dump_folder_path, exist_ok=True)
216
+ vocab_dict = target_dict.indices
217
+
218
+ # fairseq has the <pad> and <s> switched
219
+ vocab_dict["<pad>"] = 42
220
+ vocab_dict["<s>"] = 43
221
+ with open(vocab_path, "w", encoding="utf-8") as vocab_handle:
222
+ json.dump(vocab_dict, vocab_handle)
223
+ tokenizer = Wav2Vec2PhonemeCTCTokenizer(
224
+ vocab_path,
225
+ unk_token=target_dict.unk_word,
226
+ pad_token=target_dict.pad_word,
227
+ bos_token=target_dict.bos_word,
228
+ eos_token=target_dict.eos_word,
229
+ word_delimiter_token="|",
230
+ do_lower_case=False,
231
+ )
232
+ return_attention_mask = config.feat_extract_norm == "layer"
233
+ feature_extractor = Wav2Vec2FeatureExtractor(
234
+ feature_size=1,
235
+ sampling_rate=16000,
236
+ padding_value=0,
237
+ do_normalize=True,
238
+ return_attention_mask=return_attention_mask,
239
+ )
240
+ processor = Wav2Vec2Processor(feature_extractor=feature_extractor, tokenizer=tokenizer)
241
+ processor.save_pretrained(pytorch_dump_folder_path)
242
+
243
+ hf_unispeech = UniSpeechForCTC(config)
244
+ else:
245
+ hf_unispeech = UniSpeechForPreTraining(config)
246
+
247
+ if is_finetuned:
248
+ model, _, _ = fairseq.checkpoint_utils.load_model_ensemble_and_task(
249
+ [checkpoint_path], arg_overrides={"data": "/".join(dict_path.split("/")[:-1]), "w2v_path": checkpoint_path}
250
+ )
251
+ else:
252
+ model, _, _ = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path])
253
+
254
+ model = model[0].eval()
255
+
256
+ recursively_load_weights(model, hf_unispeech, is_finetuned)
257
+
258
+ hf_unispeech.save_pretrained(pytorch_dump_folder_path)
259
+
260
+
261
+ if __name__ == "__main__":
262
+ parser = argparse.ArgumentParser()
263
+ parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.")
264
+ parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to fairseq checkpoint")
265
+ parser.add_argument("--dict_path", default=None, type=str, help="Path to dict of fine-tuned model")
266
+ parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert")
267
+ parser.add_argument(
268
+ "--not_finetuned", action="store_true", help="Whether the model to convert is a fine-tuned model or not"
269
+ )
270
+ args = parser.parse_args()
271
+ convert_unispeech_checkpoint(
272
+ args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned
273
+ )
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/unispeech/modeling_unispeech.py ADDED
@@ -0,0 +1,1518 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/unispeech/modular_unispeech.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_unispeech.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2021 The Fairseq Authors and the HuggingFace Inc. team. All rights reserved.
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License");
11
+ # you may not use this file except in compliance with the License.
12
+ # You may obtain a copy of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS,
18
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ # See the License for the specific language governing permissions and
20
+ # limitations under the License.
21
+
22
+ import math
23
+ import warnings
24
+ from dataclasses import dataclass
25
+ from typing import Callable, Optional, Union
26
+
27
+ import numpy as np
28
+ import torch
29
+ import torch.nn as nn
30
+ from torch.nn import CrossEntropyLoss
31
+
32
+ from ...activations import ACT2FN
33
+ from ...integrations.deepspeed import is_deepspeed_zero3_enabled
34
+ from ...integrations.fsdp import is_fsdp_managed_module
35
+ from ...modeling_attn_mask_utils import _prepare_4d_attention_mask, _prepare_4d_attention_mask_for_sdpa
36
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
37
+ from ...modeling_layers import GradientCheckpointingLayer
38
+ from ...modeling_outputs import (
39
+ BaseModelOutput,
40
+ CausalLMOutput,
41
+ ModelOutput,
42
+ SequenceClassifierOutput,
43
+ Wav2Vec2BaseModelOutput,
44
+ )
45
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
46
+ from ...processing_utils import Unpack
47
+ from ...utils import auto_docstring, is_torch_flex_attn_available, logging
48
+ from .configuration_unispeech import UniSpeechConfig
49
+
50
+
51
+ if is_torch_flex_attn_available():
52
+ from ...integrations.flex_attention import make_flex_block_causal_mask
53
+
54
+
55
+ logger = logging.get_logger(__name__)
56
+
57
+
58
+ @dataclass
59
+ @auto_docstring(
60
+ custom_intro="""
61
+ Output type of [`UniSpeechForPreTrainingOutput`], with potential hidden states and attentions.
62
+ """
63
+ )
64
+ class UniSpeechForPreTrainingOutput(ModelOutput):
65
+ r"""
66
+ loss (*optional*, returned when model is in train mode, `torch.FloatTensor` of shape `(1,)`):
67
+ Total loss as the sum of the contrastive loss (L_m) and the diversity loss (L_d) as stated in the [official
68
+ paper](https://arxiv.org/pdf/2006.11477.pdf) . (classification) loss.
69
+ projected_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.proj_codevector_dim)`):
70
+ Hidden-states of the model projected to *config.proj_codevector_dim* that can be used to predict the masked
71
+ projected quantized states.
72
+ projected_quantized_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.proj_codevector_dim)`):
73
+ Quantized extracted feature vectors projected to *config.proj_codevector_dim* representing the positive
74
+ target vectors for contrastive loss.
75
+ codevector_perplexity (`torch.FloatTensor` of shape `(1,)`):
76
+ The perplexity of the codevector distribution, used to measure the diversity of the codebook.
77
+ """
78
+
79
+ loss: Optional[torch.FloatTensor] = None
80
+ projected_states: Optional[torch.FloatTensor] = None
81
+ projected_quantized_states: Optional[torch.FloatTensor] = None
82
+ codevector_perplexity: Optional[torch.FloatTensor] = None
83
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
84
+ attentions: Optional[tuple[torch.FloatTensor]] = None
85
+
86
+
87
+ class UniSpeechSamePadLayer(nn.Module):
88
+ def __init__(self, num_conv_pos_embeddings):
89
+ super().__init__()
90
+ self.num_pad_remove = 1 if num_conv_pos_embeddings % 2 == 0 else 0
91
+
92
+ def forward(self, hidden_states):
93
+ if self.num_pad_remove > 0:
94
+ hidden_states = hidden_states[:, :, : -self.num_pad_remove]
95
+ return hidden_states
96
+
97
+
98
+ class UniSpeechPositionalConvEmbedding(nn.Module):
99
+ def __init__(self, config):
100
+ super().__init__()
101
+ self.conv = nn.Conv1d(
102
+ config.hidden_size,
103
+ config.hidden_size,
104
+ kernel_size=config.num_conv_pos_embeddings,
105
+ padding=config.num_conv_pos_embeddings // 2,
106
+ groups=config.num_conv_pos_embedding_groups,
107
+ )
108
+
109
+ weight_norm = nn.utils.weight_norm
110
+ if hasattr(nn.utils.parametrizations, "weight_norm"):
111
+ weight_norm = nn.utils.parametrizations.weight_norm
112
+
113
+ if is_deepspeed_zero3_enabled():
114
+ import deepspeed
115
+
116
+ with deepspeed.zero.GatheredParameters(self.conv.weight, modifier_rank=0):
117
+ self.conv = weight_norm(self.conv, name="weight", dim=2)
118
+ if hasattr(self.conv, "parametrizations"):
119
+ weight_g = self.conv.parametrizations.weight.original0
120
+ weight_v = self.conv.parametrizations.weight.original1
121
+ else:
122
+ weight_g = self.conv.weight_g
123
+ weight_v = self.conv.weight_v
124
+ deepspeed.zero.register_external_parameter(self, weight_v)
125
+ deepspeed.zero.register_external_parameter(self, weight_g)
126
+ else:
127
+ self.conv = weight_norm(self.conv, name="weight", dim=2)
128
+
129
+ self.padding = UniSpeechSamePadLayer(config.num_conv_pos_embeddings)
130
+ self.activation = ACT2FN[config.feat_extract_activation]
131
+
132
+ def forward(self, hidden_states):
133
+ hidden_states = hidden_states.transpose(1, 2)
134
+
135
+ hidden_states = self.conv(hidden_states)
136
+ hidden_states = self.padding(hidden_states)
137
+ hidden_states = self.activation(hidden_states)
138
+
139
+ hidden_states = hidden_states.transpose(1, 2)
140
+ return hidden_states
141
+
142
+
143
+ class UniSpeechNoLayerNormConvLayer(GradientCheckpointingLayer):
144
+ def __init__(self, config, layer_id=0):
145
+ super().__init__()
146
+ self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1
147
+ self.out_conv_dim = config.conv_dim[layer_id]
148
+
149
+ self.conv = nn.Conv1d(
150
+ self.in_conv_dim,
151
+ self.out_conv_dim,
152
+ kernel_size=config.conv_kernel[layer_id],
153
+ stride=config.conv_stride[layer_id],
154
+ bias=config.conv_bias,
155
+ )
156
+ self.activation = ACT2FN[config.feat_extract_activation]
157
+
158
+ def forward(self, hidden_states):
159
+ hidden_states = self.conv(hidden_states)
160
+ hidden_states = self.activation(hidden_states)
161
+ return hidden_states
162
+
163
+
164
+ class UniSpeechLayerNormConvLayer(GradientCheckpointingLayer):
165
+ def __init__(self, config, layer_id=0):
166
+ super().__init__()
167
+ self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1
168
+ self.out_conv_dim = config.conv_dim[layer_id]
169
+
170
+ self.conv = nn.Conv1d(
171
+ self.in_conv_dim,
172
+ self.out_conv_dim,
173
+ kernel_size=config.conv_kernel[layer_id],
174
+ stride=config.conv_stride[layer_id],
175
+ bias=config.conv_bias,
176
+ )
177
+ self.layer_norm = nn.LayerNorm(self.out_conv_dim, elementwise_affine=True)
178
+ self.activation = ACT2FN[config.feat_extract_activation]
179
+
180
+ def forward(self, hidden_states):
181
+ hidden_states = self.conv(hidden_states)
182
+
183
+ hidden_states = hidden_states.transpose(-2, -1)
184
+ hidden_states = self.layer_norm(hidden_states)
185
+ hidden_states = hidden_states.transpose(-2, -1)
186
+
187
+ hidden_states = self.activation(hidden_states)
188
+ return hidden_states
189
+
190
+
191
+ class UniSpeechGroupNormConvLayer(GradientCheckpointingLayer):
192
+ def __init__(self, config, layer_id=0):
193
+ super().__init__()
194
+ self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1
195
+ self.out_conv_dim = config.conv_dim[layer_id]
196
+
197
+ self.conv = nn.Conv1d(
198
+ self.in_conv_dim,
199
+ self.out_conv_dim,
200
+ kernel_size=config.conv_kernel[layer_id],
201
+ stride=config.conv_stride[layer_id],
202
+ bias=config.conv_bias,
203
+ )
204
+ self.activation = ACT2FN[config.feat_extract_activation]
205
+
206
+ self.layer_norm = nn.GroupNorm(num_groups=self.out_conv_dim, num_channels=self.out_conv_dim, affine=True)
207
+
208
+ def forward(self, hidden_states):
209
+ hidden_states = self.conv(hidden_states)
210
+ hidden_states = self.layer_norm(hidden_states)
211
+ hidden_states = self.activation(hidden_states)
212
+ return hidden_states
213
+
214
+
215
+ class UniSpeechFeatureEncoder(nn.Module):
216
+ """Construct the features from raw audio waveform"""
217
+
218
+ def __init__(self, config):
219
+ super().__init__()
220
+
221
+ if config.feat_extract_norm == "group":
222
+ conv_layers = [UniSpeechGroupNormConvLayer(config, layer_id=0)] + [
223
+ UniSpeechNoLayerNormConvLayer(config, layer_id=i + 1)
224
+ for i in range(config.num_feat_extract_layers - 1)
225
+ ]
226
+ elif config.feat_extract_norm == "layer":
227
+ conv_layers = [
228
+ UniSpeechLayerNormConvLayer(config, layer_id=i) for i in range(config.num_feat_extract_layers)
229
+ ]
230
+ else:
231
+ raise ValueError(
232
+ f"`config.feat_extract_norm` is {config.feat_extract_norm}, but has to be one of ['group', 'layer']"
233
+ )
234
+ self.conv_layers = nn.ModuleList(conv_layers)
235
+ self.gradient_checkpointing = False
236
+ self._requires_grad = True
237
+
238
+ def _freeze_parameters(self):
239
+ for param in self.parameters():
240
+ param.requires_grad = False
241
+ self._requires_grad = False
242
+
243
+ def forward(self, input_values):
244
+ hidden_states = input_values[:, None]
245
+
246
+ # make sure hidden_states require grad for gradient_checkpointing
247
+ if self._requires_grad and self.training:
248
+ hidden_states.requires_grad = True
249
+
250
+ for conv_layer in self.conv_layers:
251
+ hidden_states = conv_layer(hidden_states)
252
+
253
+ return hidden_states
254
+
255
+
256
+ class UniSpeechFeatureProjection(nn.Module):
257
+ def __init__(self, config):
258
+ super().__init__()
259
+ self.layer_norm = nn.LayerNorm(config.conv_dim[-1], eps=config.layer_norm_eps)
260
+ self.projection = nn.Linear(config.conv_dim[-1], config.hidden_size)
261
+ self.dropout = nn.Dropout(config.feat_proj_dropout)
262
+
263
+ def forward(self, hidden_states):
264
+ # non-projected hidden states are needed for quantization
265
+ norm_hidden_states = self.layer_norm(hidden_states)
266
+ hidden_states = self.projection(norm_hidden_states)
267
+ hidden_states = self.dropout(hidden_states)
268
+ return hidden_states, norm_hidden_states
269
+
270
+
271
+ def eager_attention_forward(
272
+ module: nn.Module,
273
+ query: torch.Tensor,
274
+ key: torch.Tensor,
275
+ value: torch.Tensor,
276
+ attention_mask: Optional[torch.Tensor],
277
+ scaling: Optional[float] = None,
278
+ dropout: float = 0.0,
279
+ head_mask: Optional[torch.Tensor] = None,
280
+ **kwargs,
281
+ ):
282
+ if scaling is None:
283
+ scaling = query.size(-1) ** -0.5
284
+
285
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
286
+ if attention_mask is not None:
287
+ attn_weights = attn_weights + attention_mask
288
+
289
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
290
+
291
+ if head_mask is not None:
292
+ attn_weights = attn_weights * head_mask.view(1, -1, 1, 1)
293
+
294
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
295
+ attn_output = torch.matmul(attn_weights, value)
296
+ attn_output = attn_output.transpose(1, 2).contiguous()
297
+
298
+ return attn_output, attn_weights
299
+
300
+
301
+ class UniSpeechAttention(nn.Module):
302
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
303
+
304
+ def __init__(
305
+ self,
306
+ embed_dim: int,
307
+ num_heads: int,
308
+ dropout: float = 0.0,
309
+ is_decoder: bool = False,
310
+ bias: bool = True,
311
+ is_causal: bool = False,
312
+ config: Optional[UniSpeechConfig] = None,
313
+ ):
314
+ super().__init__()
315
+ self.embed_dim = embed_dim
316
+ self.num_heads = num_heads
317
+ self.dropout = dropout
318
+ self.head_dim = embed_dim // num_heads
319
+ self.config = config
320
+
321
+ if (self.head_dim * num_heads) != self.embed_dim:
322
+ raise ValueError(
323
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
324
+ f" and `num_heads`: {num_heads})."
325
+ )
326
+ self.scaling = self.head_dim**-0.5
327
+ self.is_decoder = is_decoder
328
+ self.is_causal = is_causal
329
+
330
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
331
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
332
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
333
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
334
+
335
+ def forward(
336
+ self,
337
+ hidden_states: torch.Tensor,
338
+ key_value_states: Optional[torch.Tensor] = None,
339
+ attention_mask: Optional[torch.Tensor] = None,
340
+ layer_head_mask: Optional[torch.Tensor] = None,
341
+ output_attentions: Optional[bool] = False,
342
+ # TODO: we need a refactor so that the different attention modules can get their specific kwargs
343
+ # ATM, we have mixed things encoder, decoder, and encoder-decoder attn
344
+ **kwargs: Unpack[FlashAttentionKwargs],
345
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
346
+ """Input shape: Batch x Time x Channel"""
347
+
348
+ # if key_value_states are provided this layer is used as a cross-attention layer
349
+ # for the decoder
350
+ is_cross_attention = key_value_states is not None
351
+
352
+ # determine input shapes
353
+ bsz, tgt_len = hidden_states.shape[:-1]
354
+ src_len = key_value_states.shape[1] if is_cross_attention else tgt_len
355
+
356
+ q_input_shape = (bsz, tgt_len, -1, self.head_dim)
357
+ kv_input_shape = (bsz, src_len, -1, self.head_dim)
358
+
359
+ # get query proj
360
+ query_states = self.q_proj(hidden_states).view(*q_input_shape).transpose(1, 2)
361
+
362
+ current_states = key_value_states if is_cross_attention else hidden_states
363
+ key_states = self.k_proj(current_states).view(*kv_input_shape).transpose(1, 2)
364
+ value_states = self.v_proj(current_states).view(*kv_input_shape).transpose(1, 2)
365
+
366
+ attention_interface: Callable = eager_attention_forward
367
+ if self.config._attn_implementation != "eager":
368
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
369
+
370
+ attn_output, attn_weights = attention_interface(
371
+ self,
372
+ query_states,
373
+ key_states,
374
+ value_states,
375
+ attention_mask,
376
+ dropout=0.0 if not self.training else self.dropout,
377
+ scaling=self.scaling,
378
+ output_attentions=output_attentions,
379
+ head_mask=layer_head_mask,
380
+ **kwargs,
381
+ )
382
+
383
+ attn_output = attn_output.reshape(bsz, tgt_len, -1).contiguous()
384
+ attn_output = self.out_proj(attn_output)
385
+
386
+ return attn_output, attn_weights, None
387
+
388
+
389
+ class UniSpeechFeedForward(nn.Module):
390
+ def __init__(self, config):
391
+ super().__init__()
392
+ self.intermediate_dropout = nn.Dropout(config.activation_dropout)
393
+
394
+ self.intermediate_dense = nn.Linear(config.hidden_size, config.intermediate_size)
395
+ if isinstance(config.hidden_act, str):
396
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
397
+ else:
398
+ self.intermediate_act_fn = config.hidden_act
399
+
400
+ self.output_dense = nn.Linear(config.intermediate_size, config.hidden_size)
401
+ self.output_dropout = nn.Dropout(config.hidden_dropout)
402
+
403
+ def forward(self, hidden_states):
404
+ hidden_states = self.intermediate_dense(hidden_states)
405
+ hidden_states = self.intermediate_act_fn(hidden_states)
406
+ hidden_states = self.intermediate_dropout(hidden_states)
407
+
408
+ hidden_states = self.output_dense(hidden_states)
409
+ hidden_states = self.output_dropout(hidden_states)
410
+ return hidden_states
411
+
412
+
413
+ class UniSpeechEncoderLayer(GradientCheckpointingLayer):
414
+ def __init__(self, config):
415
+ super().__init__()
416
+ self.attention = UniSpeechAttention(
417
+ embed_dim=config.hidden_size,
418
+ num_heads=config.num_attention_heads,
419
+ dropout=config.attention_dropout,
420
+ is_decoder=False,
421
+ config=config,
422
+ )
423
+
424
+ self.dropout = nn.Dropout(config.hidden_dropout)
425
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
426
+ self.feed_forward = UniSpeechFeedForward(config)
427
+ self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
428
+
429
+ def forward(self, hidden_states, attention_mask=None, output_attentions=False):
430
+ attn_residual = hidden_states
431
+ hidden_states, attn_weights, _ = self.attention(
432
+ hidden_states, attention_mask=attention_mask, output_attentions=output_attentions
433
+ )
434
+ hidden_states = self.dropout(hidden_states)
435
+ hidden_states = attn_residual + hidden_states
436
+
437
+ hidden_states = self.layer_norm(hidden_states)
438
+ hidden_states = hidden_states + self.feed_forward(hidden_states)
439
+ hidden_states = self.final_layer_norm(hidden_states)
440
+
441
+ outputs = (hidden_states,)
442
+
443
+ if output_attentions:
444
+ outputs += (attn_weights,)
445
+
446
+ return outputs
447
+
448
+
449
+ class UniSpeechEncoder(nn.Module):
450
+ def __init__(self, config):
451
+ super().__init__()
452
+ self.config = config
453
+ self.pos_conv_embed = UniSpeechPositionalConvEmbedding(config)
454
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
455
+ self.dropout = nn.Dropout(config.hidden_dropout)
456
+ self.layers = nn.ModuleList([UniSpeechEncoderLayer(config) for _ in range(config.num_hidden_layers)])
457
+ self.gradient_checkpointing = False
458
+
459
+ def forward(
460
+ self,
461
+ hidden_states: torch.tensor,
462
+ attention_mask: Optional[torch.Tensor] = None,
463
+ output_attentions: bool = False,
464
+ output_hidden_states: bool = False,
465
+ return_dict: bool = True,
466
+ ):
467
+ all_hidden_states = () if output_hidden_states else None
468
+ all_self_attentions = () if output_attentions else None
469
+
470
+ if attention_mask is not None:
471
+ # make sure padded tokens output 0
472
+ expand_attention_mask = attention_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
473
+ hidden_states[~expand_attention_mask] = 0
474
+
475
+ attention_mask = self._update_full_mask(
476
+ attention_mask,
477
+ hidden_states,
478
+ )
479
+
480
+ position_embeddings = self.pos_conv_embed(hidden_states)
481
+ hidden_states = hidden_states + position_embeddings
482
+ hidden_states = self.layer_norm(hidden_states)
483
+ hidden_states = self.dropout(hidden_states)
484
+
485
+ synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)
486
+
487
+ for layer in self.layers:
488
+ if output_hidden_states:
489
+ all_hidden_states = all_hidden_states + (hidden_states,)
490
+
491
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
492
+ dropout_probability = torch.rand([])
493
+
494
+ skip_the_layer = self.training and dropout_probability < self.config.layerdrop
495
+ if not skip_the_layer or synced_gpus:
496
+ # under fsdp or deepspeed zero3 all gpus must run in sync
497
+ layer_outputs = layer(
498
+ hidden_states, attention_mask=attention_mask, output_attentions=output_attentions
499
+ )
500
+ hidden_states = layer_outputs[0]
501
+
502
+ if skip_the_layer:
503
+ layer_outputs = (None, None)
504
+
505
+ if output_attentions:
506
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
507
+
508
+ if output_hidden_states:
509
+ all_hidden_states = all_hidden_states + (hidden_states,)
510
+
511
+ if not return_dict:
512
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
513
+ return BaseModelOutput(
514
+ last_hidden_state=hidden_states,
515
+ hidden_states=all_hidden_states,
516
+ attentions=all_self_attentions,
517
+ )
518
+
519
+ def _update_full_mask(
520
+ self,
521
+ attention_mask: Union[torch.Tensor, None],
522
+ inputs_embeds: torch.Tensor,
523
+ ):
524
+ if attention_mask is not None:
525
+ if self.config._attn_implementation == "flash_attention_2":
526
+ attention_mask = attention_mask if 0 in attention_mask else None
527
+ elif self.config._attn_implementation == "sdpa":
528
+ # output_attentions=True & head_mask can not be supported when using SDPA, fall back to
529
+ # the manual implementation that requires a 4D causal mask in all cases.
530
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
531
+ attention_mask = _prepare_4d_attention_mask_for_sdpa(attention_mask, inputs_embeds.dtype)
532
+ elif self.config._attn_implementation == "flex_attention":
533
+ if isinstance(attention_mask, torch.Tensor):
534
+ attention_mask = make_flex_block_causal_mask(attention_mask, is_causal=False)
535
+ else:
536
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
537
+ attention_mask = _prepare_4d_attention_mask(attention_mask, inputs_embeds.dtype)
538
+
539
+ return attention_mask
540
+
541
+
542
+ class UniSpeechAttnAdapterLayer(nn.Module):
543
+ def __init__(self, config):
544
+ """
545
+ Implements adapter modules directly with 3D tensor weight as parameters and without using ModuleList to speed
546
+ up training throughput.
547
+ """
548
+ super().__init__()
549
+ self.input_dim = config.adapter_attn_dim
550
+ self.hidden_dim = config.hidden_size
551
+
552
+ self.norm = nn.LayerNorm(self.hidden_dim)
553
+ self.linear_1 = nn.Linear(self.hidden_dim, self.input_dim)
554
+ self.act_fn = nn.ReLU()
555
+ self.linear_2 = nn.Linear(self.input_dim, self.hidden_dim)
556
+
557
+ def forward(self, hidden_states: torch.FloatTensor):
558
+ hidden_states = self.norm(hidden_states)
559
+
560
+ hidden_states = self.linear_1(hidden_states)
561
+ hidden_states = self.act_fn(hidden_states)
562
+ hidden_states = self.linear_2(hidden_states)
563
+
564
+ return hidden_states
565
+
566
+
567
+ class UniSpeechEncoderLayerStableLayerNorm(GradientCheckpointingLayer):
568
+ def __init__(self, config):
569
+ super().__init__()
570
+ self.attention = UniSpeechAttention(
571
+ embed_dim=config.hidden_size,
572
+ num_heads=config.num_attention_heads,
573
+ dropout=config.attention_dropout,
574
+ is_decoder=False,
575
+ config=config,
576
+ )
577
+ self.dropout = nn.Dropout(config.hidden_dropout)
578
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
579
+ self.feed_forward = UniSpeechFeedForward(config)
580
+ self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
581
+
582
+ if getattr(config, "adapter_attn_dim", None) is not None:
583
+ self.adapter_layer = UniSpeechAttnAdapterLayer(config)
584
+ else:
585
+ self.adapter_layer = None
586
+
587
+ def forward(
588
+ self,
589
+ hidden_states: torch.Tensor,
590
+ attention_mask: Optional[torch.Tensor] = None,
591
+ output_attentions: bool = False,
592
+ ):
593
+ attn_residual = hidden_states
594
+ hidden_states = self.layer_norm(hidden_states)
595
+ hidden_states, attn_weights, _ = self.attention(
596
+ hidden_states, attention_mask=attention_mask, output_attentions=output_attentions
597
+ )
598
+ hidden_states = self.dropout(hidden_states)
599
+ hidden_states = attn_residual + hidden_states
600
+ hidden_states = hidden_states + self.feed_forward(self.final_layer_norm(hidden_states))
601
+
602
+ if self.adapter_layer is not None:
603
+ hidden_states = hidden_states + self.adapter_layer(hidden_states)
604
+
605
+ outputs = (hidden_states,)
606
+
607
+ if output_attentions:
608
+ outputs += (attn_weights,)
609
+
610
+ return outputs
611
+
612
+
613
+ class UniSpeechEncoderStableLayerNorm(nn.Module):
614
+ def __init__(self, config):
615
+ super().__init__()
616
+ self.config = config
617
+ self.pos_conv_embed = UniSpeechPositionalConvEmbedding(config)
618
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
619
+ self.dropout = nn.Dropout(config.hidden_dropout)
620
+ self.layers = nn.ModuleList(
621
+ [UniSpeechEncoderLayerStableLayerNorm(config) for _ in range(config.num_hidden_layers)]
622
+ )
623
+ self.gradient_checkpointing = False
624
+
625
+ def forward(
626
+ self,
627
+ hidden_states,
628
+ attention_mask=None,
629
+ output_attentions=False,
630
+ output_hidden_states=False,
631
+ return_dict=True,
632
+ ):
633
+ all_hidden_states = () if output_hidden_states else None
634
+ all_self_attentions = () if output_attentions else None
635
+
636
+ if attention_mask is not None:
637
+ # make sure padded tokens output 0
638
+ expand_attention_mask = attention_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
639
+ hidden_states[~expand_attention_mask] = 0
640
+
641
+ attention_mask = self._update_full_mask(
642
+ attention_mask,
643
+ hidden_states,
644
+ )
645
+
646
+ position_embeddings = self.pos_conv_embed(hidden_states)
647
+ hidden_states = hidden_states + position_embeddings
648
+ hidden_states = self.dropout(hidden_states)
649
+
650
+ synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)
651
+
652
+ for layer in self.layers:
653
+ if output_hidden_states:
654
+ all_hidden_states = all_hidden_states + (hidden_states,)
655
+
656
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
657
+ dropout_probability = torch.rand([])
658
+
659
+ skip_the_layer = self.training and dropout_probability < self.config.layerdrop
660
+ if not skip_the_layer or synced_gpus:
661
+ # under fsdp or deepspeed zero3 all gpus must run in sync
662
+ # XXX: could optimize this like synced_gpus in generate_utils but not sure if it's worth the code complication
663
+ layer_outputs = layer(
664
+ hidden_states, attention_mask=attention_mask, output_attentions=output_attentions
665
+ )
666
+ hidden_states = layer_outputs[0]
667
+
668
+ if skip_the_layer:
669
+ layer_outputs = (None, None)
670
+
671
+ if output_attentions:
672
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
673
+
674
+ hidden_states = self.layer_norm(hidden_states)
675
+
676
+ if output_hidden_states:
677
+ all_hidden_states = all_hidden_states + (hidden_states,)
678
+
679
+ if not return_dict:
680
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
681
+ return BaseModelOutput(
682
+ last_hidden_state=hidden_states,
683
+ hidden_states=all_hidden_states,
684
+ attentions=all_self_attentions,
685
+ )
686
+
687
+ def _update_full_mask(
688
+ self,
689
+ attention_mask: Union[torch.Tensor, None],
690
+ inputs_embeds: torch.Tensor,
691
+ ):
692
+ if attention_mask is not None:
693
+ if self.config._attn_implementation == "flash_attention_2":
694
+ attention_mask = attention_mask if 0 in attention_mask else None
695
+ elif self.config._attn_implementation == "sdpa":
696
+ # output_attentions=True & head_mask can not be supported when using SDPA, fall back to
697
+ # the manual implementation that requires a 4D causal mask in all cases.
698
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
699
+ attention_mask = _prepare_4d_attention_mask_for_sdpa(attention_mask, inputs_embeds.dtype)
700
+ elif self.config._attn_implementation == "flex_attention":
701
+ if isinstance(attention_mask, torch.Tensor):
702
+ attention_mask = make_flex_block_causal_mask(attention_mask, is_causal=False)
703
+ else:
704
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
705
+ attention_mask = _prepare_4d_attention_mask(attention_mask, inputs_embeds.dtype)
706
+
707
+ return attention_mask
708
+
709
+
710
+ class UniSpeechGumbelVectorQuantizer(nn.Module):
711
+ """
712
+ Vector quantization using gumbel softmax. See `[CATEGORICAL REPARAMETERIZATION WITH
713
+ GUMBEL-SOFTMAX](https://huggingface.co/papers/1611.01144) for more information.
714
+ """
715
+
716
+ def __init__(self, config):
717
+ super().__init__()
718
+ self.num_groups = config.num_codevector_groups
719
+ self.num_vars = config.num_codevectors_per_group
720
+
721
+ if config.codevector_dim % self.num_groups != 0:
722
+ raise ValueError(
723
+ f"`config.codevector_dim {config.codevector_dim} must be divisible "
724
+ f"by `config.num_codevector_groups` {self.num_groups} for concatenation"
725
+ )
726
+
727
+ # storage for codebook variables (codewords)
728
+ self.codevectors = nn.Parameter(
729
+ torch.FloatTensor(1, self.num_groups * self.num_vars, config.codevector_dim // self.num_groups)
730
+ )
731
+ self.weight_proj = nn.Linear(config.conv_dim[-1], self.num_groups * self.num_vars)
732
+
733
+ # can be decayed for training
734
+ self.temperature = 2
735
+
736
+ @staticmethod
737
+ def _compute_perplexity(probs):
738
+ marginal_probs = probs.mean(dim=0)
739
+ perplexity = torch.exp(-torch.sum(marginal_probs * torch.log(marginal_probs + 1e-7), dim=-1)).sum()
740
+ return perplexity
741
+
742
+ def forward(self, hidden_states):
743
+ batch_size, sequence_length, hidden_size = hidden_states.shape
744
+
745
+ # project to codevector dim
746
+ hidden_states = self.weight_proj(hidden_states)
747
+ hidden_states = hidden_states.view(batch_size * sequence_length * self.num_groups, -1)
748
+
749
+ if self.training:
750
+ # sample code vector probs via gumbel in differentiateable way
751
+ codevector_probs = nn.functional.gumbel_softmax(
752
+ hidden_states.float(), tau=self.temperature, hard=True
753
+ ).type_as(hidden_states)
754
+
755
+ # compute perplexity
756
+ codevector_soft_dist = torch.softmax(
757
+ hidden_states.view(batch_size * sequence_length, self.num_groups, -1).float(), dim=-1
758
+ )
759
+ perplexity = self._compute_perplexity(codevector_soft_dist)
760
+ else:
761
+ # take argmax in non-differentiable way
762
+ # comptute hard codevector distribution (one hot)
763
+ codevector_idx = hidden_states.argmax(dim=-1)
764
+ codevector_probs = hidden_states.new_zeros(*hidden_states.shape).scatter_(
765
+ -1, codevector_idx.view(-1, 1), 1.0
766
+ )
767
+ codevector_probs = codevector_probs.view(batch_size * sequence_length, self.num_groups, -1)
768
+
769
+ perplexity = self._compute_perplexity(codevector_probs)
770
+
771
+ codevector_probs = codevector_probs.view(batch_size * sequence_length, -1)
772
+ # use probs to retrieve codevectors
773
+ codevectors_per_group = codevector_probs.unsqueeze(-1) * self.codevectors
774
+ codevectors = codevectors_per_group.view(batch_size * sequence_length, self.num_groups, self.num_vars, -1)
775
+ codevectors = codevectors.sum(-2).view(batch_size, sequence_length, -1)
776
+
777
+ return codevectors, perplexity
778
+
779
+
780
+ @auto_docstring
781
+ class UniSpeechPreTrainedModel(PreTrainedModel):
782
+ config: UniSpeechConfig
783
+ base_model_prefix = "unispeech"
784
+ main_input_name = "input_values"
785
+ supports_gradient_checkpointing = True
786
+ _supports_flash_attn = True
787
+ _supports_sdpa = True
788
+ _supports_flex_attn = True
789
+
790
+ def _init_weights(self, module):
791
+ """Initialize the weights"""
792
+ # gumbel softmax requires special init
793
+ if isinstance(module, UniSpeechGumbelVectorQuantizer):
794
+ module.weight_proj.weight.data.normal_(mean=0.0, std=1)
795
+ module.weight_proj.bias.data.zero_()
796
+ nn.init.uniform_(module.codevectors)
797
+ elif isinstance(module, UniSpeechPositionalConvEmbedding):
798
+ nn.init.normal_(
799
+ module.conv.weight,
800
+ mean=0,
801
+ std=2 * math.sqrt(1 / (module.conv.kernel_size[0] * module.conv.in_channels)),
802
+ )
803
+ nn.init.constant_(module.conv.bias, 0)
804
+ elif isinstance(module, UniSpeechFeatureProjection):
805
+ k = math.sqrt(1 / module.projection.in_features)
806
+ nn.init.uniform_(module.projection.weight, a=-k, b=k)
807
+ nn.init.uniform_(module.projection.bias, a=-k, b=k)
808
+ elif isinstance(module, nn.Linear):
809
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
810
+
811
+ if module.bias is not None:
812
+ module.bias.data.zero_()
813
+ elif isinstance(module, (nn.LayerNorm, nn.GroupNorm)):
814
+ module.bias.data.zero_()
815
+ module.weight.data.fill_(1.0)
816
+ elif isinstance(module, nn.Conv1d):
817
+ nn.init.kaiming_normal_(module.weight)
818
+
819
+ if module.bias is not None:
820
+ k = math.sqrt(module.groups / (module.in_channels * module.kernel_size[0]))
821
+ nn.init.uniform_(module.bias, a=-k, b=k)
822
+
823
+ def _get_feat_extract_output_lengths(self, input_lengths: Union[torch.LongTensor, int]):
824
+ """
825
+ Computes the output length of the convolutional layers
826
+ """
827
+
828
+ def _conv_out_length(input_length, kernel_size, stride):
829
+ # 1D convolutional layer output length formula taken
830
+ # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
831
+ return torch.div(input_length - kernel_size, stride, rounding_mode="floor") + 1
832
+
833
+ for kernel_size, stride in zip(self.config.conv_kernel, self.config.conv_stride):
834
+ input_lengths = _conv_out_length(input_lengths, kernel_size, stride)
835
+
836
+ return input_lengths
837
+
838
+ def _get_feature_vector_attention_mask(self, feature_vector_length: int, attention_mask: torch.LongTensor):
839
+ # Effectively attention_mask.sum(-1), but not inplace to be able to run
840
+ # on inference mode.
841
+ non_padded_lengths = attention_mask.cumsum(dim=-1)[:, -1]
842
+ output_lengths = self._get_feat_extract_output_lengths(non_padded_lengths).to(torch.long)
843
+ batch_size = attention_mask.shape[0]
844
+
845
+ attention_mask = torch.zeros(
846
+ (batch_size, feature_vector_length), dtype=attention_mask.dtype, device=attention_mask.device
847
+ )
848
+ # these two operations makes sure that all values before the output lengths idxs are attended to
849
+ attention_mask[(torch.arange(attention_mask.shape[0], device=attention_mask.device), output_lengths - 1)] = 1
850
+ attention_mask = attention_mask.flip([-1]).cumsum(-1).flip([-1]).bool()
851
+ return attention_mask
852
+
853
+
854
+ def _compute_mask_indices(
855
+ shape: tuple[int, int],
856
+ mask_prob: float,
857
+ mask_length: int,
858
+ attention_mask: Optional[torch.LongTensor] = None,
859
+ min_masks: int = 0,
860
+ ) -> np.ndarray:
861
+ """
862
+ Computes random mask spans for a given shape. Used to implement [SpecAugment: A Simple Data Augmentation Method for
863
+ ASR](https://huggingface.co/papers/1904.08779). Note that this method is not optimized to run on TPU and should be run on
864
+ CPU as part of the preprocessing during training.
865
+
866
+ Args:
867
+ shape: The shape for which to compute masks. This should be of a tuple of size 2 where
868
+ the first element is the batch size and the second element is the length of the axis to span.
869
+ mask_prob: The percentage of the whole axis (between 0 and 1) which will be masked. The number of
870
+ independently generated mask spans of length `mask_length` is computed by
871
+ `mask_prob*shape[1]/mask_length`. Note that due to overlaps, `mask_prob` is an upper bound and the
872
+ actual percentage will be smaller.
873
+ mask_length: size of the mask
874
+ min_masks: minimum number of masked spans
875
+ attention_mask: A (right-padded) attention mask which independently shortens the feature axis of
876
+ each batch dimension.
877
+ """
878
+ batch_size, sequence_length = shape
879
+
880
+ if mask_length < 1:
881
+ raise ValueError("`mask_length` has to be bigger than 0.")
882
+
883
+ if mask_length > sequence_length:
884
+ raise ValueError(
885
+ f"`mask_length` has to be smaller than `sequence_length`, but got `mask_length`: {mask_length}"
886
+ f" and `sequence_length`: {sequence_length}`"
887
+ )
888
+
889
+ # epsilon is used for probabilistic rounding
890
+ epsilon = np.random.rand(1).item()
891
+
892
+ def compute_num_masked_span(input_length):
893
+ """Given input length, compute how many spans should be masked"""
894
+ num_masked_span = int(mask_prob * input_length / mask_length + epsilon)
895
+ num_masked_span = max(num_masked_span, min_masks)
896
+
897
+ # make sure num masked span <= sequence_length
898
+ if num_masked_span * mask_length > sequence_length:
899
+ num_masked_span = sequence_length // mask_length
900
+
901
+ # make sure num_masked span is also <= input_length - (mask_length - 1)
902
+ if input_length - (mask_length - 1) < num_masked_span:
903
+ num_masked_span = max(input_length - (mask_length - 1), 0)
904
+
905
+ return num_masked_span
906
+
907
+ # compute number of masked spans in batch
908
+ input_lengths = (
909
+ attention_mask.detach().sum(-1).tolist()
910
+ if attention_mask is not None
911
+ else [sequence_length for _ in range(batch_size)]
912
+ )
913
+
914
+ # SpecAugment mask to fill
915
+ spec_aug_mask = np.zeros((batch_size, sequence_length), dtype=bool)
916
+ spec_aug_mask_idxs = []
917
+
918
+ max_num_masked_span = compute_num_masked_span(sequence_length)
919
+
920
+ if max_num_masked_span == 0:
921
+ return spec_aug_mask
922
+
923
+ for input_length in input_lengths:
924
+ # compute num of masked spans for this input
925
+ num_masked_span = compute_num_masked_span(input_length)
926
+
927
+ # get random indices to mask
928
+ spec_aug_mask_idx = np.random.choice(
929
+ np.arange(input_length - (mask_length - 1)), num_masked_span, replace=False
930
+ )
931
+
932
+ # pick first sampled index that will serve as a dummy index to pad vector
933
+ # to ensure same dimension for all batches due to probabilistic rounding
934
+ # Picking first sample just pads those vectors twice.
935
+ if len(spec_aug_mask_idx) == 0:
936
+ # this case can only happen if `input_length` is strictly smaller then
937
+ # `sequence_length` in which case the last token has to be a padding
938
+ # token which we can use as a dummy mask id
939
+ dummy_mask_idx = sequence_length - 1
940
+ else:
941
+ dummy_mask_idx = spec_aug_mask_idx[0]
942
+
943
+ spec_aug_mask_idx = np.concatenate(
944
+ [spec_aug_mask_idx, np.ones(max_num_masked_span - num_masked_span, dtype=np.int32) * dummy_mask_idx]
945
+ )
946
+ spec_aug_mask_idxs.append(spec_aug_mask_idx)
947
+
948
+ spec_aug_mask_idxs = np.array(spec_aug_mask_idxs)
949
+
950
+ # expand masked indices to masked spans
951
+ spec_aug_mask_idxs = np.broadcast_to(
952
+ spec_aug_mask_idxs[:, :, None], (batch_size, max_num_masked_span, mask_length)
953
+ )
954
+ spec_aug_mask_idxs = spec_aug_mask_idxs.reshape(batch_size, max_num_masked_span * mask_length)
955
+
956
+ # add offset to the starting indexes so that indexes now create a span
957
+ offsets = np.arange(mask_length)[None, None, :]
958
+ offsets = np.broadcast_to(offsets, (batch_size, max_num_masked_span, mask_length)).reshape(
959
+ batch_size, max_num_masked_span * mask_length
960
+ )
961
+ spec_aug_mask_idxs = spec_aug_mask_idxs + offsets
962
+
963
+ # ensure that we cannot have indices larger than sequence_length
964
+ if spec_aug_mask_idxs.max() > sequence_length - 1:
965
+ spec_aug_mask_idxs[spec_aug_mask_idxs > sequence_length - 1] = sequence_length - 1
966
+
967
+ # scatter indices to mask
968
+ np.put_along_axis(spec_aug_mask, spec_aug_mask_idxs, 1, -1)
969
+
970
+ return spec_aug_mask
971
+
972
+
973
+ UniSpeechBaseModelOutput = Wav2Vec2BaseModelOutput
974
+
975
+
976
+ @auto_docstring
977
+ class UniSpeechModel(UniSpeechPreTrainedModel):
978
+ def __init__(self, config: UniSpeechConfig):
979
+ super().__init__(config)
980
+ self.config = config
981
+ self.feature_extractor = UniSpeechFeatureEncoder(config)
982
+ self.feature_projection = UniSpeechFeatureProjection(config)
983
+
984
+ if config.mask_time_prob > 0.0 or config.mask_feature_prob > 0.0:
985
+ self.masked_spec_embed = nn.Parameter(torch.Tensor(config.hidden_size).uniform_())
986
+
987
+ if config.do_stable_layer_norm:
988
+ self.encoder = UniSpeechEncoderStableLayerNorm(config)
989
+ else:
990
+ self.encoder = UniSpeechEncoder(config)
991
+
992
+ # Initialize weights and apply final processing
993
+ self.post_init()
994
+
995
+ def _mask_hidden_states(
996
+ self,
997
+ hidden_states: torch.FloatTensor,
998
+ mask_time_indices: Optional[torch.FloatTensor] = None,
999
+ attention_mask: Optional[torch.LongTensor] = None,
1000
+ ):
1001
+ """
1002
+ Masks extracted features along time axis and/or along feature axis according to
1003
+ [SpecAugment](https://huggingface.co/papers/1904.08779).
1004
+ """
1005
+
1006
+ # `config.apply_spec_augment` can set masking to False
1007
+ if not getattr(self.config, "apply_spec_augment", True):
1008
+ return hidden_states
1009
+
1010
+ # generate indices & apply SpecAugment along time axis
1011
+ batch_size, sequence_length, hidden_size = hidden_states.size()
1012
+
1013
+ if mask_time_indices is not None:
1014
+ # apply SpecAugment along time axis with given mask_time_indices
1015
+ hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype)
1016
+ elif self.config.mask_time_prob > 0 and self.training:
1017
+ mask_time_indices = _compute_mask_indices(
1018
+ (batch_size, sequence_length),
1019
+ mask_prob=self.config.mask_time_prob,
1020
+ mask_length=self.config.mask_time_length,
1021
+ attention_mask=attention_mask,
1022
+ min_masks=self.config.mask_time_min_masks,
1023
+ )
1024
+ mask_time_indices = torch.tensor(mask_time_indices, device=hidden_states.device, dtype=torch.bool)
1025
+ hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype)
1026
+
1027
+ if self.config.mask_feature_prob > 0 and self.training:
1028
+ # generate indices & apply SpecAugment along feature axis
1029
+ mask_feature_indices = _compute_mask_indices(
1030
+ (batch_size, hidden_size),
1031
+ mask_prob=self.config.mask_feature_prob,
1032
+ mask_length=self.config.mask_feature_length,
1033
+ min_masks=self.config.mask_feature_min_masks,
1034
+ )
1035
+ mask_feature_indices = torch.tensor(mask_feature_indices, device=hidden_states.device, dtype=torch.bool)
1036
+ mask_feature_indices = mask_feature_indices[:, None].expand(-1, sequence_length, -1)
1037
+ hidden_states[mask_feature_indices] = 0
1038
+
1039
+ return hidden_states
1040
+
1041
+ @auto_docstring
1042
+ def forward(
1043
+ self,
1044
+ input_values: Optional[torch.Tensor],
1045
+ attention_mask: Optional[torch.Tensor] = None,
1046
+ mask_time_indices: Optional[torch.FloatTensor] = None,
1047
+ output_attentions: Optional[bool] = None,
1048
+ output_hidden_states: Optional[bool] = None,
1049
+ return_dict: Optional[bool] = None,
1050
+ ) -> Union[tuple, UniSpeechBaseModelOutput]:
1051
+ r"""
1052
+ mask_time_indices (`torch.BoolTensor` of shape `(batch_size, sequence_length)`, *optional*):
1053
+ Indices to mask extracted features for contrastive loss. When in training mode, model learns to predict
1054
+ masked extracted features in *config.proj_codevector_dim* space.
1055
+ """
1056
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1057
+ output_hidden_states = (
1058
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1059
+ )
1060
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1061
+
1062
+ extract_features = self.feature_extractor(input_values)
1063
+ extract_features = extract_features.transpose(1, 2)
1064
+
1065
+ if attention_mask is not None:
1066
+ # compute reduced attention_mask corresponding to feature vectors
1067
+ attention_mask = self._get_feature_vector_attention_mask(extract_features.shape[1], attention_mask)
1068
+
1069
+ hidden_states, extract_features = self.feature_projection(extract_features)
1070
+ hidden_states = self._mask_hidden_states(
1071
+ hidden_states, mask_time_indices=mask_time_indices, attention_mask=attention_mask
1072
+ )
1073
+
1074
+ encoder_outputs = self.encoder(
1075
+ hidden_states,
1076
+ attention_mask=attention_mask,
1077
+ output_attentions=output_attentions,
1078
+ output_hidden_states=output_hidden_states,
1079
+ return_dict=return_dict,
1080
+ )
1081
+
1082
+ hidden_states = encoder_outputs[0]
1083
+
1084
+ if not return_dict:
1085
+ return (hidden_states, extract_features) + encoder_outputs[1:]
1086
+
1087
+ return UniSpeechBaseModelOutput(
1088
+ last_hidden_state=hidden_states,
1089
+ extract_features=extract_features,
1090
+ hidden_states=encoder_outputs.hidden_states,
1091
+ attentions=encoder_outputs.attentions,
1092
+ )
1093
+
1094
+
1095
+ @auto_docstring(
1096
+ custom_intro="""
1097
+ UniSpeech Model with a vector-quantization module and ctc loss for pre-training.
1098
+ """
1099
+ )
1100
+ class UniSpeechForPreTraining(UniSpeechPreTrainedModel):
1101
+ def __init__(self, config: UniSpeechConfig):
1102
+ super().__init__(config)
1103
+ self.unispeech = UniSpeechModel(config)
1104
+ self.dropout_features = nn.Dropout(config.feat_quantizer_dropout)
1105
+
1106
+ self.quantizer = UniSpeechGumbelVectorQuantizer(config)
1107
+ self.project_q = nn.Linear(config.codevector_dim, config.proj_codevector_dim)
1108
+ self.project_hid = nn.Linear(config.proj_codevector_dim, config.hidden_size)
1109
+
1110
+ self.ctc_proj = nn.Linear(config.hidden_size, config.num_ctc_classes)
1111
+ self.dropout = nn.Dropout(config.final_dropout)
1112
+
1113
+ # Initialize weights and apply final processing
1114
+ self.post_init()
1115
+
1116
+ def set_gumbel_temperature(self, temperature: int):
1117
+ """
1118
+ Set the Gumbel softmax temperature to a given value. Only necessary for training
1119
+ """
1120
+ self.quantizer.temperature = temperature
1121
+
1122
+ def freeze_feature_extractor(self):
1123
+ """
1124
+ Calling this function will disable the gradient computation for the feature encoder so that its parameters will
1125
+ not be updated during training.
1126
+ """
1127
+ warnings.warn(
1128
+ "The method `freeze_feature_extractor` is deprecated and will be removed in Transformers v5. "
1129
+ "Please use the equivalent `freeze_feature_encoder` method instead.",
1130
+ FutureWarning,
1131
+ )
1132
+ self.freeze_feature_encoder()
1133
+
1134
+ def freeze_feature_encoder(self):
1135
+ """
1136
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
1137
+ not be updated during training.
1138
+ """
1139
+ self.unispeech.feature_extractor._freeze_parameters()
1140
+
1141
+ @staticmethod
1142
+ def compute_contrastive_logits(
1143
+ target_features: torch.FloatTensor,
1144
+ negative_features: torch.FloatTensor,
1145
+ predicted_features: torch.FloatTensor,
1146
+ temperature: int = 1,
1147
+ ):
1148
+ """
1149
+ Compute logits for contrastive loss based using cosine similarity as the distance measure between
1150
+ `[positive_feature, negative_features]` and `[predicted_features]`. Additionally, temperature can be applied.
1151
+ """
1152
+ target_features = torch.cat([target_features, negative_features], dim=0)
1153
+
1154
+ logits = torch.cosine_similarity(predicted_features.float(), target_features.float(), dim=-1)
1155
+ logits = logits.type_as(target_features)
1156
+
1157
+ # apply temperature
1158
+ logits = logits / temperature
1159
+ return logits
1160
+
1161
+ @auto_docstring
1162
+ def forward(
1163
+ self,
1164
+ input_values: Optional[torch.Tensor],
1165
+ attention_mask: Optional[torch.Tensor] = None,
1166
+ output_attentions: Optional[bool] = None,
1167
+ output_hidden_states: Optional[bool] = None,
1168
+ return_dict: Optional[bool] = None,
1169
+ ) -> Union[tuple, UniSpeechForPreTrainingOutput]:
1170
+ r"""
1171
+ Example:
1172
+
1173
+ ```python
1174
+ >>> import torch
1175
+ >>> from transformers import AutoFeatureExtractor, UniSpeechForPreTraining
1176
+
1177
+ >>> feature_extractor = AutoFeatureExtractor.from_pretrained("microsoft/unispeech-large-1500h-cv")
1178
+ >>> model = UniSpeechForPreTraining.from_pretrained("microsoft/unispeech-large-1500h-cv")
1179
+ >>> # TODO: Add full pretraining example
1180
+ ```"""
1181
+
1182
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1183
+
1184
+ outputs = self.unispeech(
1185
+ input_values,
1186
+ attention_mask=attention_mask,
1187
+ output_attentions=output_attentions,
1188
+ output_hidden_states=output_hidden_states,
1189
+ return_dict=return_dict,
1190
+ )
1191
+ transformer_features = outputs[0]
1192
+
1193
+ # quantize all (unmasked) extracted features and project to final vq dim
1194
+ extract_features = self.dropout_features(outputs[1])
1195
+ quantized_features, codevector_perplexity = self.quantizer(extract_features)
1196
+
1197
+ # project quantized features twice
1198
+ quantized_features = self.project_q(quantized_features.to(self.project_q.weight.dtype))
1199
+ quantized_features = self.project_hid(quantized_features)
1200
+
1201
+ prob_replace_matrix = torch.empty(transformer_features.size(0), transformer_features.size(1)).fill_(
1202
+ self.config.replace_prob
1203
+ )
1204
+ prob_replace_matrix = prob_replace_matrix.transpose(0, 1)
1205
+ sampled_replace_matrix = torch.bernoulli(prob_replace_matrix).bool().to(transformer_features.device)
1206
+ sampled_replace_matrix = sampled_replace_matrix.transpose(0, 1)
1207
+ sampled_replace_matrix = sampled_replace_matrix.unsqueeze(-1)
1208
+ logits = transformer_features.masked_fill(sampled_replace_matrix, 0.0) + (
1209
+ quantized_features.masked_fill(~sampled_replace_matrix, 0.0)
1210
+ )
1211
+
1212
+ # project to ctc units
1213
+ logits = self.dropout(logits)
1214
+ logits = self.ctc_proj(logits)
1215
+
1216
+ # TODO(PVP) - add negative sampling & loss computation
1217
+ loss = None
1218
+ if not return_dict:
1219
+ if loss is not None:
1220
+ return (loss, transformer_features, quantized_features, codevector_perplexity) + outputs[2:]
1221
+ return (transformer_features, quantized_features, codevector_perplexity) + outputs[2:]
1222
+
1223
+ return UniSpeechForPreTrainingOutput(
1224
+ loss=loss,
1225
+ projected_states=transformer_features,
1226
+ projected_quantized_states=quantized_features,
1227
+ codevector_perplexity=codevector_perplexity,
1228
+ hidden_states=outputs.hidden_states,
1229
+ attentions=outputs.attentions,
1230
+ )
1231
+
1232
+
1233
+ _HIDDEN_STATES_START_POSITION = 2
1234
+
1235
+
1236
+ @auto_docstring(
1237
+ custom_intro="""
1238
+ UniSpeech Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).
1239
+ """
1240
+ )
1241
+ class UniSpeechForCTC(UniSpeechPreTrainedModel):
1242
+ def __init__(self, config, target_lang: Optional[str] = None):
1243
+ r"""
1244
+ target_lang (`str`, *optional*):
1245
+ Language id of adapter weights. Adapter weights are stored in the format adapter.<lang>.safetensors or
1246
+ adapter.<lang>.bin. Only relevant when using an instance of [`UniSpeechForCTC`] with adapters. Uses 'eng' by
1247
+ default.
1248
+ """
1249
+ super().__init__(config)
1250
+
1251
+ self.unispeech = UniSpeechModel(config)
1252
+ self.dropout = nn.Dropout(config.final_dropout)
1253
+
1254
+ self.target_lang = target_lang
1255
+
1256
+ if config.vocab_size is None:
1257
+ raise ValueError(
1258
+ f"You are trying to instantiate {self.__class__} with a configuration that "
1259
+ "does not define the vocabulary size of the language model head. Please "
1260
+ "instantiate the model as follows: `UniSpeechForCTC.from_pretrained(..., vocab_size=vocab_size)`. "
1261
+ "or define `vocab_size` of your model's configuration."
1262
+ )
1263
+ output_hidden_size = (
1264
+ config.output_hidden_size if hasattr(config, "add_adapter") and config.add_adapter else config.hidden_size
1265
+ )
1266
+ self.lm_head = nn.Linear(output_hidden_size, config.vocab_size)
1267
+
1268
+ # Initialize weights and apply final processing
1269
+ self.post_init()
1270
+
1271
+ def tie_weights(self):
1272
+ """
1273
+ This method overwrites [`~PreTrainedModel.tie_weights`] so that adapter weights can be correctly loaded when
1274
+ passing `target_lang=...` to `from_pretrained(...)`.
1275
+
1276
+ This method is **not** supposed to be called by the user and is prone to be changed in the future.
1277
+ """
1278
+
1279
+ # Note that `tie_weights` is usually used to tie input and output embedding weights. The method is re-purposed to
1280
+ # correctly load adapter layers for UniSpeech so that we do not have to introduce a new API to
1281
+ # [`PreTrainedModel`]. While slightly hacky, UniSpeech never has to tie input and output embeddings, so that it is
1282
+ # ok to repurpose this function here.
1283
+ target_lang = self.target_lang
1284
+
1285
+ if target_lang is not None and getattr(self.config, "adapter_attn_dim", None) is None:
1286
+ raise ValueError(f"Cannot pass `target_lang`: {target_lang} if `config.adapter_attn_dim` is not defined.")
1287
+ elif target_lang is None and getattr(self.config, "adapter_attn_dim", None) is not None:
1288
+ logger.info("By default `target_lang` is set to 'eng'.")
1289
+ elif target_lang is not None:
1290
+ self.load_adapter(target_lang, force_load=True)
1291
+
1292
+ def freeze_feature_extractor(self):
1293
+ """
1294
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
1295
+ not be updated during training.
1296
+ """
1297
+ warnings.warn(
1298
+ "The method `freeze_feature_extractor` is deprecated and will be removed in Transformers v5. "
1299
+ "Please use the equivalent `freeze_feature_encoder` method instead.",
1300
+ FutureWarning,
1301
+ )
1302
+ self.freeze_feature_encoder()
1303
+
1304
+ def freeze_feature_encoder(self):
1305
+ """
1306
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
1307
+ not be updated during training.
1308
+ """
1309
+ self.unispeech.feature_extractor._freeze_parameters()
1310
+
1311
+ def freeze_base_model(self):
1312
+ """
1313
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
1314
+ be updated during training. Only the classification head will be updated.
1315
+ """
1316
+ for param in self.unispeech.parameters():
1317
+ param.requires_grad = False
1318
+
1319
+ @auto_docstring
1320
+ def forward(
1321
+ self,
1322
+ input_values: Optional[torch.Tensor],
1323
+ attention_mask: Optional[torch.Tensor] = None,
1324
+ output_attentions: Optional[bool] = None,
1325
+ output_hidden_states: Optional[bool] = None,
1326
+ return_dict: Optional[bool] = None,
1327
+ labels: Optional[torch.Tensor] = None,
1328
+ ) -> Union[tuple, CausalLMOutput]:
1329
+ r"""
1330
+ labels (`torch.LongTensor` of shape `(batch_size, target_length)`, *optional*):
1331
+ Labels for connectionist temporal classification. Note that `target_length` has to be smaller or equal to
1332
+ the sequence length of the output logits. Indices are selected in `[-100, 0, ..., config.vocab_size - 1]`.
1333
+ All labels set to `-100` are ignored (masked), the loss is only computed for labels in `[0, ...,
1334
+ config.vocab_size - 1]`.
1335
+ """
1336
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1337
+
1338
+ if labels is not None and labels.max() >= self.config.vocab_size:
1339
+ raise ValueError(f"Label values must be <= vocab_size: {self.config.vocab_size}")
1340
+
1341
+ outputs = self.unispeech(
1342
+ input_values,
1343
+ attention_mask=attention_mask,
1344
+ output_attentions=output_attentions,
1345
+ output_hidden_states=output_hidden_states,
1346
+ return_dict=return_dict,
1347
+ )
1348
+
1349
+ hidden_states = outputs[0]
1350
+ hidden_states = self.dropout(hidden_states)
1351
+
1352
+ logits = self.lm_head(hidden_states)
1353
+
1354
+ loss = None
1355
+ if labels is not None:
1356
+ # retrieve loss input_lengths from attention_mask
1357
+ attention_mask = (
1358
+ attention_mask if attention_mask is not None else torch.ones_like(input_values, dtype=torch.long)
1359
+ )
1360
+ input_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(-1)).to(torch.long)
1361
+
1362
+ # assuming that padded tokens are filled with -100
1363
+ # when not being attended to
1364
+ labels_mask = labels >= 0
1365
+ target_lengths = labels_mask.sum(-1)
1366
+ flattened_targets = labels.masked_select(labels_mask)
1367
+
1368
+ # ctc_loss doesn't support fp16
1369
+ log_probs = nn.functional.log_softmax(logits, dim=-1, dtype=torch.float32).transpose(0, 1)
1370
+
1371
+ with torch.backends.cudnn.flags(enabled=False):
1372
+ loss = nn.functional.ctc_loss(
1373
+ log_probs,
1374
+ flattened_targets,
1375
+ input_lengths,
1376
+ target_lengths,
1377
+ blank=self.config.pad_token_id,
1378
+ reduction=self.config.ctc_loss_reduction,
1379
+ zero_infinity=self.config.ctc_zero_infinity,
1380
+ )
1381
+
1382
+ if not return_dict:
1383
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
1384
+ return ((loss,) + output) if loss is not None else output
1385
+
1386
+ return CausalLMOutput(
1387
+ loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions
1388
+ )
1389
+
1390
+
1391
+ @auto_docstring(
1392
+ custom_intro="""
1393
+ UniSpeech Model with a sequence classification head on top (a linear layer over the pooled output) for tasks like
1394
+ SUPERB Keyword Spotting.
1395
+ """
1396
+ )
1397
+ class UniSpeechForSequenceClassification(UniSpeechPreTrainedModel):
1398
+ def __init__(self, config):
1399
+ super().__init__(config)
1400
+
1401
+ if hasattr(config, "add_adapter") and config.add_adapter:
1402
+ raise ValueError(
1403
+ "Sequence classification does not support the use of UniSpeech adapters (config.add_adapter=True)"
1404
+ )
1405
+ self.unispeech = UniSpeechModel(config)
1406
+ num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings
1407
+ if config.use_weighted_layer_sum:
1408
+ self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)
1409
+ self.projector = nn.Linear(config.hidden_size, config.classifier_proj_size)
1410
+ self.classifier = nn.Linear(config.classifier_proj_size, config.num_labels)
1411
+
1412
+ # Initialize weights and apply final processing
1413
+ self.post_init()
1414
+
1415
+ def freeze_feature_extractor(self):
1416
+ """
1417
+ Calling this function will disable the gradient computation for the feature encoder so that its parameters will
1418
+ not be updated during training.
1419
+ """
1420
+ warnings.warn(
1421
+ "The method `freeze_feature_extractor` is deprecated and will be removed in Transformers v5. "
1422
+ "Please use the equivalent `freeze_feature_encoder` method instead.",
1423
+ FutureWarning,
1424
+ )
1425
+ self.freeze_feature_encoder()
1426
+
1427
+ def freeze_feature_encoder(self):
1428
+ """
1429
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
1430
+ not be updated during training.
1431
+ """
1432
+ self.unispeech.feature_extractor._freeze_parameters()
1433
+
1434
+ def freeze_base_model(self):
1435
+ """
1436
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
1437
+ be updated during training. Only the classification head will be updated.
1438
+ """
1439
+ for param in self.unispeech.parameters():
1440
+ param.requires_grad = False
1441
+
1442
+ @auto_docstring
1443
+ def forward(
1444
+ self,
1445
+ input_values: Optional[torch.Tensor],
1446
+ attention_mask: Optional[torch.Tensor] = None,
1447
+ output_attentions: Optional[bool] = None,
1448
+ output_hidden_states: Optional[bool] = None,
1449
+ return_dict: Optional[bool] = None,
1450
+ labels: Optional[torch.Tensor] = None,
1451
+ ) -> Union[tuple, SequenceClassifierOutput]:
1452
+ r"""
1453
+ input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
1454
+ Float values of input raw speech waveform. Values can be obtained by loading a `.flac` or `.wav` audio file
1455
+ into an array of type `list[float]`, a `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library
1456
+ (`pip install torchcodec`) or the soundfile library (`pip install soundfile`).
1457
+ To prepare the array into `input_values`, the [`AutoProcessor`] should be used for padding and conversion
1458
+ into a tensor of type `torch.FloatTensor`. See [`UniSpeechProcessor.__call__`] for details.
1459
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1460
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1461
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1462
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1463
+ """
1464
+
1465
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1466
+ output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
1467
+
1468
+ outputs = self.unispeech(
1469
+ input_values,
1470
+ attention_mask=attention_mask,
1471
+ output_attentions=output_attentions,
1472
+ output_hidden_states=output_hidden_states,
1473
+ return_dict=return_dict,
1474
+ )
1475
+
1476
+ if self.config.use_weighted_layer_sum:
1477
+ hidden_states = outputs[_HIDDEN_STATES_START_POSITION]
1478
+ hidden_states = torch.stack(hidden_states, dim=1)
1479
+ norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
1480
+ hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
1481
+ else:
1482
+ hidden_states = outputs[0]
1483
+
1484
+ hidden_states = self.projector(hidden_states)
1485
+ if attention_mask is None:
1486
+ pooled_output = hidden_states.mean(dim=1)
1487
+ else:
1488
+ padding_mask = self._get_feature_vector_attention_mask(hidden_states.shape[1], attention_mask)
1489
+ expand_padding_mask = padding_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
1490
+ hidden_states[~expand_padding_mask] = 0.0
1491
+ pooled_output = hidden_states.sum(dim=1) / padding_mask.sum(dim=1).view(-1, 1)
1492
+
1493
+ logits = self.classifier(pooled_output)
1494
+
1495
+ loss = None
1496
+ if labels is not None:
1497
+ loss_fct = CrossEntropyLoss()
1498
+ loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
1499
+
1500
+ if not return_dict:
1501
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
1502
+ return ((loss,) + output) if loss is not None else output
1503
+
1504
+ return SequenceClassifierOutput(
1505
+ loss=loss,
1506
+ logits=logits,
1507
+ hidden_states=outputs.hidden_states,
1508
+ attentions=outputs.attentions,
1509
+ )
1510
+
1511
+
1512
+ __all__ = [
1513
+ "UniSpeechForCTC",
1514
+ "UniSpeechForPreTraining",
1515
+ "UniSpeechForSequenceClassification",
1516
+ "UniSpeechModel",
1517
+ "UniSpeechPreTrainedModel",
1518
+ ]
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/unispeech/modular_unispeech.py ADDED
@@ -0,0 +1,445 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The Fairseq Authors and the HuggingFace Inc. team. 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
+ """PyTorch UniSpeech model."""
16
+
17
+ import math
18
+ import warnings
19
+ from dataclasses import dataclass
20
+ from typing import Optional, Union
21
+
22
+ import torch
23
+ import torch.nn as nn
24
+
25
+ from ...modeling_outputs import ModelOutput, Wav2Vec2BaseModelOutput
26
+ from ...modeling_utils import PreTrainedModel
27
+ from ...utils import auto_docstring, logging
28
+ from ..wav2vec2.modeling_wav2vec2 import (
29
+ Wav2Vec2Encoder,
30
+ Wav2Vec2EncoderStableLayerNorm,
31
+ Wav2Vec2FeatureEncoder,
32
+ Wav2Vec2FeatureProjection,
33
+ Wav2Vec2ForCTC,
34
+ Wav2Vec2ForSequenceClassification,
35
+ Wav2Vec2GumbelVectorQuantizer,
36
+ Wav2Vec2Model,
37
+ Wav2Vec2PositionalConvEmbedding,
38
+ )
39
+ from .configuration_unispeech import UniSpeechConfig
40
+
41
+
42
+ logger = logging.get_logger(__name__)
43
+
44
+
45
+ @dataclass
46
+ @auto_docstring(
47
+ custom_intro="""
48
+ Output type of [`UniSpeechForPreTrainingOutput`], with potential hidden states and attentions.
49
+ """
50
+ )
51
+ class UniSpeechForPreTrainingOutput(ModelOutput):
52
+ r"""
53
+ loss (*optional*, returned when model is in train mode, `torch.FloatTensor` of shape `(1,)`):
54
+ Total loss as the sum of the contrastive loss (L_m) and the diversity loss (L_d) as stated in the [official
55
+ paper](https://arxiv.org/pdf/2006.11477.pdf) . (classification) loss.
56
+ projected_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.proj_codevector_dim)`):
57
+ Hidden-states of the model projected to *config.proj_codevector_dim* that can be used to predict the masked
58
+ projected quantized states.
59
+ projected_quantized_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.proj_codevector_dim)`):
60
+ Quantized extracted feature vectors projected to *config.proj_codevector_dim* representing the positive
61
+ target vectors for contrastive loss.
62
+ codevector_perplexity (`torch.FloatTensor` of shape `(1,)`):
63
+ The perplexity of the codevector distribution, used to measure the diversity of the codebook.
64
+ """
65
+
66
+ loss: Optional[torch.FloatTensor] = None
67
+ projected_states: Optional[torch.FloatTensor] = None
68
+ projected_quantized_states: Optional[torch.FloatTensor] = None
69
+ codevector_perplexity: Optional[torch.FloatTensor] = None
70
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
71
+ attentions: Optional[tuple[torch.FloatTensor]] = None
72
+
73
+
74
+ class UniSpeechPositionalConvEmbedding(Wav2Vec2PositionalConvEmbedding):
75
+ pass
76
+
77
+
78
+ class UniSpeechFeatureEncoder(Wav2Vec2FeatureEncoder):
79
+ pass
80
+
81
+
82
+ class UniSpeechFeatureProjection(Wav2Vec2FeatureProjection):
83
+ pass
84
+
85
+
86
+ class UniSpeechEncoder(Wav2Vec2Encoder):
87
+ pass
88
+
89
+
90
+ class UniSpeechEncoderStableLayerNorm(Wav2Vec2EncoderStableLayerNorm):
91
+ pass
92
+
93
+
94
+ class UniSpeechGumbelVectorQuantizer(Wav2Vec2GumbelVectorQuantizer):
95
+ @staticmethod
96
+ def _compute_perplexity(probs):
97
+ marginal_probs = probs.mean(dim=0)
98
+ perplexity = torch.exp(-torch.sum(marginal_probs * torch.log(marginal_probs + 1e-7), dim=-1)).sum()
99
+ return perplexity
100
+
101
+ def forward(self, hidden_states):
102
+ batch_size, sequence_length, hidden_size = hidden_states.shape
103
+
104
+ # project to codevector dim
105
+ hidden_states = self.weight_proj(hidden_states)
106
+ hidden_states = hidden_states.view(batch_size * sequence_length * self.num_groups, -1)
107
+
108
+ if self.training:
109
+ # sample code vector probs via gumbel in differentiateable way
110
+ codevector_probs = nn.functional.gumbel_softmax(
111
+ hidden_states.float(), tau=self.temperature, hard=True
112
+ ).type_as(hidden_states)
113
+
114
+ # compute perplexity
115
+ codevector_soft_dist = torch.softmax(
116
+ hidden_states.view(batch_size * sequence_length, self.num_groups, -1).float(), dim=-1
117
+ )
118
+ perplexity = self._compute_perplexity(codevector_soft_dist)
119
+ else:
120
+ # take argmax in non-differentiable way
121
+ # comptute hard codevector distribution (one hot)
122
+ codevector_idx = hidden_states.argmax(dim=-1)
123
+ codevector_probs = hidden_states.new_zeros(*hidden_states.shape).scatter_(
124
+ -1, codevector_idx.view(-1, 1), 1.0
125
+ )
126
+ codevector_probs = codevector_probs.view(batch_size * sequence_length, self.num_groups, -1)
127
+
128
+ perplexity = self._compute_perplexity(codevector_probs)
129
+
130
+ codevector_probs = codevector_probs.view(batch_size * sequence_length, -1)
131
+ # use probs to retrieve codevectors
132
+ codevectors_per_group = codevector_probs.unsqueeze(-1) * self.codevectors
133
+ codevectors = codevectors_per_group.view(batch_size * sequence_length, self.num_groups, self.num_vars, -1)
134
+ codevectors = codevectors.sum(-2).view(batch_size, sequence_length, -1)
135
+
136
+ return codevectors, perplexity
137
+
138
+
139
+ @auto_docstring
140
+ class UniSpeechPreTrainedModel(PreTrainedModel):
141
+ config: UniSpeechConfig
142
+ base_model_prefix = "unispeech"
143
+ main_input_name = "input_values"
144
+ supports_gradient_checkpointing = True
145
+ _supports_flash_attn = True
146
+ _supports_sdpa = True
147
+ _supports_flex_attn = True
148
+
149
+ def _init_weights(self, module):
150
+ """Initialize the weights"""
151
+ # gumbel softmax requires special init
152
+ if isinstance(module, UniSpeechGumbelVectorQuantizer):
153
+ module.weight_proj.weight.data.normal_(mean=0.0, std=1)
154
+ module.weight_proj.bias.data.zero_()
155
+ nn.init.uniform_(module.codevectors)
156
+ elif isinstance(module, UniSpeechPositionalConvEmbedding):
157
+ nn.init.normal_(
158
+ module.conv.weight,
159
+ mean=0,
160
+ std=2 * math.sqrt(1 / (module.conv.kernel_size[0] * module.conv.in_channels)),
161
+ )
162
+ nn.init.constant_(module.conv.bias, 0)
163
+ elif isinstance(module, UniSpeechFeatureProjection):
164
+ k = math.sqrt(1 / module.projection.in_features)
165
+ nn.init.uniform_(module.projection.weight, a=-k, b=k)
166
+ nn.init.uniform_(module.projection.bias, a=-k, b=k)
167
+ elif isinstance(module, nn.Linear):
168
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
169
+
170
+ if module.bias is not None:
171
+ module.bias.data.zero_()
172
+ elif isinstance(module, (nn.LayerNorm, nn.GroupNorm)):
173
+ module.bias.data.zero_()
174
+ module.weight.data.fill_(1.0)
175
+ elif isinstance(module, nn.Conv1d):
176
+ nn.init.kaiming_normal_(module.weight)
177
+
178
+ if module.bias is not None:
179
+ k = math.sqrt(module.groups / (module.in_channels * module.kernel_size[0]))
180
+ nn.init.uniform_(module.bias, a=-k, b=k)
181
+
182
+ def _get_feat_extract_output_lengths(self, input_lengths: Union[torch.LongTensor, int]):
183
+ """
184
+ Computes the output length of the convolutional layers
185
+ """
186
+
187
+ def _conv_out_length(input_length, kernel_size, stride):
188
+ # 1D convolutional layer output length formula taken
189
+ # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
190
+ return torch.div(input_length - kernel_size, stride, rounding_mode="floor") + 1
191
+
192
+ for kernel_size, stride in zip(self.config.conv_kernel, self.config.conv_stride):
193
+ input_lengths = _conv_out_length(input_lengths, kernel_size, stride)
194
+
195
+ return input_lengths
196
+
197
+ def _get_feature_vector_attention_mask(self, feature_vector_length: int, attention_mask: torch.LongTensor):
198
+ # Effectively attention_mask.sum(-1), but not inplace to be able to run
199
+ # on inference mode.
200
+ non_padded_lengths = attention_mask.cumsum(dim=-1)[:, -1]
201
+ output_lengths = self._get_feat_extract_output_lengths(non_padded_lengths).to(torch.long)
202
+ batch_size = attention_mask.shape[0]
203
+
204
+ attention_mask = torch.zeros(
205
+ (batch_size, feature_vector_length), dtype=attention_mask.dtype, device=attention_mask.device
206
+ )
207
+ # these two operations makes sure that all values before the output lengths idxs are attended to
208
+ attention_mask[(torch.arange(attention_mask.shape[0], device=attention_mask.device), output_lengths - 1)] = 1
209
+ attention_mask = attention_mask.flip([-1]).cumsum(-1).flip([-1]).bool()
210
+ return attention_mask
211
+
212
+
213
+ UniSpeechBaseModelOutput = Wav2Vec2BaseModelOutput
214
+
215
+
216
+ class UniSpeechModel(UniSpeechPreTrainedModel, Wav2Vec2Model):
217
+ def __init__(self, config: UniSpeechConfig):
218
+ UniSpeechPreTrainedModel.__init__(config)
219
+ self.config = config
220
+ self.feature_extractor = UniSpeechFeatureEncoder(config)
221
+ self.feature_projection = UniSpeechFeatureProjection(config)
222
+
223
+ if config.mask_time_prob > 0.0 or config.mask_feature_prob > 0.0:
224
+ self.masked_spec_embed = nn.Parameter(torch.Tensor(config.hidden_size).uniform_())
225
+
226
+ if config.do_stable_layer_norm:
227
+ self.encoder = UniSpeechEncoderStableLayerNorm(config)
228
+ else:
229
+ self.encoder = UniSpeechEncoder(config)
230
+
231
+ # Initialize weights and apply final processing
232
+ self.post_init()
233
+
234
+ def freeze_feature_extractor(self):
235
+ raise AttributeError("Not needed for UniSpeech")
236
+
237
+ def freeze_feature_encoder(self):
238
+ raise AttributeError("Not needed for UniSpeech")
239
+
240
+ def forward(
241
+ self,
242
+ input_values: Optional[torch.Tensor],
243
+ attention_mask: Optional[torch.Tensor] = None,
244
+ mask_time_indices: Optional[torch.FloatTensor] = None,
245
+ output_attentions: Optional[bool] = None,
246
+ output_hidden_states: Optional[bool] = None,
247
+ return_dict: Optional[bool] = None,
248
+ ) -> Union[tuple, UniSpeechBaseModelOutput]:
249
+ r"""
250
+ mask_time_indices (`torch.BoolTensor` of shape `(batch_size, sequence_length)`, *optional*):
251
+ Indices to mask extracted features for contrastive loss. When in training mode, model learns to predict
252
+ masked extracted features in *config.proj_codevector_dim* space.
253
+ """
254
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
255
+ output_hidden_states = (
256
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
257
+ )
258
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
259
+
260
+ extract_features = self.feature_extractor(input_values)
261
+ extract_features = extract_features.transpose(1, 2)
262
+
263
+ if attention_mask is not None:
264
+ # compute reduced attention_mask corresponding to feature vectors
265
+ attention_mask = self._get_feature_vector_attention_mask(extract_features.shape[1], attention_mask)
266
+
267
+ hidden_states, extract_features = self.feature_projection(extract_features)
268
+ hidden_states = self._mask_hidden_states(
269
+ hidden_states, mask_time_indices=mask_time_indices, attention_mask=attention_mask
270
+ )
271
+
272
+ encoder_outputs = self.encoder(
273
+ hidden_states,
274
+ attention_mask=attention_mask,
275
+ output_attentions=output_attentions,
276
+ output_hidden_states=output_hidden_states,
277
+ return_dict=return_dict,
278
+ )
279
+
280
+ hidden_states = encoder_outputs[0]
281
+
282
+ if not return_dict:
283
+ return (hidden_states, extract_features) + encoder_outputs[1:]
284
+
285
+ return UniSpeechBaseModelOutput(
286
+ last_hidden_state=hidden_states,
287
+ extract_features=extract_features,
288
+ hidden_states=encoder_outputs.hidden_states,
289
+ attentions=encoder_outputs.attentions,
290
+ )
291
+
292
+
293
+ @auto_docstring(
294
+ custom_intro="""
295
+ UniSpeech Model with a vector-quantization module and ctc loss for pre-training.
296
+ """
297
+ )
298
+ class UniSpeechForPreTraining(UniSpeechPreTrainedModel):
299
+ def __init__(self, config: UniSpeechConfig):
300
+ super().__init__(config)
301
+ self.unispeech = UniSpeechModel(config)
302
+ self.dropout_features = nn.Dropout(config.feat_quantizer_dropout)
303
+
304
+ self.quantizer = UniSpeechGumbelVectorQuantizer(config)
305
+ self.project_q = nn.Linear(config.codevector_dim, config.proj_codevector_dim)
306
+ self.project_hid = nn.Linear(config.proj_codevector_dim, config.hidden_size)
307
+
308
+ self.ctc_proj = nn.Linear(config.hidden_size, config.num_ctc_classes)
309
+ self.dropout = nn.Dropout(config.final_dropout)
310
+
311
+ # Initialize weights and apply final processing
312
+ self.post_init()
313
+
314
+ def set_gumbel_temperature(self, temperature: int):
315
+ """
316
+ Set the Gumbel softmax temperature to a given value. Only necessary for training
317
+ """
318
+ self.quantizer.temperature = temperature
319
+
320
+ def freeze_feature_extractor(self):
321
+ """
322
+ Calling this function will disable the gradient computation for the feature encoder so that its parameters will
323
+ not be updated during training.
324
+ """
325
+ warnings.warn(
326
+ "The method `freeze_feature_extractor` is deprecated and will be removed in Transformers v5. "
327
+ "Please use the equivalent `freeze_feature_encoder` method instead.",
328
+ FutureWarning,
329
+ )
330
+ self.freeze_feature_encoder()
331
+
332
+ def freeze_feature_encoder(self):
333
+ """
334
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
335
+ not be updated during training.
336
+ """
337
+ self.unispeech.feature_extractor._freeze_parameters()
338
+
339
+ @staticmethod
340
+ def compute_contrastive_logits(
341
+ target_features: torch.FloatTensor,
342
+ negative_features: torch.FloatTensor,
343
+ predicted_features: torch.FloatTensor,
344
+ temperature: int = 1,
345
+ ):
346
+ """
347
+ Compute logits for contrastive loss based using cosine similarity as the distance measure between
348
+ `[positive_feature, negative_features]` and `[predicted_features]`. Additionally, temperature can be applied.
349
+ """
350
+ target_features = torch.cat([target_features, negative_features], dim=0)
351
+
352
+ logits = torch.cosine_similarity(predicted_features.float(), target_features.float(), dim=-1)
353
+ logits = logits.type_as(target_features)
354
+
355
+ # apply temperature
356
+ logits = logits / temperature
357
+ return logits
358
+
359
+ @auto_docstring
360
+ def forward(
361
+ self,
362
+ input_values: Optional[torch.Tensor],
363
+ attention_mask: Optional[torch.Tensor] = None,
364
+ output_attentions: Optional[bool] = None,
365
+ output_hidden_states: Optional[bool] = None,
366
+ return_dict: Optional[bool] = None,
367
+ ) -> Union[tuple, UniSpeechForPreTrainingOutput]:
368
+ r"""
369
+ Example:
370
+
371
+ ```python
372
+ >>> import torch
373
+ >>> from transformers import AutoFeatureExtractor, UniSpeechForPreTraining
374
+
375
+ >>> feature_extractor = AutoFeatureExtractor.from_pretrained("microsoft/unispeech-large-1500h-cv")
376
+ >>> model = UniSpeechForPreTraining.from_pretrained("microsoft/unispeech-large-1500h-cv")
377
+ >>> # TODO: Add full pretraining example
378
+ ```"""
379
+
380
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
381
+
382
+ outputs = self.unispeech(
383
+ input_values,
384
+ attention_mask=attention_mask,
385
+ output_attentions=output_attentions,
386
+ output_hidden_states=output_hidden_states,
387
+ return_dict=return_dict,
388
+ )
389
+ transformer_features = outputs[0]
390
+
391
+ # quantize all (unmasked) extracted features and project to final vq dim
392
+ extract_features = self.dropout_features(outputs[1])
393
+ quantized_features, codevector_perplexity = self.quantizer(extract_features)
394
+
395
+ # project quantized features twice
396
+ quantized_features = self.project_q(quantized_features.to(self.project_q.weight.dtype))
397
+ quantized_features = self.project_hid(quantized_features)
398
+
399
+ prob_replace_matrix = torch.empty(transformer_features.size(0), transformer_features.size(1)).fill_(
400
+ self.config.replace_prob
401
+ )
402
+ prob_replace_matrix = prob_replace_matrix.transpose(0, 1)
403
+ sampled_replace_matrix = torch.bernoulli(prob_replace_matrix).bool().to(transformer_features.device)
404
+ sampled_replace_matrix = sampled_replace_matrix.transpose(0, 1)
405
+ sampled_replace_matrix = sampled_replace_matrix.unsqueeze(-1)
406
+ logits = transformer_features.masked_fill(sampled_replace_matrix, 0.0) + (
407
+ quantized_features.masked_fill(~sampled_replace_matrix, 0.0)
408
+ )
409
+
410
+ # project to ctc units
411
+ logits = self.dropout(logits)
412
+ logits = self.ctc_proj(logits)
413
+
414
+ # TODO(PVP) - add negative sampling & loss computation
415
+ loss = None
416
+ if not return_dict:
417
+ if loss is not None:
418
+ return (loss, transformer_features, quantized_features, codevector_perplexity) + outputs[2:]
419
+ return (transformer_features, quantized_features, codevector_perplexity) + outputs[2:]
420
+
421
+ return UniSpeechForPreTrainingOutput(
422
+ loss=loss,
423
+ projected_states=transformer_features,
424
+ projected_quantized_states=quantized_features,
425
+ codevector_perplexity=codevector_perplexity,
426
+ hidden_states=outputs.hidden_states,
427
+ attentions=outputs.attentions,
428
+ )
429
+
430
+
431
+ class UniSpeechForCTC(Wav2Vec2ForCTC):
432
+ pass
433
+
434
+
435
+ class UniSpeechForSequenceClassification(Wav2Vec2ForSequenceClassification):
436
+ pass
437
+
438
+
439
+ __all__ = [
440
+ "UniSpeechForCTC",
441
+ "UniSpeechForPreTraining",
442
+ "UniSpeechForSequenceClassification",
443
+ "UniSpeechModel",
444
+ "UniSpeechPreTrainedModel",
445
+ ]
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/unispeech_sat/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. 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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_unispeech_sat import *
22
+ from .modeling_unispeech_sat import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/unispeech_sat/configuration_unispeech_sat.py ADDED
@@ -0,0 +1,327 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The Fairseq Authors and The HuggingFace Inc. team. 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
+ """UniSpeechSat model configuration"""
16
+
17
+ import functools
18
+ import operator
19
+
20
+ from ...configuration_utils import PretrainedConfig
21
+ from ...utils import logging
22
+
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+
27
+ class UniSpeechSatConfig(PretrainedConfig):
28
+ r"""
29
+ This is the configuration class to store the configuration of a [`UniSpeechSatModel`]. It is used to instantiate an
30
+ UniSpeechSat model according to the specified arguments, defining the model architecture. Instantiating a
31
+ configuration with the defaults will yield a similar configuration to that of the UniSpeechSat
32
+ [microsoft/unispeech-sat-base-100h-libri-ft](https://huggingface.co/microsoft/unispeech-sat-base-100h-libri-ft)
33
+ architecture.
34
+
35
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
36
+ documentation from [`PretrainedConfig`] for more information.
37
+
38
+
39
+ Args:
40
+ vocab_size (`int`, *optional*, defaults to 32):
41
+ Vocabulary size of the UniSpeechSat model. Defines the number of different tokens that can be represented
42
+ by the `inputs_ids` passed when calling [`UniSpeechSatModel`]. Vocabulary size of the model. Defines the
43
+ different tokens that can be represented by the *inputs_ids* passed to the forward method of
44
+ [`UniSpeechSatModel`].
45
+ hidden_size (`int`, *optional*, defaults to 768):
46
+ Dimensionality of the encoder layers and the pooler layer.
47
+ num_hidden_layers (`int`, *optional*, defaults to 12):
48
+ Number of hidden layers in the Transformer encoder.
49
+ num_attention_heads (`int`, *optional*, defaults to 12):
50
+ Number of attention heads for each attention layer in the Transformer encoder.
51
+ intermediate_size (`int`, *optional*, defaults to 3072):
52
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
53
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
54
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
55
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
56
+ hidden_dropout (`float`, *optional*, defaults to 0.1):
57
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
58
+ activation_dropout (`float`, *optional*, defaults to 0.1):
59
+ The dropout ratio for activations inside the fully connected layer.
60
+ attention_dropout (`float`, *optional*, defaults to 0.1):
61
+ The dropout ratio for the attention probabilities.
62
+ feat_proj_dropout (`float`, *optional*, defaults to 0.0):
63
+ The dropout probability for output of the feature encoder.
64
+ feat_quantizer_dropout (`float`, *optional*, defaults to 0.0):
65
+ The dropout probability for the output of the feature encoder that's used by the quantizer.
66
+ final_dropout (`float`, *optional*, defaults to 0.1):
67
+ The dropout probability for the final projection layer of [`UniSpeechSatForCTC`].
68
+ layerdrop (`float`, *optional*, defaults to 0.1):
69
+ The LayerDrop probability. See the [LayerDrop paper](see https://huggingface.co/papers/1909.11556) for more
70
+ details.
71
+ initializer_range (`float`, *optional*, defaults to 0.02):
72
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
73
+ layer_norm_eps (`float`, *optional*, defaults to 1e-05):
74
+ The epsilon used by the layer normalization layers.
75
+ feat_extract_norm (`str`, *optional*, defaults to `"group"`):
76
+ The norm to be applied to 1D convolutional layers in feature encoder. One of `"group"` for group
77
+ normalization of only the first 1D convolutional layer or `"layer"` for layer normalization of all 1D
78
+ convolutional layers.
79
+ feat_extract_activation (`str, *optional*, defaults to `"gelu"`):
80
+ The non-linear activation function (function or string) in the 1D convolutional layers of the feature
81
+ extractor. If string, `"gelu"`, `"relu"`, `"selu"` and `"gelu_new"` are supported.
82
+ conv_dim (`tuple[int]` or `list[int]`, *optional*, defaults to `(512, 512, 512, 512, 512, 512, 512)`):
83
+ A tuple of integers defining the number of input and output channels of each 1D convolutional layer in the
84
+ feature encoder. The length of *conv_dim* defines the number of 1D convolutional layers.
85
+ conv_stride (`tuple[int]` or `list[int]`, *optional*, defaults to `(5, 2, 2, 2, 2, 2, 2)`):
86
+ A tuple of integers defining the stride of each 1D convolutional layer in the feature encoder. The length
87
+ of *conv_stride* defines the number of convolutional layers and has to match the length of *conv_dim*.
88
+ conv_kernel (`tuple[int]` or `list[int]`, *optional*, defaults to `(10, 3, 3, 3, 3, 2, 2)`):
89
+ A tuple of integers defining the kernel size of each 1D convolutional layer in the feature encoder. The
90
+ length of *conv_kernel* defines the number of convolutional layers and has to match the length of
91
+ *conv_dim*.
92
+ conv_bias (`bool`, *optional*, defaults to `False`):
93
+ Whether the 1D convolutional layers have a bias.
94
+ num_conv_pos_embeddings (`int`, *optional*, defaults to 128):
95
+ Number of convolutional positional embeddings. Defines the kernel size of 1D convolutional positional
96
+ embeddings layer.
97
+ num_conv_pos_embedding_groups (`int`, *optional*, defaults to 16):
98
+ Number of groups of 1D convolutional positional embeddings layer.
99
+ do_stable_layer_norm (`bool`, *optional*, defaults to `False`):
100
+ Whether to apply *stable* layer norm architecture of the Transformer encoder. `do_stable_layer_norm is
101
+ True` corresponds to applying layer norm before the attention layer, whereas `do_stable_layer_norm is
102
+ False` corresponds to applying layer norm after the attention layer.
103
+ apply_spec_augment (`bool`, *optional*, defaults to `True`):
104
+ Whether to apply *SpecAugment* data augmentation to the outputs of the feature encoder. For reference see
105
+ [SpecAugment: A Simple Data Augmentation Method for Automatic Speech
106
+ Recognition](https://huggingface.co/papers/1904.08779).
107
+ mask_time_prob (`float`, *optional*, defaults to 0.05):
108
+ Percentage (between 0 and 1) of all feature vectors along the time axis which will be masked. The masking
109
+ procedure generates ''mask_time_prob*len(time_axis)/mask_time_length'' independent masks over the axis. If
110
+ reasoning from the probability of each feature vector to be chosen as the start of the vector span to be
111
+ masked, *mask_time_prob* should be `prob_vector_start*mask_time_length`. Note that overlap may decrease the
112
+ actual percentage of masked vectors. This is only relevant if `apply_spec_augment is True`.
113
+ mask_time_length (`int`, *optional*, defaults to 10):
114
+ Length of vector span along the time axis.
115
+ mask_time_min_masks (`int`, *optional*, defaults to 2):
116
+ The minimum number of masks of length `mask_feature_length` generated along the time axis, each time step,
117
+ irrespectively of `mask_feature_prob`. Only relevant if ''mask_time_prob*len(time_axis)/mask_time_length <
118
+ mask_time_min_masks''
119
+ mask_feature_prob (`float`, *optional*, defaults to 0.0):
120
+ Percentage (between 0 and 1) of all feature vectors along the feature axis which will be masked. The
121
+ masking procedure generates ''mask_feature_prob*len(feature_axis)/mask_time_length'' independent masks over
122
+ the axis. If reasoning from the probability of each feature vector to be chosen as the start of the vector
123
+ span to be masked, *mask_feature_prob* should be `prob_vector_start*mask_feature_length`. Note that overlap
124
+ may decrease the actual percentage of masked vectors. This is only relevant if `apply_spec_augment is
125
+ True`.
126
+ mask_feature_length (`int`, *optional*, defaults to 10):
127
+ Length of vector span along the feature axis.
128
+ mask_feature_min_masks (`int`, *optional*, defaults to 0):
129
+ The minimum number of masks of length `mask_feature_length` generated along the feature axis, each time
130
+ step, irrespectively of `mask_feature_prob`. Only relevant if
131
+ ''mask_feature_prob*len(feature_axis)/mask_feature_length < mask_feature_min_masks''
132
+ num_codevectors_per_group (`int`, *optional*, defaults to 320):
133
+ Number of entries in each quantization codebook (group).
134
+ num_codevector_groups (`int`, *optional*, defaults to 2):
135
+ Number of codevector groups for product codevector quantization.
136
+ contrastive_logits_temperature (`float`, *optional*, defaults to 0.1):
137
+ The temperature *kappa* in the contrastive loss.
138
+ num_negatives (`int`, *optional*, defaults to 100):
139
+ Number of negative samples for the contrastive loss.
140
+ codevector_dim (`int`, *optional*, defaults to 256):
141
+ Dimensionality of the quantized feature vectors.
142
+ proj_codevector_dim (`int`, *optional*, defaults to 256):
143
+ Dimensionality of the final projection of both the quantized and the transformer features.
144
+ diversity_loss_weight (`int`, *optional*, defaults to 0.1):
145
+ The weight of the codebook diversity loss component.
146
+ ctc_loss_reduction (`str`, *optional*, defaults to `"mean"`):
147
+ Specifies the reduction to apply to the output of `torch.nn.CTCLoss`. Only relevant when training an
148
+ instance of [`UniSpeechSatForCTC`].
149
+ ctc_zero_infinity (`bool`, *optional*, defaults to `False`):
150
+ Whether to zero infinite losses and the associated gradients of `torch.nn.CTCLoss`. Infinite losses mainly
151
+ occur when the inputs are too short to be aligned to the targets. Only relevant when training an instance
152
+ of [`UniSpeechSatForCTC`].
153
+ use_weighted_layer_sum (`bool`, *optional*, defaults to `False`):
154
+ Whether to use a weighted average of layer outputs with learned weights. Only relevant when using an
155
+ instance of [`UniSpeechSatForSequenceClassification`].
156
+ classifier_proj_size (`int`, *optional*, defaults to 256):
157
+ Dimensionality of the projection before token mean-pooling for classification.
158
+ tdnn_dim (`tuple[int]` or `list[int]`, *optional*, defaults to `(512, 512, 512, 512, 1500)`):
159
+ A tuple of integers defining the number of output channels of each 1D convolutional layer in the *TDNN*
160
+ module of the *XVector* model. The length of *tdnn_dim* defines the number of *TDNN* layers.
161
+ tdnn_kernel (`tuple[int]` or `list[int]`, *optional*, defaults to `(5, 3, 3, 1, 1)`):
162
+ A tuple of integers defining the kernel size of each 1D convolutional layer in the *TDNN* module of the
163
+ *XVector* model. The length of *tdnn_kernel* has to match the length of *tdnn_dim*.
164
+ tdnn_dilation (`tuple[int]` or `list[int]`, *optional*, defaults to `(1, 2, 3, 1, 1)`):
165
+ A tuple of integers defining the dilation factor of each 1D convolutional layer in *TDNN* module of the
166
+ *XVector* model. The length of *tdnn_dilation* has to match the length of *tdnn_dim*.
167
+ xvector_output_dim (`int`, *optional*, defaults to 512):
168
+ Dimensionality of the *XVector* embedding vectors.
169
+ pad_token_id (`int`, *optional*, defaults to 0):
170
+ The id of the padding token.
171
+ bos_token_id (`int`, *optional*, defaults to 1):
172
+ The id of the "beginning-of-sequence" token.
173
+ eos_token_id (`int`, *optional*, defaults to 2):
174
+ The id of the "end-of-sequence" token.
175
+ num_clusters (`int`, *optional*, defaults to 504):
176
+ Number of clusters for weak labeling. Only relevant when using an instance of
177
+ [`UniSpeechSatForPreTraining`].
178
+
179
+ Example:
180
+
181
+ ```python
182
+ >>> from transformers import UniSpeechSatModel, UniSpeechSatConfig
183
+
184
+ >>> # Initializing a UniSpeechSat microsoft/unispeech-sat-base-100h-libri-ft style configuration
185
+ >>> configuration = UniSpeechSatConfig()
186
+
187
+ >>> # Initializing a model from the microsoft/unispeech-sat-base-100h-libri-ft style configuration
188
+ >>> model = UniSpeechSatModel(configuration)
189
+
190
+ >>> # Accessing the model configuration
191
+ >>> configuration = model.config
192
+ ```"""
193
+
194
+ model_type = "unispeech-sat"
195
+
196
+ def __init__(
197
+ self,
198
+ vocab_size=32,
199
+ hidden_size=768,
200
+ num_hidden_layers=12,
201
+ num_attention_heads=12,
202
+ intermediate_size=3072,
203
+ hidden_act="gelu",
204
+ hidden_dropout=0.1,
205
+ activation_dropout=0.1,
206
+ attention_dropout=0.1,
207
+ feat_proj_dropout=0.0,
208
+ feat_quantizer_dropout=0.0,
209
+ final_dropout=0.1,
210
+ layerdrop=0.1,
211
+ initializer_range=0.02,
212
+ layer_norm_eps=1e-5,
213
+ feat_extract_norm="group",
214
+ feat_extract_activation="gelu",
215
+ conv_dim=(512, 512, 512, 512, 512, 512, 512),
216
+ conv_stride=(5, 2, 2, 2, 2, 2, 2),
217
+ conv_kernel=(10, 3, 3, 3, 3, 2, 2),
218
+ conv_bias=False,
219
+ num_conv_pos_embeddings=128,
220
+ num_conv_pos_embedding_groups=16,
221
+ do_stable_layer_norm=False,
222
+ apply_spec_augment=True,
223
+ mask_time_prob=0.05,
224
+ mask_time_length=10,
225
+ mask_time_min_masks=2,
226
+ mask_feature_prob=0.0,
227
+ mask_feature_length=10,
228
+ mask_feature_min_masks=0,
229
+ num_codevectors_per_group=320,
230
+ num_codevector_groups=2,
231
+ contrastive_logits_temperature=0.1,
232
+ num_negatives=100,
233
+ codevector_dim=256,
234
+ proj_codevector_dim=256,
235
+ diversity_loss_weight=0.1,
236
+ ctc_loss_reduction="mean",
237
+ ctc_zero_infinity=False,
238
+ use_weighted_layer_sum=False,
239
+ classifier_proj_size=256,
240
+ tdnn_dim=(512, 512, 512, 512, 1500),
241
+ tdnn_kernel=(5, 3, 3, 1, 1),
242
+ tdnn_dilation=(1, 2, 3, 1, 1),
243
+ xvector_output_dim=512,
244
+ pad_token_id=0,
245
+ bos_token_id=1,
246
+ eos_token_id=2,
247
+ num_clusters=504,
248
+ **kwargs,
249
+ ):
250
+ super().__init__(**kwargs, pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id)
251
+ self.hidden_size = hidden_size
252
+ self.feat_extract_norm = feat_extract_norm
253
+ self.feat_extract_activation = feat_extract_activation
254
+ self.conv_dim = list(conv_dim)
255
+ self.conv_stride = list(conv_stride)
256
+ self.conv_kernel = list(conv_kernel)
257
+ self.conv_bias = conv_bias
258
+ self.num_conv_pos_embeddings = num_conv_pos_embeddings
259
+ self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups
260
+ self.num_feat_extract_layers = len(self.conv_dim)
261
+ self.num_hidden_layers = num_hidden_layers
262
+ self.intermediate_size = intermediate_size
263
+ self.hidden_act = hidden_act
264
+ self.num_attention_heads = num_attention_heads
265
+ self.hidden_dropout = hidden_dropout
266
+ self.attention_dropout = attention_dropout
267
+ self.activation_dropout = activation_dropout
268
+ self.feat_proj_dropout = feat_proj_dropout
269
+ self.final_dropout = final_dropout
270
+ self.layerdrop = layerdrop
271
+ self.layer_norm_eps = layer_norm_eps
272
+ self.initializer_range = initializer_range
273
+ self.vocab_size = vocab_size
274
+ self.num_clusters = num_clusters
275
+ self.do_stable_layer_norm = do_stable_layer_norm
276
+ self.use_weighted_layer_sum = use_weighted_layer_sum
277
+
278
+ if (
279
+ (len(self.conv_stride) != self.num_feat_extract_layers)
280
+ or (len(self.conv_kernel) != self.num_feat_extract_layers)
281
+ or (len(self.conv_dim) != self.num_feat_extract_layers)
282
+ ):
283
+ raise ValueError(
284
+ "Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="
285
+ " `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="
286
+ f" {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,"
287
+ f" `len(config.conv_kernel) = {len(self.conv_kernel)}`."
288
+ )
289
+
290
+ # fine-tuning config parameters for SpecAugment: https://huggingface.co/papers/1904.08779
291
+ self.apply_spec_augment = apply_spec_augment
292
+ self.mask_time_prob = mask_time_prob
293
+ self.mask_time_length = mask_time_length
294
+ self.mask_time_min_masks = mask_time_min_masks
295
+ self.mask_feature_prob = mask_feature_prob
296
+ self.mask_feature_length = mask_feature_length
297
+ self.mask_feature_min_masks = mask_feature_min_masks
298
+
299
+ # parameters for pretraining with codevector quantized representations
300
+ self.num_codevectors_per_group = num_codevectors_per_group
301
+ self.num_codevector_groups = num_codevector_groups
302
+ self.contrastive_logits_temperature = contrastive_logits_temperature
303
+ self.feat_quantizer_dropout = feat_quantizer_dropout
304
+ self.num_negatives = num_negatives
305
+ self.codevector_dim = codevector_dim
306
+ self.proj_codevector_dim = proj_codevector_dim
307
+ self.diversity_loss_weight = diversity_loss_weight
308
+
309
+ # ctc loss
310
+ self.ctc_loss_reduction = ctc_loss_reduction
311
+ self.ctc_zero_infinity = ctc_zero_infinity
312
+
313
+ # SequenceClassification-specific parameter. Feel free to ignore for other classes.
314
+ self.classifier_proj_size = classifier_proj_size
315
+
316
+ # XVector-specific parameters. Feel free to ignore for other classes.
317
+ self.tdnn_dim = list(tdnn_dim)
318
+ self.tdnn_kernel = list(tdnn_kernel)
319
+ self.tdnn_dilation = list(tdnn_dilation)
320
+ self.xvector_output_dim = xvector_output_dim
321
+
322
+ @property
323
+ def inputs_to_logits_ratio(self):
324
+ return functools.reduce(operator.mul, self.conv_stride, 1)
325
+
326
+
327
+ __all__ = ["UniSpeechSatConfig"]
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/unispeech_sat/convert_unispeech_original_s3prl_checkpoint_to_pytorch.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The HuggingFace Inc. team.
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
+ """Convert Hubert checkpoint."""
16
+
17
+ import argparse
18
+
19
+ import torch
20
+
21
+ from transformers import (
22
+ UniSpeechSatConfig,
23
+ UniSpeechSatForAudioFrameClassification,
24
+ UniSpeechSatForSequenceClassification,
25
+ UniSpeechSatForXVector,
26
+ Wav2Vec2FeatureExtractor,
27
+ logging,
28
+ )
29
+
30
+
31
+ logging.set_verbosity_info()
32
+ logger = logging.get_logger(__name__)
33
+
34
+
35
+ def convert_classification(base_model_name, hf_config, downstream_dict):
36
+ model = UniSpeechSatForSequenceClassification.from_pretrained(base_model_name, config=hf_config)
37
+ model.projector.weight.data = downstream_dict["projector.weight"]
38
+ model.projector.bias.data = downstream_dict["projector.bias"]
39
+ model.classifier.weight.data = downstream_dict["model.post_net.linear.weight"]
40
+ model.classifier.bias.data = downstream_dict["model.post_net.linear.bias"]
41
+ return model
42
+
43
+
44
+ def convert_diarization(base_model_name, hf_config, downstream_dict):
45
+ model = UniSpeechSatForAudioFrameClassification.from_pretrained(base_model_name, config=hf_config)
46
+ model.classifier.weight.data = downstream_dict["model.linear.weight"]
47
+ model.classifier.bias.data = downstream_dict["model.linear.bias"]
48
+ return model
49
+
50
+
51
+ def convert_xvector(base_model_name, hf_config, downstream_dict):
52
+ model = UniSpeechSatForXVector.from_pretrained(base_model_name, config=hf_config)
53
+ model.projector.weight.data = downstream_dict["connector.weight"]
54
+ model.projector.bias.data = downstream_dict["connector.bias"]
55
+ for i, kernel_size in enumerate(hf_config.tdnn_kernel):
56
+ model.tdnn[i].kernel.weight.data = downstream_dict[
57
+ f"model.framelevel_feature_extractor.module.{i}.kernel.weight"
58
+ ]
59
+ model.tdnn[i].kernel.bias.data = downstream_dict[f"model.framelevel_feature_extractor.module.{i}.kernel.bias"]
60
+
61
+ model.feature_extractor.weight.data = downstream_dict["model.utterancelevel_feature_extractor.linear1.weight"]
62
+ model.feature_extractor.bias.data = downstream_dict["model.utterancelevel_feature_extractor.linear1.bias"]
63
+ model.classifier.weight.data = downstream_dict["model.utterancelevel_feature_extractor.linear2.weight"]
64
+ model.classifier.bias.data = downstream_dict["model.utterancelevel_feature_extractor.linear2.bias"]
65
+ model.objective.weight.data = downstream_dict["objective.W"]
66
+ return model
67
+
68
+
69
+ @torch.no_grad()
70
+ def convert_s3prl_checkpoint(base_model_name, config_path, checkpoint_path, model_dump_path):
71
+ """
72
+ Copy/paste/tweak model's weights to transformers design.
73
+ """
74
+ checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=True)
75
+
76
+ downstream_dict = checkpoint["Downstream"]
77
+
78
+ hf_config = UniSpeechSatConfig.from_pretrained(config_path)
79
+ hf_feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(
80
+ base_model_name, return_attention_mask=True, do_normalize=False
81
+ )
82
+
83
+ arch = hf_config.architectures[0]
84
+ if arch.endswith("ForSequenceClassification"):
85
+ hf_model = convert_classification(base_model_name, hf_config, downstream_dict)
86
+ elif arch.endswith("ForAudioFrameClassification"):
87
+ hf_model = convert_diarization(base_model_name, hf_config, downstream_dict)
88
+ elif arch.endswith("ForXVector"):
89
+ hf_model = convert_xvector(base_model_name, hf_config, downstream_dict)
90
+ else:
91
+ raise NotImplementedError(f"S3PRL weights conversion is not supported for {arch}")
92
+
93
+ if hf_config.use_weighted_layer_sum:
94
+ hf_model.layer_weights.data = checkpoint["Featurizer"]["weights"]
95
+
96
+ hf_feature_extractor.save_pretrained(model_dump_path)
97
+ hf_model.save_pretrained(model_dump_path)
98
+
99
+
100
+ if __name__ == "__main__":
101
+ parser = argparse.ArgumentParser()
102
+ parser.add_argument(
103
+ "--base_model_name", default=None, type=str, help="Name of the huggingface pretrained base model."
104
+ )
105
+ parser.add_argument("--config_path", default=None, type=str, help="Path to the huggingface classifier config.")
106
+ parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to the s3prl checkpoint.")
107
+ parser.add_argument("--model_dump_path", default=None, type=str, help="Path to the final converted model.")
108
+ args = parser.parse_args()
109
+ convert_s3prl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/unispeech_sat/convert_unispeech_sat_original_pytorch_checkpoint_to_pytorch.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The HuggingFace Inc. team.
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
+ """Convert UniSpeechSat checkpoint."""
16
+
17
+ import argparse
18
+
19
+ import fairseq
20
+ import torch
21
+
22
+ from transformers import UniSpeechSatConfig, UniSpeechSatForCTC, UniSpeechSatForPreTraining, logging
23
+
24
+
25
+ logging.set_verbosity_info()
26
+ logger = logging.get_logger(__name__)
27
+
28
+ MAPPING = {
29
+ "post_extract_proj": "feature_projection.projection",
30
+ "encoder.pos_conv.0": "encoder.pos_conv_embed.conv",
31
+ "self_attn.k_proj": "encoder.layers.*.attention.k_proj",
32
+ "self_attn.v_proj": "encoder.layers.*.attention.v_proj",
33
+ "self_attn.q_proj": "encoder.layers.*.attention.q_proj",
34
+ "self_attn.out_proj": "encoder.layers.*.attention.out_proj",
35
+ "self_attn_layer_norm": "encoder.layers.*.layer_norm",
36
+ "fc1": "encoder.layers.*.feed_forward.intermediate_dense",
37
+ "fc2": "encoder.layers.*.feed_forward.output_dense",
38
+ "final_layer_norm": "encoder.layers.*.final_layer_norm",
39
+ "encoder.layer_norm": "encoder.layer_norm",
40
+ "encoder.layer_norm_for_extract": "layer_norm_for_extract",
41
+ "w2v_model.layer_norm": "feature_projection.layer_norm",
42
+ "quantizer.weight_proj": "quantizer.weight_proj",
43
+ "quantizer.vars": "quantizer.codevectors",
44
+ "project_q": "project_q",
45
+ "final_proj": "project_hid",
46
+ "w2v_encoder.proj": "lm_head",
47
+ "label_embs_concat": "label_embeddings_concat",
48
+ "mask_emb": "masked_spec_embed",
49
+ "spk_proj": "speaker_proj",
50
+ }
51
+ TOP_LEVEL_KEYS = [
52
+ "lm_head",
53
+ "quantizer.weight_proj",
54
+ "quantizer.codevectors",
55
+ "project_q",
56
+ "project_hid",
57
+ "label_embeddings_concat",
58
+ "speaker_proj",
59
+ "layer_norm_for_extract",
60
+ ]
61
+
62
+
63
+ def set_recursively(hf_pointer, key, value, full_name, weight_type):
64
+ for attribute in key.split("."):
65
+ hf_pointer = getattr(hf_pointer, attribute)
66
+
67
+ if weight_type is not None:
68
+ hf_shape = getattr(hf_pointer, weight_type).shape
69
+ else:
70
+ hf_shape = hf_pointer.shape
71
+
72
+ if hf_shape != value.shape:
73
+ raise ValueError(
74
+ f"Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be"
75
+ f" {value.shape} for {full_name}"
76
+ )
77
+
78
+ if weight_type == "weight":
79
+ hf_pointer.weight.data = value
80
+ elif weight_type == "weight_g":
81
+ hf_pointer.weight_g.data = value
82
+ elif weight_type == "weight_v":
83
+ hf_pointer.weight_v.data = value
84
+ elif weight_type == "bias":
85
+ hf_pointer.bias.data = value
86
+ else:
87
+ hf_pointer.data = value
88
+
89
+ logger.info(f"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.")
90
+
91
+
92
+ def recursively_load_weights(fairseq_model, hf_model):
93
+ unused_weights = []
94
+ fairseq_dict = fairseq_model.state_dict()
95
+
96
+ feature_extractor = hf_model.unispeech_sat.feature_extractor
97
+
98
+ for name, value in fairseq_dict.items():
99
+ is_used = False
100
+ if "conv_layers" in name:
101
+ load_conv_layer(
102
+ name,
103
+ value,
104
+ feature_extractor,
105
+ unused_weights,
106
+ hf_model.config.feat_extract_norm == "group",
107
+ )
108
+ is_used = True
109
+ else:
110
+ for key, mapped_key in MAPPING.items():
111
+ mapped_key = "unispeech_sat." + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key
112
+ if key in name or key.split("w2v_model.")[-1] == name.split(".")[0]:
113
+ if "layer_norm_for_extract" in name and (".".join(name.split(".")[:-1]) != key):
114
+ # special case since naming is very similar
115
+ continue
116
+ is_used = True
117
+ if "*" in mapped_key:
118
+ layer_index = name.split(key)[0].split(".")[-2]
119
+ mapped_key = mapped_key.replace("*", layer_index)
120
+ if "weight_g" in name:
121
+ weight_type = "weight_g"
122
+ elif "weight_v" in name:
123
+ weight_type = "weight_v"
124
+ elif "bias" in name:
125
+ weight_type = "bias"
126
+ elif "weight" in name:
127
+ # TODO: don't match quantizer.weight_proj
128
+ weight_type = "weight"
129
+ else:
130
+ weight_type = None
131
+ set_recursively(hf_model, mapped_key, value, name, weight_type)
132
+ continue
133
+ if not is_used:
134
+ unused_weights.append(name)
135
+
136
+ logger.warning(f"Unused weights: {unused_weights}")
137
+
138
+
139
+ def load_conv_layer(full_name, value, feature_extractor, unused_weights, use_group_norm):
140
+ name = full_name.split("conv_layers.")[-1]
141
+ items = name.split(".")
142
+ layer_id = int(items[0])
143
+ type_id = int(items[1])
144
+
145
+ if type_id == 0:
146
+ if "bias" in name:
147
+ if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape:
148
+ raise ValueError(
149
+ f"{full_name} has size {value.shape}, but"
150
+ f" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found."
151
+ )
152
+ feature_extractor.conv_layers[layer_id].conv.bias.data = value
153
+ logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}.")
154
+ elif "weight" in name:
155
+ if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape:
156
+ raise ValueError(
157
+ f"{full_name} has size {value.shape}, but"
158
+ f" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found."
159
+ )
160
+ feature_extractor.conv_layers[layer_id].conv.weight.data = value
161
+ logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}.")
162
+ elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
163
+ if "bias" in name:
164
+ if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape:
165
+ raise ValueError(
166
+ f"{full_name} has size {value.shape}, but"
167
+ f" {feature_extractor[layer_id].layer_norm.bias.data.shape} was found."
168
+ )
169
+ feature_extractor.conv_layers[layer_id].layer_norm.bias.data = value
170
+ logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.")
171
+ elif "weight" in name:
172
+ if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape:
173
+ raise ValueError(
174
+ f"{full_name} has size {value.shape}, but"
175
+ f" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found."
176
+ )
177
+ feature_extractor.conv_layers[layer_id].layer_norm.weight.data = value
178
+ logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.")
179
+ else:
180
+ unused_weights.append(full_name)
181
+
182
+
183
+ @torch.no_grad()
184
+ def convert_unispeech_sat_checkpoint(
185
+ checkpoint_path, pytorch_dump_folder_path, config_path=None, dict_path=None, is_finetuned=True
186
+ ):
187
+ """
188
+ Copy/paste/tweak model's weights to transformers design.
189
+ """
190
+ if config_path is not None:
191
+ config = UniSpeechSatConfig.from_pretrained(config_path)
192
+ else:
193
+ config = UniSpeechSatConfig()
194
+
195
+ dict_path = ""
196
+
197
+ if is_finetuned:
198
+ hf_wav2vec = UniSpeechSatForCTC(config)
199
+ else:
200
+ hf_wav2vec = UniSpeechSatForPreTraining(config)
201
+
202
+ model, _, _ = fairseq.checkpoint_utils.load_model_ensemble_and_task(
203
+ [checkpoint_path], arg_overrides={"data": "/".join(dict_path.split("/")[:-1])}
204
+ )
205
+ model = model[0].eval()
206
+
207
+ recursively_load_weights(model, hf_wav2vec)
208
+
209
+ hf_wav2vec.save_pretrained(pytorch_dump_folder_path)
210
+
211
+
212
+ if __name__ == "__main__":
213
+ parser = argparse.ArgumentParser()
214
+ parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.")
215
+ parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to fairseq checkpoint")
216
+ parser.add_argument("--dict_path", default=None, type=str, help="Path to dict of fine-tuned model")
217
+ parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert")
218
+ parser.add_argument(
219
+ "--not_finetuned", action="store_true", help="Whether the model to convert is a fine-tuned model or not"
220
+ )
221
+ args = parser.parse_args()
222
+ convert_unispeech_sat_checkpoint(
223
+ args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned
224
+ )
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/unispeech_sat/modeling_unispeech_sat.py ADDED
@@ -0,0 +1,1826 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/unispeech_sat/modular_unispeech_sat.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_unispeech_sat.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2021 The Fairseq Authors and the HuggingFace Inc. team. All rights reserved.
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License");
11
+ # you may not use this file except in compliance with the License.
12
+ # You may obtain a copy of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS,
18
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ # See the License for the specific language governing permissions and
20
+ # limitations under the License.
21
+
22
+ import math
23
+ import warnings
24
+ from dataclasses import dataclass
25
+ from typing import Callable, Optional, Union
26
+
27
+ import numpy as np
28
+ import torch
29
+ import torch.nn as nn
30
+ from torch.nn import CrossEntropyLoss
31
+
32
+ from ...activations import ACT2FN
33
+ from ...integrations.deepspeed import is_deepspeed_zero3_enabled
34
+ from ...integrations.fsdp import is_fsdp_managed_module
35
+ from ...modeling_attn_mask_utils import _prepare_4d_attention_mask, _prepare_4d_attention_mask_for_sdpa
36
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
37
+ from ...modeling_layers import GradientCheckpointingLayer
38
+ from ...modeling_outputs import (
39
+ BaseModelOutput,
40
+ CausalLMOutput,
41
+ ModelOutput,
42
+ SequenceClassifierOutput,
43
+ TokenClassifierOutput,
44
+ Wav2Vec2BaseModelOutput,
45
+ XVectorOutput,
46
+ )
47
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
48
+ from ...processing_utils import Unpack
49
+ from ...utils import auto_docstring, is_peft_available, is_torch_flex_attn_available, logging
50
+ from .configuration_unispeech_sat import UniSpeechSatConfig
51
+
52
+
53
+ if is_torch_flex_attn_available():
54
+ from ...integrations.flex_attention import make_flex_block_causal_mask
55
+
56
+
57
+ logger = logging.get_logger(__name__)
58
+
59
+
60
+ @dataclass
61
+ @auto_docstring(
62
+ custom_intro="""
63
+ Output type of [`UniSpeechSatForPreTrainingOutput`], with potential hidden states and attentions.
64
+ """
65
+ )
66
+ class UniSpeechSatForPreTrainingOutput(ModelOutput):
67
+ r"""
68
+ loss (*optional*, returned when model is in train mode, `torch.FloatTensor` of shape `(1,)`):
69
+ Total loss as the sum of the contrastive loss (L_m) and the diversity loss (L_d) as stated in the [official
70
+ paper](https://arxiv.org/pdf/2006.11477.pdf) . (classification) loss.
71
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.proj_codevector_dim)`, *optional*):
72
+ Prediction scores of the contrastive loss model, i.e. the output of the model before the final softmax.
73
+ projected_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.proj_codevector_dim)`):
74
+ Hidden-states of the model projected to *config.proj_codevector_dim* that can be used to predict the masked
75
+ projected quantized states.
76
+ projected_quantized_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.proj_codevector_dim)`):
77
+ Quantized extracted feature vectors projected to *config.proj_codevector_dim* representing the positive
78
+ target vectors for contrastive loss.
79
+ codevector_perplexity (`torch.FloatTensor` of shape `(1,)`):
80
+ The perplexity of the codevector distribution, used to measure the diversity of the codebook.
81
+ """
82
+
83
+ loss: Optional[torch.FloatTensor] = None
84
+ logits: Optional[torch.FloatTensor] = None
85
+ projected_states: Optional[torch.FloatTensor] = None
86
+ projected_quantized_states: Optional[torch.FloatTensor] = None
87
+ codevector_perplexity: Optional[torch.FloatTensor] = None
88
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
89
+ attentions: Optional[tuple[torch.FloatTensor]] = None
90
+
91
+
92
+ class UniSpeechSatSamePadLayer(nn.Module):
93
+ def __init__(self, num_conv_pos_embeddings):
94
+ super().__init__()
95
+ self.num_pad_remove = 1 if num_conv_pos_embeddings % 2 == 0 else 0
96
+
97
+ def forward(self, hidden_states):
98
+ if self.num_pad_remove > 0:
99
+ hidden_states = hidden_states[:, :, : -self.num_pad_remove]
100
+ return hidden_states
101
+
102
+
103
+ class UniSpeechSatPositionalConvEmbedding(nn.Module):
104
+ def __init__(self, config):
105
+ super().__init__()
106
+ self.conv = nn.Conv1d(
107
+ config.hidden_size,
108
+ config.hidden_size,
109
+ kernel_size=config.num_conv_pos_embeddings,
110
+ padding=config.num_conv_pos_embeddings // 2,
111
+ groups=config.num_conv_pos_embedding_groups,
112
+ )
113
+
114
+ weight_norm = nn.utils.weight_norm
115
+ if hasattr(nn.utils.parametrizations, "weight_norm"):
116
+ weight_norm = nn.utils.parametrizations.weight_norm
117
+
118
+ if is_deepspeed_zero3_enabled():
119
+ import deepspeed
120
+
121
+ with deepspeed.zero.GatheredParameters(self.conv.weight, modifier_rank=0):
122
+ self.conv = weight_norm(self.conv, name="weight", dim=2)
123
+ if hasattr(self.conv, "parametrizations"):
124
+ weight_g = self.conv.parametrizations.weight.original0
125
+ weight_v = self.conv.parametrizations.weight.original1
126
+ else:
127
+ weight_g = self.conv.weight_g
128
+ weight_v = self.conv.weight_v
129
+ deepspeed.zero.register_external_parameter(self, weight_v)
130
+ deepspeed.zero.register_external_parameter(self, weight_g)
131
+ else:
132
+ self.conv = weight_norm(self.conv, name="weight", dim=2)
133
+
134
+ self.padding = UniSpeechSatSamePadLayer(config.num_conv_pos_embeddings)
135
+ self.activation = ACT2FN[config.feat_extract_activation]
136
+
137
+ def forward(self, hidden_states):
138
+ hidden_states = hidden_states.transpose(1, 2)
139
+
140
+ hidden_states = self.conv(hidden_states)
141
+ hidden_states = self.padding(hidden_states)
142
+ hidden_states = self.activation(hidden_states)
143
+
144
+ hidden_states = hidden_states.transpose(1, 2)
145
+ return hidden_states
146
+
147
+
148
+ class UniSpeechSatNoLayerNormConvLayer(GradientCheckpointingLayer):
149
+ def __init__(self, config, layer_id=0):
150
+ super().__init__()
151
+ self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1
152
+ self.out_conv_dim = config.conv_dim[layer_id]
153
+
154
+ self.conv = nn.Conv1d(
155
+ self.in_conv_dim,
156
+ self.out_conv_dim,
157
+ kernel_size=config.conv_kernel[layer_id],
158
+ stride=config.conv_stride[layer_id],
159
+ bias=config.conv_bias,
160
+ )
161
+ self.activation = ACT2FN[config.feat_extract_activation]
162
+
163
+ def forward(self, hidden_states):
164
+ hidden_states = self.conv(hidden_states)
165
+ hidden_states = self.activation(hidden_states)
166
+ return hidden_states
167
+
168
+
169
+ class UniSpeechSatLayerNormConvLayer(GradientCheckpointingLayer):
170
+ def __init__(self, config, layer_id=0):
171
+ super().__init__()
172
+ self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1
173
+ self.out_conv_dim = config.conv_dim[layer_id]
174
+
175
+ self.conv = nn.Conv1d(
176
+ self.in_conv_dim,
177
+ self.out_conv_dim,
178
+ kernel_size=config.conv_kernel[layer_id],
179
+ stride=config.conv_stride[layer_id],
180
+ bias=config.conv_bias,
181
+ )
182
+ self.layer_norm = nn.LayerNorm(self.out_conv_dim, elementwise_affine=True)
183
+ self.activation = ACT2FN[config.feat_extract_activation]
184
+
185
+ def forward(self, hidden_states):
186
+ hidden_states = self.conv(hidden_states)
187
+
188
+ hidden_states = hidden_states.transpose(-2, -1)
189
+ hidden_states = self.layer_norm(hidden_states)
190
+ hidden_states = hidden_states.transpose(-2, -1)
191
+
192
+ hidden_states = self.activation(hidden_states)
193
+ return hidden_states
194
+
195
+
196
+ class UniSpeechSatGroupNormConvLayer(GradientCheckpointingLayer):
197
+ def __init__(self, config, layer_id=0):
198
+ super().__init__()
199
+ self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1
200
+ self.out_conv_dim = config.conv_dim[layer_id]
201
+
202
+ self.conv = nn.Conv1d(
203
+ self.in_conv_dim,
204
+ self.out_conv_dim,
205
+ kernel_size=config.conv_kernel[layer_id],
206
+ stride=config.conv_stride[layer_id],
207
+ bias=config.conv_bias,
208
+ )
209
+ self.activation = ACT2FN[config.feat_extract_activation]
210
+
211
+ self.layer_norm = nn.GroupNorm(num_groups=self.out_conv_dim, num_channels=self.out_conv_dim, affine=True)
212
+
213
+ def forward(self, hidden_states):
214
+ hidden_states = self.conv(hidden_states)
215
+ hidden_states = self.layer_norm(hidden_states)
216
+ hidden_states = self.activation(hidden_states)
217
+ return hidden_states
218
+
219
+
220
+ class UniSpeechSatFeatureEncoder(nn.Module):
221
+ """Construct the features from raw audio waveform"""
222
+
223
+ def __init__(self, config):
224
+ super().__init__()
225
+
226
+ if config.feat_extract_norm == "group":
227
+ conv_layers = [UniSpeechSatGroupNormConvLayer(config, layer_id=0)] + [
228
+ UniSpeechSatNoLayerNormConvLayer(config, layer_id=i + 1)
229
+ for i in range(config.num_feat_extract_layers - 1)
230
+ ]
231
+ elif config.feat_extract_norm == "layer":
232
+ conv_layers = [
233
+ UniSpeechSatLayerNormConvLayer(config, layer_id=i) for i in range(config.num_feat_extract_layers)
234
+ ]
235
+ else:
236
+ raise ValueError(
237
+ f"`config.feat_extract_norm` is {config.feat_extract_norm}, but has to be one of ['group', 'layer']"
238
+ )
239
+ self.conv_layers = nn.ModuleList(conv_layers)
240
+ self.gradient_checkpointing = False
241
+ self._requires_grad = True
242
+
243
+ def _freeze_parameters(self):
244
+ for param in self.parameters():
245
+ param.requires_grad = False
246
+ self._requires_grad = False
247
+
248
+ def forward(self, input_values):
249
+ hidden_states = input_values[:, None]
250
+
251
+ # make sure hidden_states require grad for gradient_checkpointing
252
+ if self._requires_grad and self.training:
253
+ hidden_states.requires_grad = True
254
+
255
+ for conv_layer in self.conv_layers:
256
+ hidden_states = conv_layer(hidden_states)
257
+
258
+ return hidden_states
259
+
260
+
261
+ class UniSpeechSatFeatureProjection(nn.Module):
262
+ def __init__(self, config):
263
+ super().__init__()
264
+ self.layer_norm = nn.LayerNorm(config.conv_dim[-1], eps=config.layer_norm_eps)
265
+ self.projection = nn.Linear(config.conv_dim[-1], config.hidden_size)
266
+ self.dropout = nn.Dropout(config.feat_proj_dropout)
267
+
268
+ def forward(self, hidden_states):
269
+ # non-projected hidden states are needed for quantization
270
+ norm_hidden_states = self.layer_norm(hidden_states)
271
+ hidden_states = self.projection(norm_hidden_states)
272
+ hidden_states = self.dropout(hidden_states)
273
+ return hidden_states, norm_hidden_states
274
+
275
+
276
+ def eager_attention_forward(
277
+ module: nn.Module,
278
+ query: torch.Tensor,
279
+ key: torch.Tensor,
280
+ value: torch.Tensor,
281
+ attention_mask: Optional[torch.Tensor],
282
+ scaling: Optional[float] = None,
283
+ dropout: float = 0.0,
284
+ head_mask: Optional[torch.Tensor] = None,
285
+ **kwargs,
286
+ ):
287
+ if scaling is None:
288
+ scaling = query.size(-1) ** -0.5
289
+
290
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
291
+ if attention_mask is not None:
292
+ attn_weights = attn_weights + attention_mask
293
+
294
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
295
+
296
+ if head_mask is not None:
297
+ attn_weights = attn_weights * head_mask.view(1, -1, 1, 1)
298
+
299
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
300
+ attn_output = torch.matmul(attn_weights, value)
301
+ attn_output = attn_output.transpose(1, 2).contiguous()
302
+
303
+ return attn_output, attn_weights
304
+
305
+
306
+ class UniSpeechSatAttention(nn.Module):
307
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
308
+
309
+ def __init__(
310
+ self,
311
+ embed_dim: int,
312
+ num_heads: int,
313
+ dropout: float = 0.0,
314
+ is_decoder: bool = False,
315
+ bias: bool = True,
316
+ is_causal: bool = False,
317
+ config: Optional[UniSpeechSatConfig] = None,
318
+ ):
319
+ super().__init__()
320
+ self.embed_dim = embed_dim
321
+ self.num_heads = num_heads
322
+ self.dropout = dropout
323
+ self.head_dim = embed_dim // num_heads
324
+ self.config = config
325
+
326
+ if (self.head_dim * num_heads) != self.embed_dim:
327
+ raise ValueError(
328
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
329
+ f" and `num_heads`: {num_heads})."
330
+ )
331
+ self.scaling = self.head_dim**-0.5
332
+ self.is_decoder = is_decoder
333
+ self.is_causal = is_causal
334
+
335
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
336
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
337
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
338
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
339
+
340
+ def forward(
341
+ self,
342
+ hidden_states: torch.Tensor,
343
+ key_value_states: Optional[torch.Tensor] = None,
344
+ attention_mask: Optional[torch.Tensor] = None,
345
+ layer_head_mask: Optional[torch.Tensor] = None,
346
+ output_attentions: Optional[bool] = False,
347
+ # TODO: we need a refactor so that the different attention modules can get their specific kwargs
348
+ # ATM, we have mixed things encoder, decoder, and encoder-decoder attn
349
+ **kwargs: Unpack[FlashAttentionKwargs],
350
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
351
+ """Input shape: Batch x Time x Channel"""
352
+
353
+ # if key_value_states are provided this layer is used as a cross-attention layer
354
+ # for the decoder
355
+ is_cross_attention = key_value_states is not None
356
+
357
+ # determine input shapes
358
+ bsz, tgt_len = hidden_states.shape[:-1]
359
+ src_len = key_value_states.shape[1] if is_cross_attention else tgt_len
360
+
361
+ q_input_shape = (bsz, tgt_len, -1, self.head_dim)
362
+ kv_input_shape = (bsz, src_len, -1, self.head_dim)
363
+
364
+ # get query proj
365
+ query_states = self.q_proj(hidden_states).view(*q_input_shape).transpose(1, 2)
366
+
367
+ current_states = key_value_states if is_cross_attention else hidden_states
368
+ key_states = self.k_proj(current_states).view(*kv_input_shape).transpose(1, 2)
369
+ value_states = self.v_proj(current_states).view(*kv_input_shape).transpose(1, 2)
370
+
371
+ attention_interface: Callable = eager_attention_forward
372
+ if self.config._attn_implementation != "eager":
373
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
374
+
375
+ attn_output, attn_weights = attention_interface(
376
+ self,
377
+ query_states,
378
+ key_states,
379
+ value_states,
380
+ attention_mask,
381
+ dropout=0.0 if not self.training else self.dropout,
382
+ scaling=self.scaling,
383
+ output_attentions=output_attentions,
384
+ head_mask=layer_head_mask,
385
+ **kwargs,
386
+ )
387
+
388
+ attn_output = attn_output.reshape(bsz, tgt_len, -1).contiguous()
389
+ attn_output = self.out_proj(attn_output)
390
+
391
+ return attn_output, attn_weights, None
392
+
393
+
394
+ class UniSpeechSatFeedForward(nn.Module):
395
+ def __init__(self, config):
396
+ super().__init__()
397
+ self.intermediate_dropout = nn.Dropout(config.activation_dropout)
398
+
399
+ self.intermediate_dense = nn.Linear(config.hidden_size, config.intermediate_size)
400
+ if isinstance(config.hidden_act, str):
401
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
402
+ else:
403
+ self.intermediate_act_fn = config.hidden_act
404
+
405
+ self.output_dense = nn.Linear(config.intermediate_size, config.hidden_size)
406
+ self.output_dropout = nn.Dropout(config.hidden_dropout)
407
+
408
+ def forward(self, hidden_states):
409
+ hidden_states = self.intermediate_dense(hidden_states)
410
+ hidden_states = self.intermediate_act_fn(hidden_states)
411
+ hidden_states = self.intermediate_dropout(hidden_states)
412
+
413
+ hidden_states = self.output_dense(hidden_states)
414
+ hidden_states = self.output_dropout(hidden_states)
415
+ return hidden_states
416
+
417
+
418
+ class UniSpeechSatEncoderLayer(GradientCheckpointingLayer):
419
+ def __init__(self, config):
420
+ super().__init__()
421
+ self.attention = UniSpeechSatAttention(
422
+ embed_dim=config.hidden_size,
423
+ num_heads=config.num_attention_heads,
424
+ dropout=config.attention_dropout,
425
+ is_decoder=False,
426
+ config=config,
427
+ )
428
+
429
+ self.dropout = nn.Dropout(config.hidden_dropout)
430
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
431
+ self.feed_forward = UniSpeechSatFeedForward(config)
432
+ self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
433
+
434
+ def forward(self, hidden_states, attention_mask=None, output_attentions=False):
435
+ attn_residual = hidden_states
436
+ hidden_states, attn_weights, _ = self.attention(
437
+ hidden_states, attention_mask=attention_mask, output_attentions=output_attentions
438
+ )
439
+ hidden_states = self.dropout(hidden_states)
440
+ hidden_states = attn_residual + hidden_states
441
+
442
+ hidden_states = self.layer_norm(hidden_states)
443
+ hidden_states = hidden_states + self.feed_forward(hidden_states)
444
+ hidden_states = self.final_layer_norm(hidden_states)
445
+
446
+ outputs = (hidden_states,)
447
+
448
+ if output_attentions:
449
+ outputs += (attn_weights,)
450
+
451
+ return outputs
452
+
453
+
454
+ class UniSpeechSatEncoder(nn.Module):
455
+ def __init__(self, config):
456
+ super().__init__()
457
+ self.config = config
458
+ self.pos_conv_embed = UniSpeechSatPositionalConvEmbedding(config)
459
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
460
+ self.dropout = nn.Dropout(config.hidden_dropout)
461
+ self.layers = nn.ModuleList([UniSpeechSatEncoderLayer(config) for _ in range(config.num_hidden_layers)])
462
+ self.gradient_checkpointing = False
463
+
464
+ def forward(
465
+ self,
466
+ hidden_states: torch.tensor,
467
+ attention_mask: Optional[torch.Tensor] = None,
468
+ output_attentions: bool = False,
469
+ output_hidden_states: bool = False,
470
+ return_dict: bool = True,
471
+ ):
472
+ all_hidden_states = () if output_hidden_states else None
473
+ all_self_attentions = () if output_attentions else None
474
+
475
+ if attention_mask is not None:
476
+ # make sure padded tokens output 0
477
+ expand_attention_mask = attention_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
478
+ hidden_states[~expand_attention_mask] = 0
479
+
480
+ attention_mask = self._update_full_mask(
481
+ attention_mask,
482
+ hidden_states,
483
+ )
484
+
485
+ position_embeddings = self.pos_conv_embed(hidden_states)
486
+ hidden_states = hidden_states + position_embeddings
487
+ hidden_states = self.layer_norm(hidden_states)
488
+ hidden_states = self.dropout(hidden_states)
489
+
490
+ synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)
491
+
492
+ for layer in self.layers:
493
+ if output_hidden_states:
494
+ all_hidden_states = all_hidden_states + (hidden_states,)
495
+
496
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
497
+ dropout_probability = torch.rand([])
498
+
499
+ skip_the_layer = self.training and dropout_probability < self.config.layerdrop
500
+ if not skip_the_layer or synced_gpus:
501
+ # under fsdp or deepspeed zero3 all gpus must run in sync
502
+ layer_outputs = layer(
503
+ hidden_states, attention_mask=attention_mask, output_attentions=output_attentions
504
+ )
505
+ hidden_states = layer_outputs[0]
506
+
507
+ if skip_the_layer:
508
+ layer_outputs = (None, None)
509
+
510
+ if output_attentions:
511
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
512
+
513
+ if output_hidden_states:
514
+ all_hidden_states = all_hidden_states + (hidden_states,)
515
+
516
+ if not return_dict:
517
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
518
+ return BaseModelOutput(
519
+ last_hidden_state=hidden_states,
520
+ hidden_states=all_hidden_states,
521
+ attentions=all_self_attentions,
522
+ )
523
+
524
+ def _update_full_mask(
525
+ self,
526
+ attention_mask: Union[torch.Tensor, None],
527
+ inputs_embeds: torch.Tensor,
528
+ ):
529
+ if attention_mask is not None:
530
+ if self.config._attn_implementation == "flash_attention_2":
531
+ attention_mask = attention_mask if 0 in attention_mask else None
532
+ elif self.config._attn_implementation == "sdpa":
533
+ # output_attentions=True & head_mask can not be supported when using SDPA, fall back to
534
+ # the manual implementation that requires a 4D causal mask in all cases.
535
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
536
+ attention_mask = _prepare_4d_attention_mask_for_sdpa(attention_mask, inputs_embeds.dtype)
537
+ elif self.config._attn_implementation == "flex_attention":
538
+ if isinstance(attention_mask, torch.Tensor):
539
+ attention_mask = make_flex_block_causal_mask(attention_mask, is_causal=False)
540
+ else:
541
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
542
+ attention_mask = _prepare_4d_attention_mask(attention_mask, inputs_embeds.dtype)
543
+
544
+ return attention_mask
545
+
546
+
547
+ class UniSpeechSatAttnAdapterLayer(nn.Module):
548
+ def __init__(self, config):
549
+ """
550
+ Implements adapter modules directly with 3D tensor weight as parameters and without using ModuleList to speed
551
+ up training throughput.
552
+ """
553
+ super().__init__()
554
+ self.input_dim = config.adapter_attn_dim
555
+ self.hidden_dim = config.hidden_size
556
+
557
+ self.norm = nn.LayerNorm(self.hidden_dim)
558
+ self.linear_1 = nn.Linear(self.hidden_dim, self.input_dim)
559
+ self.act_fn = nn.ReLU()
560
+ self.linear_2 = nn.Linear(self.input_dim, self.hidden_dim)
561
+
562
+ def forward(self, hidden_states: torch.FloatTensor):
563
+ hidden_states = self.norm(hidden_states)
564
+
565
+ hidden_states = self.linear_1(hidden_states)
566
+ hidden_states = self.act_fn(hidden_states)
567
+ hidden_states = self.linear_2(hidden_states)
568
+
569
+ return hidden_states
570
+
571
+
572
+ class UniSpeechSatEncoderLayerStableLayerNorm(GradientCheckpointingLayer):
573
+ def __init__(self, config):
574
+ super().__init__()
575
+ self.attention = UniSpeechSatAttention(
576
+ embed_dim=config.hidden_size,
577
+ num_heads=config.num_attention_heads,
578
+ dropout=config.attention_dropout,
579
+ is_decoder=False,
580
+ config=config,
581
+ )
582
+ self.dropout = nn.Dropout(config.hidden_dropout)
583
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
584
+ self.feed_forward = UniSpeechSatFeedForward(config)
585
+ self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
586
+
587
+ if getattr(config, "adapter_attn_dim", None) is not None:
588
+ self.adapter_layer = UniSpeechSatAttnAdapterLayer(config)
589
+ else:
590
+ self.adapter_layer = None
591
+
592
+ def forward(
593
+ self,
594
+ hidden_states: torch.Tensor,
595
+ attention_mask: Optional[torch.Tensor] = None,
596
+ output_attentions: bool = False,
597
+ ):
598
+ attn_residual = hidden_states
599
+ hidden_states = self.layer_norm(hidden_states)
600
+ hidden_states, attn_weights, _ = self.attention(
601
+ hidden_states, attention_mask=attention_mask, output_attentions=output_attentions
602
+ )
603
+ hidden_states = self.dropout(hidden_states)
604
+ hidden_states = attn_residual + hidden_states
605
+ hidden_states = hidden_states + self.feed_forward(self.final_layer_norm(hidden_states))
606
+
607
+ if self.adapter_layer is not None:
608
+ hidden_states = hidden_states + self.adapter_layer(hidden_states)
609
+
610
+ outputs = (hidden_states,)
611
+
612
+ if output_attentions:
613
+ outputs += (attn_weights,)
614
+
615
+ return outputs
616
+
617
+
618
+ class UniSpeechSatEncoderStableLayerNorm(nn.Module):
619
+ def __init__(self, config):
620
+ super().__init__()
621
+ self.config = config
622
+ self.pos_conv_embed = UniSpeechSatPositionalConvEmbedding(config)
623
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
624
+ self.dropout = nn.Dropout(config.hidden_dropout)
625
+ self.layers = nn.ModuleList(
626
+ [UniSpeechSatEncoderLayerStableLayerNorm(config) for _ in range(config.num_hidden_layers)]
627
+ )
628
+ self.gradient_checkpointing = False
629
+
630
+ def forward(
631
+ self,
632
+ hidden_states,
633
+ attention_mask=None,
634
+ output_attentions=False,
635
+ output_hidden_states=False,
636
+ return_dict=True,
637
+ ):
638
+ all_hidden_states = () if output_hidden_states else None
639
+ all_self_attentions = () if output_attentions else None
640
+
641
+ if attention_mask is not None:
642
+ # make sure padded tokens output 0
643
+ expand_attention_mask = attention_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
644
+ hidden_states[~expand_attention_mask] = 0
645
+
646
+ attention_mask = self._update_full_mask(
647
+ attention_mask,
648
+ hidden_states,
649
+ )
650
+
651
+ position_embeddings = self.pos_conv_embed(hidden_states)
652
+ hidden_states = hidden_states + position_embeddings
653
+ hidden_states = self.dropout(hidden_states)
654
+
655
+ synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)
656
+
657
+ for layer in self.layers:
658
+ if output_hidden_states:
659
+ all_hidden_states = all_hidden_states + (hidden_states,)
660
+
661
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
662
+ dropout_probability = torch.rand([])
663
+
664
+ skip_the_layer = self.training and dropout_probability < self.config.layerdrop
665
+ if not skip_the_layer or synced_gpus:
666
+ # under fsdp or deepspeed zero3 all gpus must run in sync
667
+ # XXX: could optimize this like synced_gpus in generate_utils but not sure if it's worth the code complication
668
+ layer_outputs = layer(
669
+ hidden_states, attention_mask=attention_mask, output_attentions=output_attentions
670
+ )
671
+ hidden_states = layer_outputs[0]
672
+
673
+ if skip_the_layer:
674
+ layer_outputs = (None, None)
675
+
676
+ if output_attentions:
677
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
678
+
679
+ hidden_states = self.layer_norm(hidden_states)
680
+
681
+ if output_hidden_states:
682
+ all_hidden_states = all_hidden_states + (hidden_states,)
683
+
684
+ if not return_dict:
685
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
686
+ return BaseModelOutput(
687
+ last_hidden_state=hidden_states,
688
+ hidden_states=all_hidden_states,
689
+ attentions=all_self_attentions,
690
+ )
691
+
692
+ def _update_full_mask(
693
+ self,
694
+ attention_mask: Union[torch.Tensor, None],
695
+ inputs_embeds: torch.Tensor,
696
+ ):
697
+ if attention_mask is not None:
698
+ if self.config._attn_implementation == "flash_attention_2":
699
+ attention_mask = attention_mask if 0 in attention_mask else None
700
+ elif self.config._attn_implementation == "sdpa":
701
+ # output_attentions=True & head_mask can not be supported when using SDPA, fall back to
702
+ # the manual implementation that requires a 4D causal mask in all cases.
703
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
704
+ attention_mask = _prepare_4d_attention_mask_for_sdpa(attention_mask, inputs_embeds.dtype)
705
+ elif self.config._attn_implementation == "flex_attention":
706
+ if isinstance(attention_mask, torch.Tensor):
707
+ attention_mask = make_flex_block_causal_mask(attention_mask, is_causal=False)
708
+ else:
709
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
710
+ attention_mask = _prepare_4d_attention_mask(attention_mask, inputs_embeds.dtype)
711
+
712
+ return attention_mask
713
+
714
+
715
+ class UniSpeechSatGumbelVectorQuantizer(nn.Module):
716
+ """
717
+ Vector quantization using gumbel softmax. See `[CATEGORICAL REPARAMETERIZATION WITH
718
+ GUMBEL-SOFTMAX](https://huggingface.co/papers/1611.01144) for more information.
719
+ """
720
+
721
+ def __init__(self, config):
722
+ super().__init__()
723
+ self.num_groups = config.num_codevector_groups
724
+ self.num_vars = config.num_codevectors_per_group
725
+
726
+ if config.codevector_dim % self.num_groups != 0:
727
+ raise ValueError(
728
+ f"`config.codevector_dim {config.codevector_dim} must be divisible "
729
+ f"by `config.num_codevector_groups` {self.num_groups} for concatenation"
730
+ )
731
+
732
+ # storage for codebook variables (codewords)
733
+ self.codevectors = nn.Parameter(
734
+ torch.FloatTensor(1, self.num_groups * self.num_vars, config.codevector_dim // self.num_groups)
735
+ )
736
+ self.weight_proj = nn.Linear(config.hidden_size, self.num_groups * self.num_vars)
737
+
738
+ # can be decayed for training
739
+ self.temperature = 2
740
+
741
+ @staticmethod
742
+ def _compute_perplexity(probs, mask=None):
743
+ marginal_probs = probs.mean(dim=0)
744
+ perplexity = torch.exp(-torch.sum(marginal_probs * torch.log(marginal_probs + 1e-7), dim=-1)).sum()
745
+ return perplexity
746
+
747
+ def forward(self, hidden_states):
748
+ batch_size, sequence_length, hidden_size = hidden_states.shape
749
+
750
+ # project to codevector dim
751
+ hidden_states = self.weight_proj(hidden_states)
752
+ hidden_states = hidden_states.view(batch_size * sequence_length * self.num_groups, -1)
753
+
754
+ if self.training:
755
+ # sample code vector probs via gumbel in differentiateable way
756
+ codevector_probs = nn.functional.gumbel_softmax(
757
+ hidden_states.float(), tau=self.temperature, hard=True
758
+ ).type_as(hidden_states)
759
+
760
+ # compute perplexity
761
+ codevector_soft_dist = torch.softmax(
762
+ hidden_states.view(batch_size * sequence_length, self.num_groups, -1).float(), dim=-1
763
+ )
764
+ perplexity = self._compute_perplexity(codevector_soft_dist)
765
+ else:
766
+ # take argmax in non-differentiable way
767
+ # comptute hard codevector distribution (one hot)
768
+ codevector_idx = hidden_states.argmax(dim=-1)
769
+ codevector_probs = hidden_states.new_zeros(*hidden_states.shape).scatter_(
770
+ -1, codevector_idx.view(-1, 1), 1.0
771
+ )
772
+ codevector_probs = codevector_probs.view(batch_size * sequence_length, self.num_groups, -1)
773
+
774
+ perplexity = self._compute_perplexity(codevector_probs)
775
+
776
+ codevector_probs = codevector_probs.view(batch_size * sequence_length, -1)
777
+ # use probs to retrieve codevectors
778
+ codevectors_per_group = codevector_probs.unsqueeze(-1) * self.codevectors
779
+ codevectors = codevectors_per_group.view(batch_size * sequence_length, self.num_groups, self.num_vars, -1)
780
+ codevectors = codevectors.sum(-2).view(batch_size, sequence_length, -1)
781
+
782
+ return codevectors, perplexity
783
+
784
+
785
+ @auto_docstring
786
+ class UniSpeechSatPreTrainedModel(PreTrainedModel):
787
+ config: UniSpeechSatConfig
788
+ base_model_prefix = "unispeech_sat"
789
+ main_input_name = "input_values"
790
+ supports_gradient_checkpointing = True
791
+ _supports_flash_attn = True
792
+ _supports_sdpa = True
793
+ _supports_flex_attn = True
794
+
795
+ def _init_weights(self, module):
796
+ """Initialize the weights"""
797
+ # gumbel softmax requires special init
798
+ if isinstance(module, UniSpeechSatGumbelVectorQuantizer):
799
+ module.weight_proj.weight.data.normal_(mean=0.0, std=1)
800
+ module.weight_proj.bias.data.zero_()
801
+ nn.init.uniform_(module.codevectors)
802
+ elif isinstance(module, UniSpeechSatPositionalConvEmbedding):
803
+ nn.init.normal_(
804
+ module.conv.weight,
805
+ mean=0,
806
+ std=2 * math.sqrt(1 / (module.conv.kernel_size[0] * module.conv.in_channels)),
807
+ )
808
+ nn.init.constant_(module.conv.bias, 0)
809
+ elif isinstance(module, UniSpeechSatFeatureProjection):
810
+ k = math.sqrt(1 / module.projection.in_features)
811
+ nn.init.uniform_(module.projection.weight, a=-k, b=k)
812
+ nn.init.uniform_(module.projection.bias, a=-k, b=k)
813
+ elif isinstance(module, nn.Linear):
814
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
815
+
816
+ if module.bias is not None:
817
+ module.bias.data.zero_()
818
+ elif isinstance(module, (nn.LayerNorm, nn.GroupNorm)):
819
+ module.bias.data.zero_()
820
+ module.weight.data.fill_(1.0)
821
+ elif isinstance(module, nn.Conv1d):
822
+ nn.init.kaiming_normal_(module.weight)
823
+
824
+ if module.bias is not None:
825
+ k = math.sqrt(module.groups / (module.in_channels * module.kernel_size[0]))
826
+ nn.init.uniform_(module.bias, a=-k, b=k)
827
+
828
+ def _get_feat_extract_output_lengths(self, input_lengths: Union[torch.LongTensor, int]):
829
+ """
830
+ Computes the output length of the convolutional layers
831
+ """
832
+
833
+ def _conv_out_length(input_length, kernel_size, stride):
834
+ # 1D convolutional layer output length formula taken
835
+ # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
836
+ return torch.div(input_length - kernel_size, stride, rounding_mode="floor") + 1
837
+
838
+ for kernel_size, stride in zip(self.config.conv_kernel, self.config.conv_stride):
839
+ input_lengths = _conv_out_length(input_lengths, kernel_size, stride)
840
+
841
+ return input_lengths
842
+
843
+ def _get_feature_vector_attention_mask(self, feature_vector_length: int, attention_mask: torch.LongTensor):
844
+ # Effectively attention_mask.sum(-1), but not inplace to be able to run
845
+ # on inference mode.
846
+ non_padded_lengths = attention_mask.cumsum(dim=-1)[:, -1]
847
+ output_lengths = self._get_feat_extract_output_lengths(non_padded_lengths).to(torch.long)
848
+ batch_size = attention_mask.shape[0]
849
+
850
+ attention_mask = torch.zeros(
851
+ (batch_size, feature_vector_length), dtype=attention_mask.dtype, device=attention_mask.device
852
+ )
853
+ # these two operations makes sure that all values before the output lengths idxs are attended to
854
+ attention_mask[(torch.arange(attention_mask.shape[0], device=attention_mask.device), output_lengths - 1)] = 1
855
+ attention_mask = attention_mask.flip([-1]).cumsum(-1).flip([-1]).bool()
856
+ return attention_mask
857
+
858
+
859
+ def _compute_mask_indices(
860
+ shape: tuple[int, int],
861
+ mask_prob: float,
862
+ mask_length: int,
863
+ attention_mask: Optional[torch.LongTensor] = None,
864
+ min_masks: int = 0,
865
+ ) -> np.ndarray:
866
+ """
867
+ Computes random mask spans for a given shape. Used to implement [SpecAugment: A Simple Data Augmentation Method for
868
+ ASR](https://huggingface.co/papers/1904.08779). Note that this method is not optimized to run on TPU and should be run on
869
+ CPU as part of the preprocessing during training.
870
+
871
+ Args:
872
+ shape: The shape for which to compute masks. This should be of a tuple of size 2 where
873
+ the first element is the batch size and the second element is the length of the axis to span.
874
+ mask_prob: The percentage of the whole axis (between 0 and 1) which will be masked. The number of
875
+ independently generated mask spans of length `mask_length` is computed by
876
+ `mask_prob*shape[1]/mask_length`. Note that due to overlaps, `mask_prob` is an upper bound and the
877
+ actual percentage will be smaller.
878
+ mask_length: size of the mask
879
+ min_masks: minimum number of masked spans
880
+ attention_mask: A (right-padded) attention mask which independently shortens the feature axis of
881
+ each batch dimension.
882
+ """
883
+ batch_size, sequence_length = shape
884
+
885
+ if mask_length < 1:
886
+ raise ValueError("`mask_length` has to be bigger than 0.")
887
+
888
+ if mask_length > sequence_length:
889
+ raise ValueError(
890
+ f"`mask_length` has to be smaller than `sequence_length`, but got `mask_length`: {mask_length}"
891
+ f" and `sequence_length`: {sequence_length}`"
892
+ )
893
+
894
+ # epsilon is used for probabilistic rounding
895
+ epsilon = np.random.rand(1).item()
896
+
897
+ def compute_num_masked_span(input_length):
898
+ """Given input length, compute how many spans should be masked"""
899
+ num_masked_span = int(mask_prob * input_length / mask_length + epsilon)
900
+ num_masked_span = max(num_masked_span, min_masks)
901
+
902
+ # make sure num masked span <= sequence_length
903
+ if num_masked_span * mask_length > sequence_length:
904
+ num_masked_span = sequence_length // mask_length
905
+
906
+ # make sure num_masked span is also <= input_length - (mask_length - 1)
907
+ if input_length - (mask_length - 1) < num_masked_span:
908
+ num_masked_span = max(input_length - (mask_length - 1), 0)
909
+
910
+ return num_masked_span
911
+
912
+ # compute number of masked spans in batch
913
+ input_lengths = (
914
+ attention_mask.detach().sum(-1).tolist()
915
+ if attention_mask is not None
916
+ else [sequence_length for _ in range(batch_size)]
917
+ )
918
+
919
+ # SpecAugment mask to fill
920
+ spec_aug_mask = np.zeros((batch_size, sequence_length), dtype=bool)
921
+ spec_aug_mask_idxs = []
922
+
923
+ max_num_masked_span = compute_num_masked_span(sequence_length)
924
+
925
+ if max_num_masked_span == 0:
926
+ return spec_aug_mask
927
+
928
+ for input_length in input_lengths:
929
+ # compute num of masked spans for this input
930
+ num_masked_span = compute_num_masked_span(input_length)
931
+
932
+ # get random indices to mask
933
+ spec_aug_mask_idx = np.random.choice(
934
+ np.arange(input_length - (mask_length - 1)), num_masked_span, replace=False
935
+ )
936
+
937
+ # pick first sampled index that will serve as a dummy index to pad vector
938
+ # to ensure same dimension for all batches due to probabilistic rounding
939
+ # Picking first sample just pads those vectors twice.
940
+ if len(spec_aug_mask_idx) == 0:
941
+ # this case can only happen if `input_length` is strictly smaller then
942
+ # `sequence_length` in which case the last token has to be a padding
943
+ # token which we can use as a dummy mask id
944
+ dummy_mask_idx = sequence_length - 1
945
+ else:
946
+ dummy_mask_idx = spec_aug_mask_idx[0]
947
+
948
+ spec_aug_mask_idx = np.concatenate(
949
+ [spec_aug_mask_idx, np.ones(max_num_masked_span - num_masked_span, dtype=np.int32) * dummy_mask_idx]
950
+ )
951
+ spec_aug_mask_idxs.append(spec_aug_mask_idx)
952
+
953
+ spec_aug_mask_idxs = np.array(spec_aug_mask_idxs)
954
+
955
+ # expand masked indices to masked spans
956
+ spec_aug_mask_idxs = np.broadcast_to(
957
+ spec_aug_mask_idxs[:, :, None], (batch_size, max_num_masked_span, mask_length)
958
+ )
959
+ spec_aug_mask_idxs = spec_aug_mask_idxs.reshape(batch_size, max_num_masked_span * mask_length)
960
+
961
+ # add offset to the starting indexes so that indexes now create a span
962
+ offsets = np.arange(mask_length)[None, None, :]
963
+ offsets = np.broadcast_to(offsets, (batch_size, max_num_masked_span, mask_length)).reshape(
964
+ batch_size, max_num_masked_span * mask_length
965
+ )
966
+ spec_aug_mask_idxs = spec_aug_mask_idxs + offsets
967
+
968
+ # ensure that we cannot have indices larger than sequence_length
969
+ if spec_aug_mask_idxs.max() > sequence_length - 1:
970
+ spec_aug_mask_idxs[spec_aug_mask_idxs > sequence_length - 1] = sequence_length - 1
971
+
972
+ # scatter indices to mask
973
+ np.put_along_axis(spec_aug_mask, spec_aug_mask_idxs, 1, -1)
974
+
975
+ return spec_aug_mask
976
+
977
+
978
+ UniSpeechSatBaseModelOutput = Wav2Vec2BaseModelOutput
979
+
980
+
981
+ @auto_docstring
982
+ class UniSpeechSatModel(UniSpeechSatPreTrainedModel):
983
+ def __init__(self, config: UniSpeechSatConfig):
984
+ super().__init__(config)
985
+ self.config = config
986
+ self.feature_extractor = UniSpeechSatFeatureEncoder(config)
987
+ self.feature_projection = UniSpeechSatFeatureProjection(config)
988
+
989
+ self.masked_spec_embed = nn.Parameter(torch.Tensor(config.hidden_size).uniform_())
990
+
991
+ if config.do_stable_layer_norm:
992
+ self.encoder = UniSpeechSatEncoderStableLayerNorm(config)
993
+ else:
994
+ self.encoder = UniSpeechSatEncoder(config)
995
+
996
+ # Initialize weights and apply final processing
997
+ self.post_init()
998
+
999
+ def _mask_hidden_states(
1000
+ self,
1001
+ hidden_states: torch.FloatTensor,
1002
+ mask_time_indices: Optional[torch.FloatTensor] = None,
1003
+ attention_mask: Optional[torch.LongTensor] = None,
1004
+ ):
1005
+ """
1006
+ Masks extracted features along time axis and/or along feature axis according to
1007
+ [SpecAugment](https://huggingface.co/papers/1904.08779).
1008
+ """
1009
+
1010
+ # `config.apply_spec_augment` can set masking to False
1011
+ if not getattr(self.config, "apply_spec_augment", True):
1012
+ return hidden_states
1013
+
1014
+ # generate indices & apply SpecAugment along time axis
1015
+ batch_size, sequence_length, hidden_size = hidden_states.size()
1016
+
1017
+ if mask_time_indices is not None:
1018
+ # apply SpecAugment along time axis with given mask_time_indices
1019
+ hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype)
1020
+ elif self.config.mask_time_prob > 0 and self.training:
1021
+ mask_time_indices = _compute_mask_indices(
1022
+ (batch_size, sequence_length),
1023
+ mask_prob=self.config.mask_time_prob,
1024
+ mask_length=self.config.mask_time_length,
1025
+ attention_mask=attention_mask,
1026
+ min_masks=self.config.mask_time_min_masks,
1027
+ )
1028
+ mask_time_indices = torch.tensor(mask_time_indices, device=hidden_states.device, dtype=torch.bool)
1029
+ hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype)
1030
+
1031
+ if self.config.mask_feature_prob > 0 and self.training:
1032
+ # generate indices & apply SpecAugment along feature axis
1033
+ mask_feature_indices = _compute_mask_indices(
1034
+ (batch_size, hidden_size),
1035
+ mask_prob=self.config.mask_feature_prob,
1036
+ mask_length=self.config.mask_feature_length,
1037
+ min_masks=self.config.mask_feature_min_masks,
1038
+ )
1039
+ mask_feature_indices = torch.tensor(mask_feature_indices, device=hidden_states.device, dtype=torch.bool)
1040
+ mask_feature_indices = mask_feature_indices[:, None].expand(-1, sequence_length, -1)
1041
+ hidden_states[mask_feature_indices] = 0
1042
+
1043
+ return hidden_states
1044
+
1045
+ @auto_docstring
1046
+ def forward(
1047
+ self,
1048
+ input_values: Optional[torch.Tensor],
1049
+ attention_mask: Optional[torch.Tensor] = None,
1050
+ mask_time_indices: Optional[torch.FloatTensor] = None,
1051
+ output_attentions: Optional[bool] = None,
1052
+ output_hidden_states: Optional[bool] = None,
1053
+ return_dict: Optional[bool] = None,
1054
+ ) -> Union[tuple, UniSpeechSatBaseModelOutput]:
1055
+ r"""
1056
+ mask_time_indices (`torch.BoolTensor` of shape `(batch_size, sequence_length)`, *optional*):
1057
+ Indices to mask extracted features for contrastive loss. When in training mode, model learns to predict
1058
+ masked extracted features in *config.proj_codevector_dim* space.
1059
+ """
1060
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1061
+ output_hidden_states = (
1062
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1063
+ )
1064
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1065
+
1066
+ extract_features = self.feature_extractor(input_values)
1067
+ extract_features = extract_features.transpose(1, 2)
1068
+
1069
+ if attention_mask is not None:
1070
+ # compute reduced attention_mask corresponding to feature vectors
1071
+ attention_mask = self._get_feature_vector_attention_mask(extract_features.shape[1], attention_mask)
1072
+
1073
+ hidden_states, extract_features = self.feature_projection(extract_features)
1074
+ hidden_states = self._mask_hidden_states(
1075
+ hidden_states, mask_time_indices=mask_time_indices, attention_mask=attention_mask
1076
+ )
1077
+
1078
+ encoder_outputs = self.encoder(
1079
+ hidden_states,
1080
+ attention_mask=attention_mask,
1081
+ output_attentions=output_attentions,
1082
+ output_hidden_states=output_hidden_states,
1083
+ return_dict=return_dict,
1084
+ )
1085
+
1086
+ hidden_states = encoder_outputs[0]
1087
+
1088
+ if not return_dict:
1089
+ return (hidden_states, extract_features) + encoder_outputs[1:]
1090
+
1091
+ return UniSpeechSatBaseModelOutput(
1092
+ last_hidden_state=hidden_states,
1093
+ extract_features=extract_features,
1094
+ hidden_states=encoder_outputs.hidden_states,
1095
+ attentions=encoder_outputs.attentions,
1096
+ )
1097
+
1098
+
1099
+ @auto_docstring(
1100
+ custom_intro="""
1101
+ UniSpeechSat Model with a vector-quantization module and ctc loss for pre-training.
1102
+ """
1103
+ )
1104
+ class UniSpeechSatForPreTraining(UniSpeechSatPreTrainedModel):
1105
+ def __init__(self, config: UniSpeechSatConfig):
1106
+ super().__init__(config)
1107
+ self.unispeech_sat = UniSpeechSatModel(config)
1108
+ self.dropout_features = nn.Dropout(config.feat_quantizer_dropout)
1109
+
1110
+ self.quantizer = UniSpeechSatGumbelVectorQuantizer(config)
1111
+ self.project_q = nn.Linear(config.codevector_dim, config.proj_codevector_dim)
1112
+ self.project_hid = nn.Linear(config.hidden_size, config.proj_codevector_dim)
1113
+
1114
+ self.dropout = nn.Dropout(config.final_dropout)
1115
+
1116
+ self.speaker_proj = nn.Linear(config.hidden_size, config.codevector_dim)
1117
+ self.label_embeddings_concat = nn.Parameter(torch.FloatTensor(config.num_clusters, config.codevector_dim))
1118
+ self.label_embeddings_concat.data.zero_()
1119
+
1120
+ self.layer_norm_for_extract = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
1121
+ if self.config.do_stable_layer_norm:
1122
+ self.layer_norm_for_extract.requires_grad = False
1123
+
1124
+ # Initialize weights and apply final processing
1125
+ self.post_init()
1126
+
1127
+ def set_gumbel_temperature(self, temperature: int):
1128
+ """
1129
+ Set the Gumbel softmax temperature to a given value. Only necessary for training
1130
+ """
1131
+ self.quantizer.temperature = temperature
1132
+
1133
+ def freeze_feature_extractor(self):
1134
+ """
1135
+ Calling this function will disable the gradient computation for the feature encoder so that its parameters will
1136
+ not be updated during training.
1137
+ """
1138
+ warnings.warn(
1139
+ "The method `freeze_feature_extractor` is deprecated and will be removed in Transformers v5. "
1140
+ "Please use the equivalent `freeze_feature_encoder` method instead.",
1141
+ FutureWarning,
1142
+ )
1143
+ self.freeze_feature_encoder()
1144
+
1145
+ def freeze_feature_encoder(self):
1146
+ """
1147
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
1148
+ not be updated during training.
1149
+ """
1150
+ self.unispeech_sat.feature_extractor._freeze_parameters()
1151
+
1152
+ @staticmethod
1153
+ def compute_contrastive_logits(
1154
+ target_features: torch.FloatTensor,
1155
+ negative_features: torch.FloatTensor,
1156
+ predicted_features: torch.FloatTensor,
1157
+ temperature: int = 1,
1158
+ ):
1159
+ """
1160
+ Compute logits for contrastive loss based using cosine similarity as the distance measure between
1161
+ `[positive_feature, negative_features]` and `[predicted_features]`. Additionally, temperature can be applied.
1162
+ """
1163
+ target_features = torch.cat([target_features, negative_features], dim=0)
1164
+
1165
+ logits = torch.cosine_similarity(predicted_features.float(), target_features.float(), dim=-1)
1166
+ logits = logits.type_as(target_features)
1167
+
1168
+ # apply temperature
1169
+ logits = logits / temperature
1170
+ return logits
1171
+
1172
+ @auto_docstring
1173
+ def forward(
1174
+ self,
1175
+ input_values: Optional[torch.Tensor],
1176
+ attention_mask: Optional[torch.Tensor] = None,
1177
+ output_attentions: Optional[bool] = None,
1178
+ output_hidden_states: Optional[bool] = None,
1179
+ return_dict: Optional[bool] = None,
1180
+ ) -> Union[tuple, UniSpeechSatForPreTrainingOutput]:
1181
+ r"""
1182
+ Example:
1183
+
1184
+ ```python
1185
+ >>> import torch
1186
+ >>> from transformers import AutoFeatureExtractor, UniSpeechSatForPreTraining
1187
+ >>> from transformers.models.unispeech_sat.modeling_unispeech_sat import _compute_mask_indices
1188
+
1189
+ >>> feature_extractor = AutoFeatureExtractor.from_pretrained("microsoft/unispeech-sat-base")
1190
+ >>> model = UniSpeechSatForPreTraining.from_pretrained("microsoft/unispeech-sat-base")
1191
+ >>> # TODO: Add full pretraining example
1192
+ ```"""
1193
+
1194
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1195
+
1196
+ outputs = self.unispeech_sat(
1197
+ input_values,
1198
+ attention_mask=attention_mask,
1199
+ output_attentions=output_attentions,
1200
+ output_hidden_states=output_hidden_states,
1201
+ return_dict=return_dict,
1202
+ )
1203
+ transformer_features = outputs[0]
1204
+
1205
+ # quantize all (unmasked) extracted features and project to final vq dim
1206
+ extract_features = self.dropout_features(outputs[1])
1207
+
1208
+ # TODO(PVP) - add pretraining logic and add to tests
1209
+ logits = extract_features
1210
+ loss = quantized_features = codevector_perplexity = None
1211
+
1212
+ if not return_dict:
1213
+ if loss is not None:
1214
+ return (loss, logits, transformer_features, quantized_features, codevector_perplexity) + outputs[2:]
1215
+ return (logits, transformer_features, quantized_features, codevector_perplexity) + outputs[2:]
1216
+
1217
+ return UniSpeechSatForPreTrainingOutput(
1218
+ loss=loss,
1219
+ logits=logits,
1220
+ projected_states=transformer_features,
1221
+ projected_quantized_states=quantized_features,
1222
+ codevector_perplexity=codevector_perplexity,
1223
+ hidden_states=outputs.hidden_states,
1224
+ attentions=outputs.attentions,
1225
+ )
1226
+
1227
+
1228
+ _HIDDEN_STATES_START_POSITION = 2
1229
+
1230
+
1231
+ @auto_docstring(
1232
+ custom_intro="""
1233
+ UniSpeechSat Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).
1234
+ """
1235
+ )
1236
+ class UniSpeechSatForCTC(UniSpeechSatPreTrainedModel):
1237
+ def __init__(self, config, target_lang: Optional[str] = None):
1238
+ r"""
1239
+ target_lang (`str`, *optional*):
1240
+ Language id of adapter weights. Adapter weights are stored in the format adapter.<lang>.safetensors or
1241
+ adapter.<lang>.bin. Only relevant when using an instance of [`UniSpeechSatForCTC`] with adapters. Uses 'eng' by
1242
+ default.
1243
+ """
1244
+ super().__init__(config)
1245
+
1246
+ self.unispeech_sat = UniSpeechSatModel(config)
1247
+ self.dropout = nn.Dropout(config.final_dropout)
1248
+
1249
+ self.target_lang = target_lang
1250
+
1251
+ if config.vocab_size is None:
1252
+ raise ValueError(
1253
+ f"You are trying to instantiate {self.__class__} with a configuration that "
1254
+ "does not define the vocabulary size of the language model head. Please "
1255
+ "instantiate the model as follows: `UniSpeechSatForCTC.from_pretrained(..., vocab_size=vocab_size)`. "
1256
+ "or define `vocab_size` of your model's configuration."
1257
+ )
1258
+ output_hidden_size = (
1259
+ config.output_hidden_size if hasattr(config, "add_adapter") and config.add_adapter else config.hidden_size
1260
+ )
1261
+ self.lm_head = nn.Linear(output_hidden_size, config.vocab_size)
1262
+
1263
+ # Initialize weights and apply final processing
1264
+ self.post_init()
1265
+
1266
+ def tie_weights(self):
1267
+ """
1268
+ This method overwrites [`~PreTrainedModel.tie_weights`] so that adapter weights can be correctly loaded when
1269
+ passing `target_lang=...` to `from_pretrained(...)`.
1270
+
1271
+ This method is **not** supposed to be called by the user and is prone to be changed in the future.
1272
+ """
1273
+
1274
+ # Note that `tie_weights` is usually used to tie input and output embedding weights. The method is re-purposed to
1275
+ # correctly load adapter layers for UniSpeechSat so that we do not have to introduce a new API to
1276
+ # [`PreTrainedModel`]. While slightly hacky, UniSpeechSat never has to tie input and output embeddings, so that it is
1277
+ # ok to repurpose this function here.
1278
+ target_lang = self.target_lang
1279
+
1280
+ if target_lang is not None and getattr(self.config, "adapter_attn_dim", None) is None:
1281
+ raise ValueError(f"Cannot pass `target_lang`: {target_lang} if `config.adapter_attn_dim` is not defined.")
1282
+ elif target_lang is None and getattr(self.config, "adapter_attn_dim", None) is not None:
1283
+ logger.info("By default `target_lang` is set to 'eng'.")
1284
+ elif target_lang is not None:
1285
+ self.load_adapter(target_lang, force_load=True)
1286
+
1287
+ def freeze_feature_extractor(self):
1288
+ """
1289
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
1290
+ not be updated during training.
1291
+ """
1292
+ warnings.warn(
1293
+ "The method `freeze_feature_extractor` is deprecated and will be removed in Transformers v5. "
1294
+ "Please use the equivalent `freeze_feature_encoder` method instead.",
1295
+ FutureWarning,
1296
+ )
1297
+ self.freeze_feature_encoder()
1298
+
1299
+ def freeze_feature_encoder(self):
1300
+ """
1301
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
1302
+ not be updated during training.
1303
+ """
1304
+ self.unispeech_sat.feature_extractor._freeze_parameters()
1305
+
1306
+ def freeze_base_model(self):
1307
+ """
1308
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
1309
+ be updated during training. Only the classification head will be updated.
1310
+ """
1311
+ for param in self.unispeech_sat.parameters():
1312
+ param.requires_grad = False
1313
+
1314
+ @auto_docstring
1315
+ def forward(
1316
+ self,
1317
+ input_values: Optional[torch.Tensor],
1318
+ attention_mask: Optional[torch.Tensor] = None,
1319
+ output_attentions: Optional[bool] = None,
1320
+ output_hidden_states: Optional[bool] = None,
1321
+ return_dict: Optional[bool] = None,
1322
+ labels: Optional[torch.Tensor] = None,
1323
+ ) -> Union[tuple, CausalLMOutput]:
1324
+ r"""
1325
+ labels (`torch.LongTensor` of shape `(batch_size, target_length)`, *optional*):
1326
+ Labels for connectionist temporal classification. Note that `target_length` has to be smaller or equal to
1327
+ the sequence length of the output logits. Indices are selected in `[-100, 0, ..., config.vocab_size - 1]`.
1328
+ All labels set to `-100` are ignored (masked), the loss is only computed for labels in `[0, ...,
1329
+ config.vocab_size - 1]`.
1330
+ """
1331
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1332
+
1333
+ if labels is not None and labels.max() >= self.config.vocab_size:
1334
+ raise ValueError(f"Label values must be <= vocab_size: {self.config.vocab_size}")
1335
+
1336
+ outputs = self.unispeech_sat(
1337
+ input_values,
1338
+ attention_mask=attention_mask,
1339
+ output_attentions=output_attentions,
1340
+ output_hidden_states=output_hidden_states,
1341
+ return_dict=return_dict,
1342
+ )
1343
+
1344
+ hidden_states = outputs[0]
1345
+ hidden_states = self.dropout(hidden_states)
1346
+
1347
+ logits = self.lm_head(hidden_states)
1348
+
1349
+ loss = None
1350
+ if labels is not None:
1351
+ # retrieve loss input_lengths from attention_mask
1352
+ attention_mask = (
1353
+ attention_mask if attention_mask is not None else torch.ones_like(input_values, dtype=torch.long)
1354
+ )
1355
+ input_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(-1)).to(torch.long)
1356
+
1357
+ # assuming that padded tokens are filled with -100
1358
+ # when not being attended to
1359
+ labels_mask = labels >= 0
1360
+ target_lengths = labels_mask.sum(-1)
1361
+ flattened_targets = labels.masked_select(labels_mask)
1362
+
1363
+ # ctc_loss doesn't support fp16
1364
+ log_probs = nn.functional.log_softmax(logits, dim=-1, dtype=torch.float32).transpose(0, 1)
1365
+
1366
+ with torch.backends.cudnn.flags(enabled=False):
1367
+ loss = nn.functional.ctc_loss(
1368
+ log_probs,
1369
+ flattened_targets,
1370
+ input_lengths,
1371
+ target_lengths,
1372
+ blank=self.config.pad_token_id,
1373
+ reduction=self.config.ctc_loss_reduction,
1374
+ zero_infinity=self.config.ctc_zero_infinity,
1375
+ )
1376
+
1377
+ if not return_dict:
1378
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
1379
+ return ((loss,) + output) if loss is not None else output
1380
+
1381
+ return CausalLMOutput(
1382
+ loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions
1383
+ )
1384
+
1385
+
1386
+ @auto_docstring(
1387
+ custom_intro="""
1388
+ UniSpeechSat Model with a sequence classification head on top (a linear layer over the pooled output) for tasks like
1389
+ SUPERB Keyword Spotting.
1390
+ """
1391
+ )
1392
+ class UniSpeechSatForSequenceClassification(UniSpeechSatPreTrainedModel):
1393
+ def __init__(self, config):
1394
+ super().__init__(config)
1395
+
1396
+ if hasattr(config, "add_adapter") and config.add_adapter:
1397
+ raise ValueError(
1398
+ "Sequence classification does not support the use of UniSpeechSat adapters (config.add_adapter=True)"
1399
+ )
1400
+ self.unispeech_sat = UniSpeechSatModel(config)
1401
+ num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings
1402
+ if config.use_weighted_layer_sum:
1403
+ self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)
1404
+ self.projector = nn.Linear(config.hidden_size, config.classifier_proj_size)
1405
+ self.classifier = nn.Linear(config.classifier_proj_size, config.num_labels)
1406
+
1407
+ # Initialize weights and apply final processing
1408
+ self.post_init()
1409
+
1410
+ def freeze_feature_extractor(self):
1411
+ """
1412
+ Calling this function will disable the gradient computation for the feature encoder so that its parameters will
1413
+ not be updated during training.
1414
+ """
1415
+ warnings.warn(
1416
+ "The method `freeze_feature_extractor` is deprecated and will be removed in Transformers v5. "
1417
+ "Please use the equivalent `freeze_feature_encoder` method instead.",
1418
+ FutureWarning,
1419
+ )
1420
+ self.freeze_feature_encoder()
1421
+
1422
+ def freeze_feature_encoder(self):
1423
+ """
1424
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
1425
+ not be updated during training.
1426
+ """
1427
+ self.unispeech_sat.feature_extractor._freeze_parameters()
1428
+
1429
+ def freeze_base_model(self):
1430
+ """
1431
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
1432
+ be updated during training. Only the classification head will be updated.
1433
+ """
1434
+ for param in self.unispeech_sat.parameters():
1435
+ param.requires_grad = False
1436
+
1437
+ @auto_docstring
1438
+ def forward(
1439
+ self,
1440
+ input_values: Optional[torch.Tensor],
1441
+ attention_mask: Optional[torch.Tensor] = None,
1442
+ output_attentions: Optional[bool] = None,
1443
+ output_hidden_states: Optional[bool] = None,
1444
+ return_dict: Optional[bool] = None,
1445
+ labels: Optional[torch.Tensor] = None,
1446
+ ) -> Union[tuple, SequenceClassifierOutput]:
1447
+ r"""
1448
+ input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
1449
+ Float values of input raw speech waveform. Values can be obtained by loading a `.flac` or `.wav` audio file
1450
+ into an array of type `list[float]`, a `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library
1451
+ (`pip install torchcodec`) or the soundfile library (`pip install soundfile`).
1452
+ To prepare the array into `input_values`, the [`AutoProcessor`] should be used for padding and conversion
1453
+ into a tensor of type `torch.FloatTensor`. See [`UniSpeechSatProcessor.__call__`] for details.
1454
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1455
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1456
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1457
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1458
+ """
1459
+
1460
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1461
+ output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
1462
+
1463
+ outputs = self.unispeech_sat(
1464
+ input_values,
1465
+ attention_mask=attention_mask,
1466
+ output_attentions=output_attentions,
1467
+ output_hidden_states=output_hidden_states,
1468
+ return_dict=return_dict,
1469
+ )
1470
+
1471
+ if self.config.use_weighted_layer_sum:
1472
+ hidden_states = outputs[_HIDDEN_STATES_START_POSITION]
1473
+ hidden_states = torch.stack(hidden_states, dim=1)
1474
+ norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
1475
+ hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
1476
+ else:
1477
+ hidden_states = outputs[0]
1478
+
1479
+ hidden_states = self.projector(hidden_states)
1480
+ if attention_mask is None:
1481
+ pooled_output = hidden_states.mean(dim=1)
1482
+ else:
1483
+ padding_mask = self._get_feature_vector_attention_mask(hidden_states.shape[1], attention_mask)
1484
+ expand_padding_mask = padding_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
1485
+ hidden_states[~expand_padding_mask] = 0.0
1486
+ pooled_output = hidden_states.sum(dim=1) / padding_mask.sum(dim=1).view(-1, 1)
1487
+
1488
+ logits = self.classifier(pooled_output)
1489
+
1490
+ loss = None
1491
+ if labels is not None:
1492
+ loss_fct = CrossEntropyLoss()
1493
+ loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
1494
+
1495
+ if not return_dict:
1496
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
1497
+ return ((loss,) + output) if loss is not None else output
1498
+
1499
+ return SequenceClassifierOutput(
1500
+ loss=loss,
1501
+ logits=logits,
1502
+ hidden_states=outputs.hidden_states,
1503
+ attentions=outputs.attentions,
1504
+ )
1505
+
1506
+
1507
+ @auto_docstring
1508
+ class UniSpeechSatForAudioFrameClassification(UniSpeechSatPreTrainedModel):
1509
+ def __init__(self, config):
1510
+ super().__init__(config)
1511
+
1512
+ if hasattr(config, "add_adapter") and config.add_adapter:
1513
+ raise ValueError(
1514
+ "Audio frame classification does not support the use of UniSpeechSat adapters (config.add_adapter=True)"
1515
+ )
1516
+ self.unispeech_sat = UniSpeechSatModel(config)
1517
+ num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings
1518
+ if config.use_weighted_layer_sum:
1519
+ self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)
1520
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1521
+ self.num_labels = config.num_labels
1522
+
1523
+ self.init_weights()
1524
+
1525
+ def freeze_feature_extractor(self):
1526
+ """
1527
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
1528
+ not be updated during training.
1529
+ """
1530
+ warnings.warn(
1531
+ "The method `freeze_feature_extractor` is deprecated and will be removed in Transformers v5. "
1532
+ "Please use the equivalent `freeze_feature_encoder` method instead.",
1533
+ FutureWarning,
1534
+ )
1535
+ self.freeze_feature_encoder()
1536
+
1537
+ def freeze_feature_encoder(self):
1538
+ """
1539
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
1540
+ not be updated during training.
1541
+ """
1542
+ self.unispeech_sat.feature_extractor._freeze_parameters()
1543
+
1544
+ def freeze_base_model(self):
1545
+ """
1546
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
1547
+ be updated during training. Only the classification head will be updated.
1548
+ """
1549
+ for param in self.unispeech_sat.parameters():
1550
+ param.requires_grad = False
1551
+
1552
+ @auto_docstring
1553
+ def forward(
1554
+ self,
1555
+ input_values: Optional[torch.Tensor],
1556
+ attention_mask: Optional[torch.Tensor] = None,
1557
+ labels: Optional[torch.Tensor] = None,
1558
+ output_attentions: Optional[bool] = None,
1559
+ output_hidden_states: Optional[bool] = None,
1560
+ return_dict: Optional[bool] = None,
1561
+ ) -> Union[tuple, TokenClassifierOutput]:
1562
+ r"""
1563
+ input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
1564
+ Float values of input raw speech waveform. Values can be obtained by loading a `.flac` or `.wav` audio file
1565
+ into an array of type `list[float]`, a `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library
1566
+ (`pip install torchcodec`) or the soundfile library (`pip install soundfile`).
1567
+ To prepare the array into `input_values`, the [`AutoProcessor`] should be used for padding and conversion
1568
+ into a tensor of type `torch.FloatTensor`. See [`UniSpeechSatProcessor.__call__`] for details.
1569
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1570
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1571
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1572
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1573
+ """
1574
+
1575
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1576
+ output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
1577
+
1578
+ outputs = self.unispeech_sat(
1579
+ input_values,
1580
+ attention_mask=attention_mask,
1581
+ output_attentions=output_attentions,
1582
+ output_hidden_states=output_hidden_states,
1583
+ return_dict=return_dict,
1584
+ )
1585
+
1586
+ if self.config.use_weighted_layer_sum:
1587
+ hidden_states = outputs[_HIDDEN_STATES_START_POSITION]
1588
+ hidden_states = torch.stack(hidden_states, dim=1)
1589
+ norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
1590
+ hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
1591
+ else:
1592
+ hidden_states = outputs[0]
1593
+
1594
+ logits = self.classifier(hidden_states)
1595
+
1596
+ loss = None
1597
+ if labels is not None:
1598
+ loss_fct = CrossEntropyLoss()
1599
+ loss = loss_fct(logits.view(-1, self.num_labels), torch.argmax(labels.view(-1, self.num_labels), axis=1))
1600
+
1601
+ if not return_dict:
1602
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
1603
+ return output
1604
+
1605
+ return TokenClassifierOutput(
1606
+ loss=loss,
1607
+ logits=logits,
1608
+ hidden_states=outputs.hidden_states,
1609
+ attentions=outputs.attentions,
1610
+ )
1611
+
1612
+
1613
+ class AMSoftmaxLoss(nn.Module):
1614
+ def __init__(self, input_dim, num_labels, scale=30.0, margin=0.4):
1615
+ super().__init__()
1616
+ self.scale = scale
1617
+ self.margin = margin
1618
+ self.num_labels = num_labels
1619
+ self.weight = nn.Parameter(torch.randn(input_dim, num_labels), requires_grad=True)
1620
+ self.loss = nn.CrossEntropyLoss()
1621
+
1622
+ def forward(self, hidden_states, labels):
1623
+ labels = labels.flatten()
1624
+ weight = nn.functional.normalize(self.weight, dim=0)
1625
+ hidden_states = nn.functional.normalize(hidden_states, dim=1)
1626
+ cos_theta = torch.mm(hidden_states, weight)
1627
+ psi = cos_theta - self.margin
1628
+
1629
+ onehot = nn.functional.one_hot(labels, self.num_labels)
1630
+ logits = self.scale * torch.where(onehot.bool(), psi, cos_theta)
1631
+ loss = self.loss(logits, labels)
1632
+
1633
+ return loss
1634
+
1635
+
1636
+ class TDNNLayer(nn.Module):
1637
+ def __init__(self, config, layer_id=0):
1638
+ super().__init__()
1639
+ self.in_conv_dim = config.tdnn_dim[layer_id - 1] if layer_id > 0 else config.tdnn_dim[layer_id]
1640
+ self.out_conv_dim = config.tdnn_dim[layer_id]
1641
+ self.kernel_size = config.tdnn_kernel[layer_id]
1642
+ self.dilation = config.tdnn_dilation[layer_id]
1643
+
1644
+ self.kernel = nn.Linear(self.in_conv_dim * self.kernel_size, self.out_conv_dim)
1645
+ self.activation = nn.ReLU()
1646
+
1647
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
1648
+ if is_peft_available():
1649
+ from peft.tuners.lora import LoraLayer
1650
+
1651
+ if is_peft_available():
1652
+ if isinstance(self.kernel, LoraLayer):
1653
+ warnings.warn(
1654
+ "Detected LoRA on TDNNLayer. LoRA weights won't be applied due to optimization. "
1655
+ "You should exclude TDNNLayer from LoRA's target modules.",
1656
+ )
1657
+
1658
+ # for backward compatibility, we keep nn.Linear but call F.conv1d for speed up
1659
+ hidden_states = hidden_states.transpose(1, 2)
1660
+ weight = self.kernel.weight.view(self.out_conv_dim, self.kernel_size, self.in_conv_dim).transpose(1, 2)
1661
+ hidden_states = nn.functional.conv1d(hidden_states, weight, self.kernel.bias, dilation=self.dilation)
1662
+ hidden_states = hidden_states.transpose(1, 2)
1663
+
1664
+ hidden_states = self.activation(hidden_states)
1665
+ return hidden_states
1666
+
1667
+
1668
+ @auto_docstring(
1669
+ custom_intro="""
1670
+ UniSpeechSat Model with an XVector feature extraction head on top for tasks like Speaker Verification.
1671
+ """
1672
+ )
1673
+ class UniSpeechSatForXVector(UniSpeechSatPreTrainedModel):
1674
+ def __init__(self, config):
1675
+ super().__init__(config)
1676
+
1677
+ self.unispeech_sat = UniSpeechSatModel(config)
1678
+ num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings
1679
+ if config.use_weighted_layer_sum:
1680
+ self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)
1681
+ self.projector = nn.Linear(config.hidden_size, config.tdnn_dim[0])
1682
+
1683
+ tdnn_layers = [TDNNLayer(config, i) for i in range(len(config.tdnn_dim))]
1684
+ self.tdnn = nn.ModuleList(tdnn_layers)
1685
+
1686
+ self.feature_extractor = nn.Linear(config.tdnn_dim[-1] * 2, config.xvector_output_dim)
1687
+ self.classifier = nn.Linear(config.xvector_output_dim, config.xvector_output_dim)
1688
+
1689
+ self.objective = AMSoftmaxLoss(config.xvector_output_dim, config.num_labels)
1690
+
1691
+ self.init_weights()
1692
+
1693
+ def freeze_feature_extractor(self):
1694
+ """
1695
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
1696
+ not be updated during training.
1697
+ """
1698
+ warnings.warn(
1699
+ "The method `freeze_feature_extractor` is deprecated and will be removed in Transformers v5. "
1700
+ "Please use the equivalent `freeze_feature_encoder` method instead.",
1701
+ FutureWarning,
1702
+ )
1703
+ self.freeze_feature_encoder()
1704
+
1705
+ def freeze_feature_encoder(self):
1706
+ """
1707
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
1708
+ not be updated during training.
1709
+ """
1710
+ self.unispeech_sat.feature_extractor._freeze_parameters()
1711
+
1712
+ def freeze_base_model(self):
1713
+ """
1714
+ Calling this function will disable the gradient computation for the base model so that its parameters will not
1715
+ be updated during training. Only the classification head will be updated.
1716
+ """
1717
+ for param in self.unispeech_sat.parameters():
1718
+ param.requires_grad = False
1719
+
1720
+ def _get_tdnn_output_lengths(self, input_lengths: Union[torch.LongTensor, int]):
1721
+ """
1722
+ Computes the output length of the TDNN layers
1723
+ """
1724
+
1725
+ def _conv_out_length(input_length, kernel_size, stride):
1726
+ # 1D convolutional layer output length formula taken
1727
+ # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
1728
+ return (input_length - kernel_size) // stride + 1
1729
+
1730
+ for kernel_size in self.config.tdnn_kernel:
1731
+ input_lengths = _conv_out_length(input_lengths, kernel_size, 1)
1732
+
1733
+ return input_lengths
1734
+
1735
+ @auto_docstring
1736
+ def forward(
1737
+ self,
1738
+ input_values: Optional[torch.Tensor],
1739
+ attention_mask: Optional[torch.Tensor] = None,
1740
+ output_attentions: Optional[bool] = None,
1741
+ output_hidden_states: Optional[bool] = None,
1742
+ return_dict: Optional[bool] = None,
1743
+ labels: Optional[torch.Tensor] = None,
1744
+ ) -> Union[tuple, XVectorOutput]:
1745
+ r"""
1746
+ input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
1747
+ Float values of input raw speech waveform. Values can be obtained by loading a `.flac` or `.wav` audio file
1748
+ into an array of type `list[float]`, a `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library
1749
+ (`pip install torchcodec`) or the soundfile library (`pip install soundfile`).
1750
+ To prepare the array into `input_values`, the [`AutoProcessor`] should be used for padding and conversion
1751
+ into a tensor of type `torch.FloatTensor`. See [`UniSpeechSatProcessor.__call__`] for details.
1752
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1753
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1754
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1755
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1756
+ """
1757
+
1758
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1759
+ output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
1760
+
1761
+ outputs = self.unispeech_sat(
1762
+ input_values,
1763
+ attention_mask=attention_mask,
1764
+ output_attentions=output_attentions,
1765
+ output_hidden_states=output_hidden_states,
1766
+ return_dict=return_dict,
1767
+ )
1768
+
1769
+ if self.config.use_weighted_layer_sum:
1770
+ hidden_states = outputs[_HIDDEN_STATES_START_POSITION]
1771
+ hidden_states = torch.stack(hidden_states, dim=1)
1772
+ norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
1773
+ hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
1774
+ else:
1775
+ hidden_states = outputs[0]
1776
+
1777
+ hidden_states = self.projector(hidden_states)
1778
+
1779
+ for tdnn_layer in self.tdnn:
1780
+ hidden_states = tdnn_layer(hidden_states)
1781
+
1782
+ # Statistic Pooling
1783
+ if attention_mask is None:
1784
+ mean_features = hidden_states.mean(dim=1)
1785
+ std_features = hidden_states.std(dim=1)
1786
+ else:
1787
+ feat_extract_output_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(dim=1))
1788
+ tdnn_output_lengths = self._get_tdnn_output_lengths(feat_extract_output_lengths)
1789
+ mean_features = []
1790
+ std_features = []
1791
+ for i, length in enumerate(tdnn_output_lengths):
1792
+ mean_features.append(hidden_states[i, :length].mean(dim=0))
1793
+ std_features.append(hidden_states[i, :length].std(dim=0))
1794
+ mean_features = torch.stack(mean_features)
1795
+ std_features = torch.stack(std_features)
1796
+ statistic_pooling = torch.cat([mean_features, std_features], dim=-1)
1797
+
1798
+ output_embeddings = self.feature_extractor(statistic_pooling)
1799
+ logits = self.classifier(output_embeddings)
1800
+
1801
+ loss = None
1802
+ if labels is not None:
1803
+ loss = self.objective(logits, labels)
1804
+
1805
+ if not return_dict:
1806
+ output = (logits, output_embeddings) + outputs[_HIDDEN_STATES_START_POSITION:]
1807
+ return ((loss,) + output) if loss is not None else output
1808
+
1809
+ return XVectorOutput(
1810
+ loss=loss,
1811
+ logits=logits,
1812
+ embeddings=output_embeddings,
1813
+ hidden_states=outputs.hidden_states,
1814
+ attentions=outputs.attentions,
1815
+ )
1816
+
1817
+
1818
+ __all__ = [
1819
+ "UniSpeechSatForAudioFrameClassification",
1820
+ "UniSpeechSatForCTC",
1821
+ "UniSpeechSatForPreTraining",
1822
+ "UniSpeechSatForSequenceClassification",
1823
+ "UniSpeechSatForXVector",
1824
+ "UniSpeechSatModel",
1825
+ "UniSpeechSatPreTrainedModel",
1826
+ ]
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/unispeech_sat/modular_unispeech_sat.py ADDED
@@ -0,0 +1,457 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The Fairseq Authors and the HuggingFace Inc. team. 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
+ """PyTorch UniSpeechSat model."""
16
+
17
+ import math
18
+ import warnings
19
+ from dataclasses import dataclass
20
+ from typing import Optional, Union
21
+
22
+ import torch
23
+ import torch.nn as nn
24
+
25
+ from ...modeling_outputs import ModelOutput, Wav2Vec2BaseModelOutput
26
+ from ...modeling_utils import PreTrainedModel
27
+ from ...utils import auto_docstring, logging
28
+ from ..wav2vec2.modeling_wav2vec2 import (
29
+ Wav2Vec2Encoder,
30
+ Wav2Vec2EncoderStableLayerNorm,
31
+ Wav2Vec2FeatureEncoder,
32
+ Wav2Vec2FeatureProjection,
33
+ Wav2Vec2ForAudioFrameClassification,
34
+ Wav2Vec2ForCTC,
35
+ Wav2Vec2ForSequenceClassification,
36
+ Wav2Vec2ForXVector,
37
+ Wav2Vec2GumbelVectorQuantizer,
38
+ Wav2Vec2Model,
39
+ Wav2Vec2PositionalConvEmbedding,
40
+ )
41
+ from .configuration_unispeech_sat import UniSpeechSatConfig
42
+
43
+
44
+ logger = logging.get_logger(__name__)
45
+
46
+
47
+ _HIDDEN_STATES_START_POSITION = 2
48
+
49
+
50
+ @dataclass
51
+ @auto_docstring(
52
+ custom_intro="""
53
+ Output type of [`UniSpeechSatForPreTrainingOutput`], with potential hidden states and attentions.
54
+ """
55
+ )
56
+ class UniSpeechSatForPreTrainingOutput(ModelOutput):
57
+ r"""
58
+ loss (*optional*, returned when model is in train mode, `torch.FloatTensor` of shape `(1,)`):
59
+ Total loss as the sum of the contrastive loss (L_m) and the diversity loss (L_d) as stated in the [official
60
+ paper](https://arxiv.org/pdf/2006.11477.pdf) . (classification) loss.
61
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.proj_codevector_dim)`, *optional*):
62
+ Prediction scores of the contrastive loss model, i.e. the output of the model before the final softmax.
63
+ projected_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.proj_codevector_dim)`):
64
+ Hidden-states of the model projected to *config.proj_codevector_dim* that can be used to predict the masked
65
+ projected quantized states.
66
+ projected_quantized_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.proj_codevector_dim)`):
67
+ Quantized extracted feature vectors projected to *config.proj_codevector_dim* representing the positive
68
+ target vectors for contrastive loss.
69
+ codevector_perplexity (`torch.FloatTensor` of shape `(1,)`):
70
+ The perplexity of the codevector distribution, used to measure the diversity of the codebook.
71
+ """
72
+
73
+ loss: Optional[torch.FloatTensor] = None
74
+ logits: Optional[torch.FloatTensor] = None
75
+ projected_states: Optional[torch.FloatTensor] = None
76
+ projected_quantized_states: Optional[torch.FloatTensor] = None
77
+ codevector_perplexity: Optional[torch.FloatTensor] = None
78
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
79
+ attentions: Optional[tuple[torch.FloatTensor]] = None
80
+
81
+
82
+ class UniSpeechSatPositionalConvEmbedding(Wav2Vec2PositionalConvEmbedding):
83
+ pass
84
+
85
+
86
+ class UniSpeechSatFeatureEncoder(Wav2Vec2FeatureEncoder):
87
+ pass
88
+
89
+
90
+ class UniSpeechSatFeatureProjection(Wav2Vec2FeatureProjection):
91
+ pass
92
+
93
+
94
+ class UniSpeechSatEncoder(Wav2Vec2Encoder):
95
+ pass
96
+
97
+
98
+ class UniSpeechSatEncoderStableLayerNorm(Wav2Vec2EncoderStableLayerNorm):
99
+ pass
100
+
101
+
102
+ class UniSpeechSatGumbelVectorQuantizer(Wav2Vec2GumbelVectorQuantizer):
103
+ def __init__(self, config):
104
+ super().__init__()
105
+ self.weight_proj = nn.Linear(config.hidden_size, self.num_groups * self.num_vars)
106
+
107
+ @staticmethod
108
+ def _compute_perplexity(probs, mask=None):
109
+ marginal_probs = probs.mean(dim=0)
110
+ perplexity = torch.exp(-torch.sum(marginal_probs * torch.log(marginal_probs + 1e-7), dim=-1)).sum()
111
+ return perplexity
112
+
113
+ def forward(self, hidden_states):
114
+ batch_size, sequence_length, hidden_size = hidden_states.shape
115
+
116
+ # project to codevector dim
117
+ hidden_states = self.weight_proj(hidden_states)
118
+ hidden_states = hidden_states.view(batch_size * sequence_length * self.num_groups, -1)
119
+
120
+ if self.training:
121
+ # sample code vector probs via gumbel in differentiateable way
122
+ codevector_probs = nn.functional.gumbel_softmax(
123
+ hidden_states.float(), tau=self.temperature, hard=True
124
+ ).type_as(hidden_states)
125
+
126
+ # compute perplexity
127
+ codevector_soft_dist = torch.softmax(
128
+ hidden_states.view(batch_size * sequence_length, self.num_groups, -1).float(), dim=-1
129
+ )
130
+ perplexity = self._compute_perplexity(codevector_soft_dist)
131
+ else:
132
+ # take argmax in non-differentiable way
133
+ # comptute hard codevector distribution (one hot)
134
+ codevector_idx = hidden_states.argmax(dim=-1)
135
+ codevector_probs = hidden_states.new_zeros(*hidden_states.shape).scatter_(
136
+ -1, codevector_idx.view(-1, 1), 1.0
137
+ )
138
+ codevector_probs = codevector_probs.view(batch_size * sequence_length, self.num_groups, -1)
139
+
140
+ perplexity = self._compute_perplexity(codevector_probs)
141
+
142
+ codevector_probs = codevector_probs.view(batch_size * sequence_length, -1)
143
+ # use probs to retrieve codevectors
144
+ codevectors_per_group = codevector_probs.unsqueeze(-1) * self.codevectors
145
+ codevectors = codevectors_per_group.view(batch_size * sequence_length, self.num_groups, self.num_vars, -1)
146
+ codevectors = codevectors.sum(-2).view(batch_size, sequence_length, -1)
147
+
148
+ return codevectors, perplexity
149
+
150
+
151
+ @auto_docstring
152
+ class UniSpeechSatPreTrainedModel(PreTrainedModel):
153
+ config: UniSpeechSatConfig
154
+ base_model_prefix = "unispeech_sat"
155
+ main_input_name = "input_values"
156
+ supports_gradient_checkpointing = True
157
+ _supports_flash_attn = True
158
+ _supports_sdpa = True
159
+ _supports_flex_attn = True
160
+
161
+ def _init_weights(self, module):
162
+ """Initialize the weights"""
163
+ # gumbel softmax requires special init
164
+ if isinstance(module, UniSpeechSatGumbelVectorQuantizer):
165
+ module.weight_proj.weight.data.normal_(mean=0.0, std=1)
166
+ module.weight_proj.bias.data.zero_()
167
+ nn.init.uniform_(module.codevectors)
168
+ elif isinstance(module, UniSpeechSatPositionalConvEmbedding):
169
+ nn.init.normal_(
170
+ module.conv.weight,
171
+ mean=0,
172
+ std=2 * math.sqrt(1 / (module.conv.kernel_size[0] * module.conv.in_channels)),
173
+ )
174
+ nn.init.constant_(module.conv.bias, 0)
175
+ elif isinstance(module, UniSpeechSatFeatureProjection):
176
+ k = math.sqrt(1 / module.projection.in_features)
177
+ nn.init.uniform_(module.projection.weight, a=-k, b=k)
178
+ nn.init.uniform_(module.projection.bias, a=-k, b=k)
179
+ elif isinstance(module, nn.Linear):
180
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
181
+
182
+ if module.bias is not None:
183
+ module.bias.data.zero_()
184
+ elif isinstance(module, (nn.LayerNorm, nn.GroupNorm)):
185
+ module.bias.data.zero_()
186
+ module.weight.data.fill_(1.0)
187
+ elif isinstance(module, nn.Conv1d):
188
+ nn.init.kaiming_normal_(module.weight)
189
+
190
+ if module.bias is not None:
191
+ k = math.sqrt(module.groups / (module.in_channels * module.kernel_size[0]))
192
+ nn.init.uniform_(module.bias, a=-k, b=k)
193
+
194
+ def _get_feat_extract_output_lengths(self, input_lengths: Union[torch.LongTensor, int]):
195
+ """
196
+ Computes the output length of the convolutional layers
197
+ """
198
+
199
+ def _conv_out_length(input_length, kernel_size, stride):
200
+ # 1D convolutional layer output length formula taken
201
+ # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html
202
+ return torch.div(input_length - kernel_size, stride, rounding_mode="floor") + 1
203
+
204
+ for kernel_size, stride in zip(self.config.conv_kernel, self.config.conv_stride):
205
+ input_lengths = _conv_out_length(input_lengths, kernel_size, stride)
206
+
207
+ return input_lengths
208
+
209
+ def _get_feature_vector_attention_mask(self, feature_vector_length: int, attention_mask: torch.LongTensor):
210
+ # Effectively attention_mask.sum(-1), but not inplace to be able to run
211
+ # on inference mode.
212
+ non_padded_lengths = attention_mask.cumsum(dim=-1)[:, -1]
213
+ output_lengths = self._get_feat_extract_output_lengths(non_padded_lengths).to(torch.long)
214
+ batch_size = attention_mask.shape[0]
215
+
216
+ attention_mask = torch.zeros(
217
+ (batch_size, feature_vector_length), dtype=attention_mask.dtype, device=attention_mask.device
218
+ )
219
+ # these two operations makes sure that all values before the output lengths idxs are attended to
220
+ attention_mask[(torch.arange(attention_mask.shape[0], device=attention_mask.device), output_lengths - 1)] = 1
221
+ attention_mask = attention_mask.flip([-1]).cumsum(-1).flip([-1]).bool()
222
+ return attention_mask
223
+
224
+
225
+ UniSpeechSatBaseModelOutput = Wav2Vec2BaseModelOutput
226
+
227
+
228
+ class UniSpeechSatModel(UniSpeechSatPreTrainedModel, Wav2Vec2Model):
229
+ def __init__(self, config: UniSpeechSatConfig):
230
+ UniSpeechSatPreTrainedModel.__init__(config)
231
+ self.config = config
232
+ self.feature_extractor = UniSpeechSatFeatureEncoder(config)
233
+ self.feature_projection = UniSpeechSatFeatureProjection(config)
234
+
235
+ self.masked_spec_embed = nn.Parameter(torch.Tensor(config.hidden_size).uniform_())
236
+
237
+ if config.do_stable_layer_norm:
238
+ self.encoder = UniSpeechSatEncoderStableLayerNorm(config)
239
+ else:
240
+ self.encoder = UniSpeechSatEncoder(config)
241
+
242
+ # Initialize weights and apply final processing
243
+ self.post_init()
244
+
245
+ def freeze_feature_extractor(self):
246
+ raise AttributeError("Not needed for UniSpeechSat")
247
+
248
+ def freeze_feature_encoder(self):
249
+ raise AttributeError("Not needed for UniSpeechSat")
250
+
251
+ def forward(
252
+ self,
253
+ input_values: Optional[torch.Tensor],
254
+ attention_mask: Optional[torch.Tensor] = None,
255
+ mask_time_indices: Optional[torch.FloatTensor] = None,
256
+ output_attentions: Optional[bool] = None,
257
+ output_hidden_states: Optional[bool] = None,
258
+ return_dict: Optional[bool] = None,
259
+ ) -> Union[tuple, UniSpeechSatBaseModelOutput]:
260
+ r"""
261
+ mask_time_indices (`torch.BoolTensor` of shape `(batch_size, sequence_length)`, *optional*):
262
+ Indices to mask extracted features for contrastive loss. When in training mode, model learns to predict
263
+ masked extracted features in *config.proj_codevector_dim* space.
264
+ """
265
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
266
+ output_hidden_states = (
267
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
268
+ )
269
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
270
+
271
+ extract_features = self.feature_extractor(input_values)
272
+ extract_features = extract_features.transpose(1, 2)
273
+
274
+ if attention_mask is not None:
275
+ # compute reduced attention_mask corresponding to feature vectors
276
+ attention_mask = self._get_feature_vector_attention_mask(extract_features.shape[1], attention_mask)
277
+
278
+ hidden_states, extract_features = self.feature_projection(extract_features)
279
+ hidden_states = self._mask_hidden_states(
280
+ hidden_states, mask_time_indices=mask_time_indices, attention_mask=attention_mask
281
+ )
282
+
283
+ encoder_outputs = self.encoder(
284
+ hidden_states,
285
+ attention_mask=attention_mask,
286
+ output_attentions=output_attentions,
287
+ output_hidden_states=output_hidden_states,
288
+ return_dict=return_dict,
289
+ )
290
+
291
+ hidden_states = encoder_outputs[0]
292
+
293
+ if not return_dict:
294
+ return (hidden_states, extract_features) + encoder_outputs[1:]
295
+
296
+ return UniSpeechSatBaseModelOutput(
297
+ last_hidden_state=hidden_states,
298
+ extract_features=extract_features,
299
+ hidden_states=encoder_outputs.hidden_states,
300
+ attentions=encoder_outputs.attentions,
301
+ )
302
+
303
+
304
+ @auto_docstring(
305
+ custom_intro="""
306
+ UniSpeechSat Model with a vector-quantization module and ctc loss for pre-training.
307
+ """
308
+ )
309
+ class UniSpeechSatForPreTraining(UniSpeechSatPreTrainedModel):
310
+ def __init__(self, config: UniSpeechSatConfig):
311
+ super().__init__(config)
312
+ self.unispeech_sat = UniSpeechSatModel(config)
313
+ self.dropout_features = nn.Dropout(config.feat_quantizer_dropout)
314
+
315
+ self.quantizer = UniSpeechSatGumbelVectorQuantizer(config)
316
+ self.project_q = nn.Linear(config.codevector_dim, config.proj_codevector_dim)
317
+ self.project_hid = nn.Linear(config.hidden_size, config.proj_codevector_dim)
318
+
319
+ self.dropout = nn.Dropout(config.final_dropout)
320
+
321
+ self.speaker_proj = nn.Linear(config.hidden_size, config.codevector_dim)
322
+ self.label_embeddings_concat = nn.Parameter(torch.FloatTensor(config.num_clusters, config.codevector_dim))
323
+ self.label_embeddings_concat.data.zero_()
324
+
325
+ self.layer_norm_for_extract = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
326
+ if self.config.do_stable_layer_norm:
327
+ self.layer_norm_for_extract.requires_grad = False
328
+
329
+ # Initialize weights and apply final processing
330
+ self.post_init()
331
+
332
+ def set_gumbel_temperature(self, temperature: int):
333
+ """
334
+ Set the Gumbel softmax temperature to a given value. Only necessary for training
335
+ """
336
+ self.quantizer.temperature = temperature
337
+
338
+ def freeze_feature_extractor(self):
339
+ """
340
+ Calling this function will disable the gradient computation for the feature encoder so that its parameters will
341
+ not be updated during training.
342
+ """
343
+ warnings.warn(
344
+ "The method `freeze_feature_extractor` is deprecated and will be removed in Transformers v5. "
345
+ "Please use the equivalent `freeze_feature_encoder` method instead.",
346
+ FutureWarning,
347
+ )
348
+ self.freeze_feature_encoder()
349
+
350
+ def freeze_feature_encoder(self):
351
+ """
352
+ Calling this function will disable the gradient computation for the feature encoder so that its parameter will
353
+ not be updated during training.
354
+ """
355
+ self.unispeech_sat.feature_extractor._freeze_parameters()
356
+
357
+ @staticmethod
358
+ def compute_contrastive_logits(
359
+ target_features: torch.FloatTensor,
360
+ negative_features: torch.FloatTensor,
361
+ predicted_features: torch.FloatTensor,
362
+ temperature: int = 1,
363
+ ):
364
+ """
365
+ Compute logits for contrastive loss based using cosine similarity as the distance measure between
366
+ `[positive_feature, negative_features]` and `[predicted_features]`. Additionally, temperature can be applied.
367
+ """
368
+ target_features = torch.cat([target_features, negative_features], dim=0)
369
+
370
+ logits = torch.cosine_similarity(predicted_features.float(), target_features.float(), dim=-1)
371
+ logits = logits.type_as(target_features)
372
+
373
+ # apply temperature
374
+ logits = logits / temperature
375
+ return logits
376
+
377
+ @auto_docstring
378
+ def forward(
379
+ self,
380
+ input_values: Optional[torch.Tensor],
381
+ attention_mask: Optional[torch.Tensor] = None,
382
+ output_attentions: Optional[bool] = None,
383
+ output_hidden_states: Optional[bool] = None,
384
+ return_dict: Optional[bool] = None,
385
+ ) -> Union[tuple, UniSpeechSatForPreTrainingOutput]:
386
+ r"""
387
+ Example:
388
+
389
+ ```python
390
+ >>> import torch
391
+ >>> from transformers import AutoFeatureExtractor, UniSpeechSatForPreTraining
392
+ >>> from transformers.models.unispeech_sat.modeling_unispeech_sat import _compute_mask_indices
393
+
394
+ >>> feature_extractor = AutoFeatureExtractor.from_pretrained("microsoft/unispeech-sat-base")
395
+ >>> model = UniSpeechSatForPreTraining.from_pretrained("microsoft/unispeech-sat-base")
396
+ >>> # TODO: Add full pretraining example
397
+ ```"""
398
+
399
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
400
+
401
+ outputs = self.unispeech_sat(
402
+ input_values,
403
+ attention_mask=attention_mask,
404
+ output_attentions=output_attentions,
405
+ output_hidden_states=output_hidden_states,
406
+ return_dict=return_dict,
407
+ )
408
+ transformer_features = outputs[0]
409
+
410
+ # quantize all (unmasked) extracted features and project to final vq dim
411
+ extract_features = self.dropout_features(outputs[1])
412
+
413
+ # TODO(PVP) - add pretraining logic and add to tests
414
+ logits = extract_features
415
+ loss = quantized_features = codevector_perplexity = None
416
+
417
+ if not return_dict:
418
+ if loss is not None:
419
+ return (loss, logits, transformer_features, quantized_features, codevector_perplexity) + outputs[2:]
420
+ return (logits, transformer_features, quantized_features, codevector_perplexity) + outputs[2:]
421
+
422
+ return UniSpeechSatForPreTrainingOutput(
423
+ loss=loss,
424
+ logits=logits,
425
+ projected_states=transformer_features,
426
+ projected_quantized_states=quantized_features,
427
+ codevector_perplexity=codevector_perplexity,
428
+ hidden_states=outputs.hidden_states,
429
+ attentions=outputs.attentions,
430
+ )
431
+
432
+
433
+ class UniSpeechSatForCTC(Wav2Vec2ForCTC):
434
+ pass
435
+
436
+
437
+ class UniSpeechSatForSequenceClassification(Wav2Vec2ForSequenceClassification):
438
+ pass
439
+
440
+
441
+ class UniSpeechSatForAudioFrameClassification(Wav2Vec2ForAudioFrameClassification):
442
+ pass
443
+
444
+
445
+ class UniSpeechSatForXVector(Wav2Vec2ForXVector):
446
+ pass
447
+
448
+
449
+ __all__ = [
450
+ "UniSpeechSatForAudioFrameClassification",
451
+ "UniSpeechSatForCTC",
452
+ "UniSpeechSatForPreTraining",
453
+ "UniSpeechSatForSequenceClassification",
454
+ "UniSpeechSatForXVector",
455
+ "UniSpeechSatModel",
456
+ "UniSpeechSatPreTrainedModel",
457
+ ]
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/univnet/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. 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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_univnet import *
22
+ from .feature_extraction_univnet import *
23
+ from .modeling_univnet import *
24
+ else:
25
+ import sys
26
+
27
+ _file = globals()["__file__"]
28
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/univnet/configuration_univnet.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team. 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
+ """UnivNetModel model configuration"""
15
+
16
+ from ...configuration_utils import PretrainedConfig
17
+ from ...utils import logging
18
+
19
+
20
+ logger = logging.get_logger(__name__)
21
+
22
+
23
+ class UnivNetConfig(PretrainedConfig):
24
+ r"""
25
+ This is the configuration class to store the configuration of a [`UnivNetModel`]. It is used to instantiate a
26
+ UnivNet vocoder model according to the specified arguments, defining the model architecture. Instantiating a
27
+ configuration with the defaults will yield a similar configuration to that of the UnivNet
28
+ [dg845/univnet-dev](https://huggingface.co/dg845/univnet-dev) architecture, which corresponds to the 'c32'
29
+ architecture in [maum-ai/univnet](https://github.com/maum-ai/univnet/blob/master/config/default_c32.yaml).
30
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+ Args:
35
+ model_in_channels (`int`, *optional*, defaults to 64):
36
+ The number of input channels for the UnivNet residual network. This should correspond to
37
+ `noise_sequence.shape[1]` and the value used in the [`UnivNetFeatureExtractor`] class.
38
+ model_hidden_channels (`int`, *optional*, defaults to 32):
39
+ The number of hidden channels of each residual block in the UnivNet residual network.
40
+ num_mel_bins (`int`, *optional*, defaults to 100):
41
+ The number of frequency bins in the conditioning log-mel spectrogram. This should correspond to the value
42
+ used in the [`UnivNetFeatureExtractor`] class.
43
+ resblock_kernel_sizes (`tuple[int]` or `list[int]`, *optional*, defaults to `[3, 3, 3]`):
44
+ A tuple of integers defining the kernel sizes of the 1D convolutional layers in the UnivNet residual
45
+ network. The length of `resblock_kernel_sizes` defines the number of resnet blocks and should match that of
46
+ `resblock_stride_sizes` and `resblock_dilation_sizes`.
47
+ resblock_stride_sizes (`tuple[int]` or `list[int]`, *optional*, defaults to `[8, 8, 4]`):
48
+ A tuple of integers defining the stride sizes of the 1D convolutional layers in the UnivNet residual
49
+ network. The length of `resblock_stride_sizes` should match that of `resblock_kernel_sizes` and
50
+ `resblock_dilation_sizes`.
51
+ resblock_dilation_sizes (`tuple[tuple[int]]` or `list[list[int]]`, *optional*, defaults to `[[1, 3, 9, 27], [1, 3, 9, 27], [1, 3, 9, 27]]`):
52
+ A nested tuple of integers defining the dilation rates of the dilated 1D convolutional layers in the
53
+ UnivNet residual network. The length of `resblock_dilation_sizes` should match that of
54
+ `resblock_kernel_sizes` and `resblock_stride_sizes`. The length of each nested list in
55
+ `resblock_dilation_sizes` defines the number of convolutional layers per resnet block.
56
+ kernel_predictor_num_blocks (`int`, *optional*, defaults to 3):
57
+ The number of residual blocks in the kernel predictor network, which calculates the kernel and bias for
58
+ each location variable convolution layer in the UnivNet residual network.
59
+ kernel_predictor_hidden_channels (`int`, *optional*, defaults to 64):
60
+ The number of hidden channels for each residual block in the kernel predictor network.
61
+ kernel_predictor_conv_size (`int`, *optional*, defaults to 3):
62
+ The kernel size of each 1D convolutional layer in the kernel predictor network.
63
+ kernel_predictor_dropout (`float`, *optional*, defaults to 0.0):
64
+ The dropout probability for each residual block in the kernel predictor network.
65
+ initializer_range (`float`, *optional*, defaults to 0.01):
66
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
67
+ leaky_relu_slope (`float`, *optional*, defaults to 0.2):
68
+ The angle of the negative slope used by the leaky ReLU activation.
69
+
70
+ Example:
71
+
72
+ ```python
73
+ >>> from transformers import UnivNetModel, UnivNetConfig
74
+
75
+ >>> # Initializing a Tortoise TTS style configuration
76
+ >>> configuration = UnivNetConfig()
77
+
78
+ >>> # Initializing a model (with random weights) from the Tortoise TTS style configuration
79
+ >>> model = UnivNetModel(configuration)
80
+
81
+ >>> # Accessing the model configuration
82
+ >>> configuration = model.config
83
+ ```
84
+ """
85
+
86
+ model_type = "univnet"
87
+
88
+ def __init__(
89
+ self,
90
+ model_in_channels=64,
91
+ model_hidden_channels=32,
92
+ num_mel_bins=100,
93
+ resblock_kernel_sizes=[3, 3, 3],
94
+ resblock_stride_sizes=[8, 8, 4],
95
+ resblock_dilation_sizes=[[1, 3, 9, 27], [1, 3, 9, 27], [1, 3, 9, 27]],
96
+ kernel_predictor_num_blocks=3,
97
+ kernel_predictor_hidden_channels=64,
98
+ kernel_predictor_conv_size=3,
99
+ kernel_predictor_dropout=0.0,
100
+ initializer_range=0.01,
101
+ leaky_relu_slope=0.2,
102
+ **kwargs,
103
+ ):
104
+ if not (len(resblock_kernel_sizes) == len(resblock_stride_sizes) == len(resblock_dilation_sizes)):
105
+ raise ValueError(
106
+ "`resblock_kernel_sizes`, `resblock_stride_sizes`, and `resblock_dilation_sizes` must all have the"
107
+ " same length (which will be the number of resnet blocks in the model)."
108
+ )
109
+
110
+ self.model_in_channels = model_in_channels
111
+ self.model_hidden_channels = model_hidden_channels
112
+ self.num_mel_bins = num_mel_bins
113
+ self.resblock_kernel_sizes = resblock_kernel_sizes
114
+ self.resblock_stride_sizes = resblock_stride_sizes
115
+ self.resblock_dilation_sizes = resblock_dilation_sizes
116
+ self.kernel_predictor_num_blocks = kernel_predictor_num_blocks
117
+ self.kernel_predictor_hidden_channels = kernel_predictor_hidden_channels
118
+ self.kernel_predictor_conv_size = kernel_predictor_conv_size
119
+ self.kernel_predictor_dropout = kernel_predictor_dropout
120
+ self.initializer_range = initializer_range
121
+ self.leaky_relu_slope = leaky_relu_slope
122
+ super().__init__(**kwargs)
123
+
124
+
125
+ __all__ = ["UnivNetConfig"]
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/univnet/convert_univnet.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team. 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 argparse
16
+
17
+ import torch
18
+
19
+ from transformers import UnivNetConfig, UnivNetModel, logging
20
+
21
+
22
+ logging.set_verbosity_info()
23
+ logger = logging.get_logger("transformers.models.univnet")
24
+
25
+
26
+ def get_kernel_predictor_key_mapping(config: UnivNetConfig, old_prefix: str = "", new_prefix: str = ""):
27
+ mapping = {}
28
+ # Initial conv layer
29
+ mapping[f"{old_prefix}.input_conv.0.weight_g"] = f"{new_prefix}.input_conv.weight_g"
30
+ mapping[f"{old_prefix}.input_conv.0.weight_v"] = f"{new_prefix}.input_conv.weight_v"
31
+ mapping[f"{old_prefix}.input_conv.0.bias"] = f"{new_prefix}.input_conv.bias"
32
+
33
+ # Kernel predictor resnet blocks
34
+ for i in range(config.kernel_predictor_num_blocks):
35
+ mapping[f"{old_prefix}.residual_convs.{i}.1.weight_g"] = f"{new_prefix}.resblocks.{i}.conv1.weight_g"
36
+ mapping[f"{old_prefix}.residual_convs.{i}.1.weight_v"] = f"{new_prefix}.resblocks.{i}.conv1.weight_v"
37
+ mapping[f"{old_prefix}.residual_convs.{i}.1.bias"] = f"{new_prefix}.resblocks.{i}.conv1.bias"
38
+
39
+ mapping[f"{old_prefix}.residual_convs.{i}.3.weight_g"] = f"{new_prefix}.resblocks.{i}.conv2.weight_g"
40
+ mapping[f"{old_prefix}.residual_convs.{i}.3.weight_v"] = f"{new_prefix}.resblocks.{i}.conv2.weight_v"
41
+ mapping[f"{old_prefix}.residual_convs.{i}.3.bias"] = f"{new_prefix}.resblocks.{i}.conv2.bias"
42
+
43
+ # Kernel output conv
44
+ mapping[f"{old_prefix}.kernel_conv.weight_g"] = f"{new_prefix}.kernel_conv.weight_g"
45
+ mapping[f"{old_prefix}.kernel_conv.weight_v"] = f"{new_prefix}.kernel_conv.weight_v"
46
+ mapping[f"{old_prefix}.kernel_conv.bias"] = f"{new_prefix}.kernel_conv.bias"
47
+
48
+ # Bias output conv
49
+ mapping[f"{old_prefix}.bias_conv.weight_g"] = f"{new_prefix}.bias_conv.weight_g"
50
+ mapping[f"{old_prefix}.bias_conv.weight_v"] = f"{new_prefix}.bias_conv.weight_v"
51
+ mapping[f"{old_prefix}.bias_conv.bias"] = f"{new_prefix}.bias_conv.bias"
52
+
53
+ return mapping
54
+
55
+
56
+ def get_key_mapping(config: UnivNetConfig):
57
+ mapping = {}
58
+
59
+ # NOTE: initial conv layer keys are the same
60
+
61
+ # LVC Residual blocks
62
+ for i in range(len(config.resblock_stride_sizes)):
63
+ # LVCBlock initial convt layer
64
+ mapping[f"res_stack.{i}.convt_pre.1.weight_g"] = f"resblocks.{i}.convt_pre.weight_g"
65
+ mapping[f"res_stack.{i}.convt_pre.1.weight_v"] = f"resblocks.{i}.convt_pre.weight_v"
66
+ mapping[f"res_stack.{i}.convt_pre.1.bias"] = f"resblocks.{i}.convt_pre.bias"
67
+
68
+ # Kernel predictor
69
+ kernel_predictor_mapping = get_kernel_predictor_key_mapping(
70
+ config, old_prefix=f"res_stack.{i}.kernel_predictor", new_prefix=f"resblocks.{i}.kernel_predictor"
71
+ )
72
+ mapping.update(kernel_predictor_mapping)
73
+
74
+ # LVC Residual blocks
75
+ for j in range(len(config.resblock_dilation_sizes[i])):
76
+ mapping[f"res_stack.{i}.conv_blocks.{j}.1.weight_g"] = f"resblocks.{i}.resblocks.{j}.conv.weight_g"
77
+ mapping[f"res_stack.{i}.conv_blocks.{j}.1.weight_v"] = f"resblocks.{i}.resblocks.{j}.conv.weight_v"
78
+ mapping[f"res_stack.{i}.conv_blocks.{j}.1.bias"] = f"resblocks.{i}.resblocks.{j}.conv.bias"
79
+
80
+ # Output conv layer
81
+ mapping["conv_post.1.weight_g"] = "conv_post.weight_g"
82
+ mapping["conv_post.1.weight_v"] = "conv_post.weight_v"
83
+ mapping["conv_post.1.bias"] = "conv_post.bias"
84
+
85
+ return mapping
86
+
87
+
88
+ def rename_state_dict(state_dict, keys_to_modify, keys_to_remove):
89
+ model_state_dict = {}
90
+ for key, value in state_dict.items():
91
+ if key in keys_to_remove:
92
+ continue
93
+
94
+ if key in keys_to_modify:
95
+ new_key = keys_to_modify[key]
96
+ model_state_dict[new_key] = value
97
+ else:
98
+ model_state_dict[key] = value
99
+ return model_state_dict
100
+
101
+
102
+ def convert_univnet_checkpoint(
103
+ checkpoint_path,
104
+ pytorch_dump_folder_path,
105
+ config_path=None,
106
+ repo_id=None,
107
+ safe_serialization=False,
108
+ ):
109
+ model_state_dict_base = torch.load(checkpoint_path, map_location="cpu", weights_only=True)
110
+ # Get the generator's state dict
111
+ state_dict = model_state_dict_base["model_g"]
112
+
113
+ if config_path is not None:
114
+ config = UnivNetConfig.from_pretrained(config_path)
115
+ else:
116
+ config = UnivNetConfig()
117
+
118
+ keys_to_modify = get_key_mapping(config)
119
+ keys_to_remove = set()
120
+ hf_state_dict = rename_state_dict(state_dict, keys_to_modify, keys_to_remove)
121
+
122
+ model = UnivNetModel(config)
123
+ # Apply weight norm since the original checkpoint has weight norm applied
124
+ model.apply_weight_norm()
125
+ model.load_state_dict(hf_state_dict)
126
+ # Remove weight norm in preparation for inference
127
+ model.remove_weight_norm()
128
+
129
+ model.save_pretrained(pytorch_dump_folder_path, safe_serialization=safe_serialization)
130
+
131
+ if repo_id:
132
+ print("Pushing to the hub...")
133
+ model.push_to_hub(repo_id)
134
+
135
+
136
+ def main():
137
+ parser = argparse.ArgumentParser()
138
+ parser.add_argument("--checkpoint_path", required=True, default=None, type=str, help="Path to original checkpoint")
139
+ parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert")
140
+ parser.add_argument(
141
+ "--pytorch_dump_folder_path", required=True, default=None, type=str, help="Path to the output PyTorch model."
142
+ )
143
+ parser.add_argument(
144
+ "--push_to_hub", default=None, type=str, help="Where to upload the converted model on the 🤗 hub."
145
+ )
146
+ parser.add_argument(
147
+ "--safe_serialization", action="store_true", help="Whether to save the model using `safetensors`."
148
+ )
149
+
150
+ args = parser.parse_args()
151
+
152
+ convert_univnet_checkpoint(
153
+ args.checkpoint_path,
154
+ args.pytorch_dump_folder_path,
155
+ args.config_path,
156
+ args.push_to_hub,
157
+ args.safe_serialization,
158
+ )
159
+
160
+
161
+ if __name__ == "__main__":
162
+ main()
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/univnet/feature_extraction_univnet.py ADDED
@@ -0,0 +1,459 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team. 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
+ """Feature extractor class for UnivNetModel."""
15
+
16
+ from typing import Any, Optional, Union
17
+
18
+ import numpy as np
19
+
20
+ from ...audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function
21
+ from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
22
+ from ...feature_extraction_utils import BatchFeature
23
+ from ...utils import PaddingStrategy, TensorType, logging
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+
29
+ class UnivNetFeatureExtractor(SequenceFeatureExtractor):
30
+ r"""
31
+ Constructs a UnivNet feature extractor.
32
+
33
+ This class extracts log-mel-filter bank features from raw speech using the short time Fourier Transform (STFT). The
34
+ STFT implementation follows that of TacoTron 2 and Hifi-GAN.
35
+
36
+ This feature extractor inherits from [`~feature_extraction_sequence_utils.SequenceFeatureExtractor`] which contains
37
+ most of the main methods. Users should refer to this superclass for more information regarding those methods.
38
+
39
+ Args:
40
+ feature_size (`int`, *optional*, defaults to 1):
41
+ The feature dimension of the extracted features.
42
+ sampling_rate (`int`, *optional*, defaults to 24000):
43
+ The sampling rate at which the audio files should be digitalized expressed in hertz (Hz).
44
+ padding_value (`float`, *optional*, defaults to 0.0):
45
+ The value to pad with when applying the padding strategy defined by the `padding` argument to
46
+ [`UnivNetFeatureExtractor.__call__`]. Should correspond to audio silence. The `pad_end` argument to
47
+ `__call__` will also use this padding value.
48
+ do_normalize (`bool`, *optional*, defaults to `False`):
49
+ Whether to perform Tacotron 2 normalization on the input. Normalizing can help to significantly improve the
50
+ performance for some models.
51
+ num_mel_bins (`int`, *optional*, defaults to 100):
52
+ The number of mel-frequency bins in the extracted spectrogram features. This should match
53
+ `UnivNetModel.config.num_mel_bins`.
54
+ hop_length (`int`, *optional*, defaults to 256):
55
+ The direct number of samples between sliding windows. Otherwise referred to as "shift" in many papers. Note
56
+ that this is different from other audio feature extractors such as [`SpeechT5FeatureExtractor`] which take
57
+ the `hop_length` in ms.
58
+ win_length (`int`, *optional*, defaults to 1024):
59
+ The direct number of samples for each sliding window. Note that this is different from other audio feature
60
+ extractors such as [`SpeechT5FeatureExtractor`] which take the `win_length` in ms.
61
+ win_function (`str`, *optional*, defaults to `"hann_window"`):
62
+ Name for the window function used for windowing, must be accessible via `torch.{win_function}`
63
+ filter_length (`int`, *optional*, defaults to 1024):
64
+ The number of FFT components to use. If `None`, this is determined using
65
+ `transformers.audio_utils.optimal_fft_length`.
66
+ max_length_s (`int`, *optional*, defaults to 10):
67
+ The maximum input length of the model in seconds. This is used to pad the audio.
68
+ fmin (`float`, *optional*, defaults to 0.0):
69
+ Minimum mel frequency in Hz.
70
+ fmax (`float`, *optional*):
71
+ Maximum mel frequency in Hz. If not set, defaults to `sampling_rate / 2`.
72
+ mel_floor (`float`, *optional*, defaults to 1e-09):
73
+ Minimum value of mel frequency banks. Note that the way [`UnivNetFeatureExtractor`] uses `mel_floor` is
74
+ different than in [`transformers.audio_utils.spectrogram`].
75
+ center (`bool`, *optional*, defaults to `False`):
76
+ Whether to pad the waveform so that frame `t` is centered around time `t * hop_length`. If `False`, frame
77
+ `t` will start at time `t * hop_length`.
78
+ compression_factor (`float`, *optional*, defaults to 1.0):
79
+ The multiplicative compression factor for dynamic range compression during spectral normalization.
80
+ compression_clip_val (`float`, *optional*, defaults to 1e-05):
81
+ The clip value applied to the waveform before applying dynamic range compression during spectral
82
+ normalization.
83
+ normalize_min (`float`, *optional*, defaults to -11.512925148010254):
84
+ The min value used for Tacotron 2-style linear normalization. The default is the original value from the
85
+ Tacotron 2 implementation.
86
+ normalize_max (`float`, *optional*, defaults to 2.3143386840820312):
87
+ The max value used for Tacotron 2-style linear normalization. The default is the original value from the
88
+ Tacotron 2 implementation.
89
+ model_in_channels (`int`, *optional*, defaults to 64):
90
+ The number of input channels to the [`UnivNetModel`] model. This should match
91
+ `UnivNetModel.config.model_in_channels`.
92
+ pad_end_length (`int`, *optional*, defaults to 10):
93
+ If padding the end of each waveform, the number of spectrogram frames worth of samples to append. The
94
+ number of appended samples will be `pad_end_length * hop_length`.
95
+ return_attention_mask (`bool`, *optional*, defaults to `True`):
96
+ Whether or not [`~UnivNetFeatureExtractor.__call__`] should return `attention_mask`.
97
+ """
98
+
99
+ model_input_names = ["input_features", "noise_sequence", "padding_mask"]
100
+
101
+ def __init__(
102
+ self,
103
+ feature_size: int = 1,
104
+ sampling_rate: int = 24000,
105
+ padding_value: float = 0.0,
106
+ do_normalize: bool = False,
107
+ num_mel_bins: int = 100,
108
+ hop_length: int = 256,
109
+ win_length: int = 1024,
110
+ win_function: str = "hann_window",
111
+ filter_length: Optional[int] = 1024,
112
+ max_length_s: int = 10,
113
+ fmin: float = 0.0,
114
+ fmax: Optional[float] = None,
115
+ mel_floor: float = 1e-9,
116
+ center: bool = False,
117
+ compression_factor: float = 1.0,
118
+ compression_clip_val: float = 1e-5,
119
+ normalize_min: float = -11.512925148010254,
120
+ normalize_max: float = 2.3143386840820312,
121
+ model_in_channels: int = 64,
122
+ pad_end_length: int = 10,
123
+ return_attention_mask=True,
124
+ **kwargs,
125
+ ):
126
+ super().__init__(
127
+ feature_size=feature_size,
128
+ sampling_rate=sampling_rate,
129
+ padding_value=padding_value,
130
+ return_attention_mask=return_attention_mask,
131
+ **kwargs,
132
+ )
133
+
134
+ self.do_normalize = do_normalize
135
+
136
+ self.num_mel_bins = num_mel_bins
137
+ self.hop_length = hop_length
138
+ self.win_length = win_length
139
+ self.win_function = win_function
140
+ self.filter_length = filter_length
141
+ self.fmin = fmin
142
+ if fmax is None:
143
+ # Follows the librosa.filters.mel implementation
144
+ fmax = float(sampling_rate) / 2
145
+ self.fmax = fmax
146
+ self.mel_floor = mel_floor
147
+
148
+ self.max_length_s = max_length_s
149
+ self.num_max_samples = max_length_s * sampling_rate
150
+
151
+ if self.filter_length is None:
152
+ self.n_fft = optimal_fft_length(self.win_length)
153
+ else:
154
+ self.n_fft = self.filter_length
155
+ self.n_freqs = (self.n_fft // 2) + 1
156
+
157
+ self.window = window_function(window_length=self.win_length, name=self.win_function, periodic=True)
158
+
159
+ self.mel_filters = mel_filter_bank(
160
+ num_frequency_bins=self.n_freqs,
161
+ num_mel_filters=self.num_mel_bins,
162
+ min_frequency=self.fmin,
163
+ max_frequency=self.fmax,
164
+ sampling_rate=self.sampling_rate,
165
+ norm="slaney",
166
+ mel_scale="slaney",
167
+ )
168
+
169
+ self.center = center
170
+ self.compression_factor = compression_factor
171
+ self.compression_clip_val = compression_clip_val
172
+ self.normalize_min = normalize_min
173
+ self.normalize_max = normalize_max
174
+ self.model_in_channels = model_in_channels
175
+ self.pad_end_length = pad_end_length
176
+
177
+ def normalize(self, spectrogram):
178
+ return 2 * ((spectrogram - self.normalize_min) / (self.normalize_max - self.normalize_min)) - 1
179
+
180
+ def denormalize(self, spectrogram):
181
+ return self.normalize_min + (self.normalize_max - self.normalize_min) * ((spectrogram + 1) / 2)
182
+
183
+ def mel_spectrogram(self, waveform: np.ndarray) -> np.ndarray:
184
+ """
185
+ Calculates log MEL spectrograms from a batch of waveforms. Note that the input waveform(s) will be padded by
186
+ `int(self.n_fft - self.hop_length) / 2` on both sides using the `reflect` padding mode.
187
+
188
+ Args:
189
+ waveform (`np.ndarray` of shape `(length,)`):
190
+ The input waveform. This must be a single real-valued, mono waveform.
191
+
192
+ Returns:
193
+ `numpy.ndarray`: Array containing a log-mel spectrogram of shape `(num_frames, num_mel_bins)`.
194
+ """
195
+ # Do custom padding based on the official MelGAN and Hifi-GAN implementations
196
+ # See https://github.com/maum-ai/univnet/blob/9bb2b54838bb6d7ce767131cc7b8b61198bc7558/utils/stft.py#L84-L86
197
+ waveform = np.pad(
198
+ waveform,
199
+ (int((self.n_fft - self.hop_length) / 2), int((self.n_fft - self.hop_length) / 2)),
200
+ mode="reflect",
201
+ )
202
+
203
+ # Get the complex spectrogram.
204
+ # Note: waveform must be unbatched currently due to the implementation of spectrogram(...).
205
+ complex_spectrogram = spectrogram(
206
+ waveform,
207
+ window=self.window,
208
+ frame_length=self.n_fft,
209
+ hop_length=self.hop_length,
210
+ fft_length=self.n_fft,
211
+ power=None,
212
+ center=self.center,
213
+ mel_filters=None,
214
+ mel_floor=None,
215
+ )
216
+
217
+ # Apply the MEL filter bank and MEL floor manually since UnivNet uses a slightly different implementation
218
+ amplitude_spectrogram = np.sqrt(
219
+ np.real(complex_spectrogram) ** 2 + np.imag(complex_spectrogram) ** 2 + self.mel_floor
220
+ )
221
+ mel_spectrogram = np.matmul(self.mel_filters.T, amplitude_spectrogram)
222
+
223
+ # Perform spectral normalization to get the log mel spectrogram.
224
+ log_mel_spectrogram = np.log(
225
+ np.clip(mel_spectrogram, a_min=self.compression_clip_val, a_max=None) * self.compression_factor
226
+ )
227
+
228
+ # Return spectrogram with num_mel_bins last
229
+ return log_mel_spectrogram.T
230
+
231
+ def generate_noise(
232
+ self,
233
+ noise_length: int,
234
+ generator: Optional[np.random.Generator] = None,
235
+ ) -> np.ndarray:
236
+ """
237
+ Generates a random noise sequence of standard Gaussian noise for use in the `noise_sequence` argument of
238
+ [`UnivNetModel.forward`].
239
+
240
+ Args:
241
+ spectrogram_length (`int`):
242
+ The length (dim 0) of the generated noise.
243
+ model_in_channels (`int`, *optional*, defaults to `None`):
244
+ The number of features (dim 1) of the generated noise. This should correspond to the
245
+ `model_in_channels` of the [`UnivNetGan`] model. If not set, this will default to
246
+ `self.config.model_in_channels`.
247
+ generator (`numpy.random.Generator`, *optional*, defaults to `None`)
248
+ An optional `numpy.random.Generator` random number generator to control noise generation. If not set, a
249
+ new generator with fresh entropy will be created.
250
+
251
+ Returns:
252
+ `numpy.ndarray`: Array containing random standard Gaussian noise of shape `(noise_length,
253
+ model_in_channels)`.
254
+ """
255
+ if generator is None:
256
+ generator = np.random.default_rng()
257
+
258
+ noise_shape = (noise_length, self.model_in_channels)
259
+ noise = generator.standard_normal(noise_shape, dtype=np.float32)
260
+
261
+ return noise
262
+
263
+ def batch_decode(self, waveforms, waveform_lengths=None) -> list[np.ndarray]:
264
+ r"""
265
+ Removes padding from generated audio after running [`UnivNetModel.forward`]. This returns a ragged list of 1D
266
+ audio waveform arrays and not a single tensor/array because in general the waveforms will have different
267
+ lengths after removing padding.
268
+
269
+ Args:
270
+ waveforms (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
271
+ The batched output waveforms from the [`UnivNetModel`].
272
+ waveform_lengths (`torch.FloatTensor` of shape `(batch_size,)`, *optional*):
273
+ The batched lengths of each waveform before padding.
274
+
275
+ Returns:
276
+ `list[np.ndarray]`: A ragged list of 1D waveform arrays with padding removed.
277
+ """
278
+ # Collapse the batched waveform tensor to a list of 1D audio waveforms
279
+ waveforms = [waveform.detach().to(device="cpu", copy=True).numpy() for waveform in waveforms]
280
+
281
+ if waveform_lengths is not None:
282
+ waveforms = [waveform[: waveform_lengths[i]] for i, waveform in enumerate(waveforms)]
283
+
284
+ return waveforms
285
+
286
+ def __call__(
287
+ self,
288
+ raw_speech: Union[np.ndarray, list[float], list[np.ndarray], list[list[float]]],
289
+ sampling_rate: Optional[int] = None,
290
+ padding: Union[bool, str, PaddingStrategy] = True,
291
+ max_length: Optional[int] = None,
292
+ truncation: bool = True,
293
+ pad_to_multiple_of: Optional[int] = None,
294
+ return_noise: bool = True,
295
+ generator: Optional[np.random.Generator] = None,
296
+ pad_end: bool = False,
297
+ pad_length: Optional[int] = None,
298
+ do_normalize: Optional[str] = None,
299
+ return_attention_mask: Optional[bool] = None,
300
+ return_tensors: Optional[Union[str, TensorType]] = None,
301
+ ) -> BatchFeature:
302
+ """
303
+ Main method to featurize and prepare for the model one or several sequence(s).
304
+
305
+ Args:
306
+ raw_speech (`np.ndarray`, `list[float]`, `list[np.ndarray]`, `list[list[float]]`):
307
+ The sequence or batch of sequences to be padded. Each sequence can be a numpy array, a list of float
308
+ values, a list of numpy arrays or a list of list of float values. Must be mono channel audio, not
309
+ stereo, i.e. single float per timestep.
310
+ sampling_rate (`int`, *optional*):
311
+ The sampling rate at which the `raw_speech` input was sampled. It is strongly recommended to pass
312
+ `sampling_rate` at the forward call to prevent silent errors and allow automatic speech recognition
313
+ pipeline.
314
+ padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True`):
315
+ Select a strategy to pad the input `raw_speech` waveforms (according to the model's padding side and
316
+ padding index) among:
317
+
318
+ - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
319
+ sequence if provided).
320
+ - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
321
+ acceptable input length for the model if that argument is not provided.
322
+ - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
323
+ lengths).
324
+
325
+ If `pad_end = True`, that padding will occur before the `padding` strategy is applied.
326
+ max_length (`int`, *optional*):
327
+ Maximum length of the returned list and optionally padding length (see above).
328
+ truncation (`bool`, *optional*, defaults to `True`):
329
+ Activates truncation to cut input sequences longer than `max_length` to `max_length`.
330
+ pad_to_multiple_of (`int`, *optional*):
331
+ If set will pad the sequence to a multiple of the provided value.
332
+
333
+ This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability
334
+ `>= 7.5` (Volta), or on TPUs which benefit from having sequence lengths be a multiple of 128.
335
+ return_noise (`bool`, *optional*, defaults to `True`):
336
+ Whether to generate and return a noise waveform for use in [`UnivNetModel.forward`].
337
+ generator (`numpy.random.Generator`, *optional*, defaults to `None`):
338
+ An optional `numpy.random.Generator` random number generator to use when generating noise.
339
+ pad_end (`bool`, *optional*, defaults to `False`):
340
+ Whether to pad the end of each waveform with silence. This can help reduce artifacts at the end of the
341
+ generated audio sample; see https://github.com/seungwonpark/melgan/issues/8 for more details. This
342
+ padding will be done before the padding strategy specified in `padding` is performed.
343
+ pad_length (`int`, *optional*, defaults to `None`):
344
+ If padding the end of each waveform, the length of the padding in spectrogram frames. If not set, this
345
+ will default to `self.config.pad_end_length`.
346
+ do_normalize (`bool`, *optional*):
347
+ Whether to perform Tacotron 2 normalization on the input. Normalizing can help to significantly improve
348
+ the performance for some models. If not set, this will default to `self.config.do_normalize`.
349
+ return_attention_mask (`bool`, *optional*):
350
+ Whether to return the attention mask. If left to the default, will return the attention mask according
351
+ to the specific feature_extractor's default.
352
+
353
+ [What are attention masks?](../glossary#attention-mask)
354
+
355
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
356
+ If set, will return tensors instead of list of python integers. Acceptable values are:
357
+
358
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
359
+ - `'pt'`: Return PyTorch `torch.np.array` objects.
360
+ - `'np'`: Return Numpy `np.ndarray` objects.
361
+ """
362
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
363
+
364
+ if sampling_rate is not None:
365
+ if sampling_rate != self.sampling_rate:
366
+ raise ValueError(
367
+ f"The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a"
368
+ f" sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input"
369
+ f" was sampled with {self.sampling_rate} and not {sampling_rate}."
370
+ )
371
+ else:
372
+ logger.warning(
373
+ f"It is strongly recommended to pass the `sampling_rate` argument to `{self.__class__.__name__}()`. "
374
+ "Failing to do so can result in silent errors that might be hard to debug."
375
+ )
376
+
377
+ is_batched_numpy = isinstance(raw_speech, np.ndarray) and len(raw_speech.shape) > 1
378
+ if is_batched_numpy and len(raw_speech.shape) > 2:
379
+ raise ValueError(f"Only mono-channel audio is supported for input to {self}")
380
+ is_batched = is_batched_numpy or (
381
+ isinstance(raw_speech, (list, tuple)) and (isinstance(raw_speech[0], (np.ndarray, tuple, list)))
382
+ )
383
+
384
+ if is_batched:
385
+ raw_speech = [np.asarray(speech, dtype=np.float32) for speech in raw_speech]
386
+ elif not is_batched and not isinstance(raw_speech, np.ndarray):
387
+ raw_speech = np.asarray(raw_speech, dtype=np.float32)
388
+ elif isinstance(raw_speech, np.ndarray) and raw_speech.dtype is np.dtype(np.float64):
389
+ raw_speech = raw_speech.astype(np.float32)
390
+
391
+ # always return batch
392
+ if not is_batched:
393
+ raw_speech = [np.asarray(raw_speech, dtype=np.float32)]
394
+
395
+ # Pad end to reduce artifacts
396
+ if pad_end:
397
+ pad_length = pad_length if pad_length is not None else self.pad_end_length
398
+ raw_speech = [
399
+ np.pad(waveform, (0, pad_length * self.hop_length), constant_values=self.padding_value)
400
+ for waveform in raw_speech
401
+ ]
402
+
403
+ batched_speech = BatchFeature({"input_features": raw_speech})
404
+
405
+ padded_inputs = self.pad(
406
+ batched_speech,
407
+ padding=padding,
408
+ max_length=max_length if max_length is not None else self.num_max_samples,
409
+ truncation=truncation,
410
+ pad_to_multiple_of=pad_to_multiple_of,
411
+ return_attention_mask=return_attention_mask,
412
+ )
413
+
414
+ # make sure list is in array format
415
+ # input_features = padded_inputs.get("input_features").transpose(2, 0, 1)
416
+ input_features = padded_inputs.get("input_features")
417
+
418
+ mel_spectrograms = [self.mel_spectrogram(waveform) for waveform in input_features]
419
+
420
+ if isinstance(input_features[0], list):
421
+ batched_speech["input_features"] = [np.asarray(mel, dtype=np.float32) for mel in mel_spectrograms]
422
+ else:
423
+ batched_speech["input_features"] = [mel.astype(np.float32) for mel in mel_spectrograms]
424
+
425
+ # convert attention_mask to correct format
426
+ attention_mask = padded_inputs.get("attention_mask")
427
+ if attention_mask is not None:
428
+ batched_speech["padding_mask"] = [np.asarray(array, dtype=np.int32) for array in attention_mask]
429
+
430
+ if return_noise:
431
+ noise = [
432
+ self.generate_noise(spectrogram.shape[0], generator)
433
+ for spectrogram in batched_speech["input_features"]
434
+ ]
435
+ batched_speech["noise_sequence"] = noise
436
+
437
+ if do_normalize:
438
+ batched_speech["input_features"] = [
439
+ self.normalize(spectrogram) for spectrogram in batched_speech["input_features"]
440
+ ]
441
+
442
+ if return_tensors is not None:
443
+ batched_speech = batched_speech.convert_to_tensors(return_tensors)
444
+
445
+ return batched_speech
446
+
447
+ def to_dict(self) -> dict[str, Any]:
448
+ output = super().to_dict()
449
+
450
+ # Don't serialize these as they are derived from the other properties.
451
+ names = ["window", "mel_filters", "n_fft", "n_freqs", "num_max_samples"]
452
+ for name in names:
453
+ if name in output:
454
+ del output[name]
455
+
456
+ return output
457
+
458
+
459
+ __all__ = ["UnivNetFeatureExtractor"]
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/univnet/modeling_univnet.py ADDED
@@ -0,0 +1,618 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team. 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
+ """PyTorch UnivNetModel model."""
15
+
16
+ from dataclasses import dataclass
17
+ from typing import Optional, Union
18
+
19
+ import torch
20
+ import torch.utils.checkpoint
21
+ from torch import nn
22
+
23
+ from ...modeling_outputs import ModelOutput
24
+ from ...modeling_utils import PreTrainedModel
25
+ from ...utils import auto_docstring, logging
26
+ from .configuration_univnet import UnivNetConfig
27
+
28
+
29
+ logger = logging.get_logger(__name__)
30
+
31
+
32
+ @dataclass
33
+ @auto_docstring(
34
+ custom_intro="""
35
+ Output class for the [`UnivNetModel`], which includes the generated audio waveforms and the original unpadded
36
+ lengths of those waveforms (so that the padding can be removed by [`UnivNetModel.batch_decode`]).
37
+ """
38
+ )
39
+ class UnivNetModelOutput(ModelOutput):
40
+ r"""
41
+ waveforms (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
42
+ Batched 1D (mono-channel) output audio waveforms.
43
+ waveform_lengths (`torch.FloatTensor` of shape `(batch_size,)`):
44
+ The batched length in samples of each unpadded waveform in `waveforms`.
45
+ """
46
+
47
+ waveforms: Optional[torch.FloatTensor] = None
48
+ waveform_lengths: Optional[torch.FloatTensor] = None
49
+
50
+
51
+ class UnivNetKernelPredictorResidualBlock(nn.Module):
52
+ """
53
+ Implementation of the residual block for the kernel predictor network inside each location variable convolution
54
+ block (LVCBlock).
55
+
56
+ Parameters:
57
+ config: (`UnivNetConfig`):
58
+ Config for the `UnivNetModel` model.
59
+ """
60
+
61
+ def __init__(
62
+ self,
63
+ config: UnivNetConfig,
64
+ ):
65
+ super().__init__()
66
+ self.channels = config.model_in_channels
67
+ self.kernel_size = config.kernel_predictor_conv_size
68
+ self.dropout_prob = config.kernel_predictor_dropout
69
+ self.leaky_relu_slope = config.leaky_relu_slope
70
+
71
+ padding = (self.kernel_size - 1) // 2
72
+
73
+ self.dropout = nn.Dropout(self.dropout_prob)
74
+ self.conv1 = nn.Conv1d(self.channels, self.channels, self.kernel_size, padding=padding, bias=True)
75
+ self.conv2 = nn.Conv1d(self.channels, self.channels, self.kernel_size, padding=padding, bias=True)
76
+
77
+ def forward(self, hidden_states: torch.FloatTensor):
78
+ # hidden_states should have shape (batch_size, channels, seq_length)
79
+ residual = hidden_states
80
+ hidden_states = self.dropout(hidden_states)
81
+ hidden_states = self.conv1(hidden_states)
82
+ hidden_states = nn.functional.leaky_relu(hidden_states, self.leaky_relu_slope)
83
+ hidden_states = self.conv2(hidden_states)
84
+ hidden_states = nn.functional.leaky_relu(hidden_states, self.leaky_relu_slope)
85
+ return hidden_states + residual
86
+
87
+ def apply_weight_norm(self):
88
+ weight_norm = nn.utils.weight_norm
89
+ if hasattr(nn.utils.parametrizations, "weight_norm"):
90
+ weight_norm = nn.utils.parametrizations.weight_norm
91
+
92
+ weight_norm(self.conv1)
93
+ weight_norm(self.conv2)
94
+
95
+ def remove_weight_norm(self):
96
+ nn.utils.remove_weight_norm(self.conv1)
97
+ nn.utils.remove_weight_norm(self.conv2)
98
+
99
+
100
+ class UnivNetKernelPredictor(nn.Module):
101
+ """
102
+ Implementation of the kernel predictor network which supplies the kernel and bias for the location variable
103
+ convolutional layers (LVCs) in each UnivNet LVCBlock.
104
+
105
+ Based on the KernelPredictor implementation in
106
+ [maum-ai/univnet](https://github.com/maum-ai/univnet/blob/9bb2b54838bb6d7ce767131cc7b8b61198bc7558/model/lvcnet.py#L7).
107
+
108
+ Parameters:
109
+ config: (`UnivNetConfig`):
110
+ Config for the `UnivNetModel` model.
111
+ conv_kernel_size (`int`, *optional*, defaults to 3):
112
+ The kernel size for the location variable convolutional layer kernels (convolutional weight tensor).
113
+ conv_layers (`int`, *optional*, defaults to 4):
114
+ The number of location variable convolutional layers to output kernels and biases for.
115
+ """
116
+
117
+ def __init__(
118
+ self,
119
+ config: UnivNetConfig,
120
+ conv_kernel_size: int = 3,
121
+ conv_layers: int = 4,
122
+ ):
123
+ super().__init__()
124
+
125
+ self.conv_in_channels = config.model_hidden_channels
126
+ self.conv_out_channels = 2 * config.model_hidden_channels
127
+ self.conv_kernel_size = conv_kernel_size
128
+ self.conv_layers = conv_layers
129
+
130
+ self.kernel_channels = (
131
+ self.conv_in_channels * self.conv_out_channels * self.conv_kernel_size * self.conv_layers
132
+ )
133
+ self.bias_channels = self.conv_out_channels * self.conv_layers
134
+
135
+ self.resnet_in_channels = config.num_mel_bins
136
+ self.resnet_hidden_channels = config.kernel_predictor_hidden_channels
137
+ self.resnet_kernel_size = config.kernel_predictor_conv_size
138
+ self.num_blocks = config.kernel_predictor_num_blocks
139
+
140
+ self.leaky_relu_slope = config.leaky_relu_slope
141
+
142
+ padding = (self.resnet_kernel_size - 1) // 2
143
+
144
+ self.input_conv = nn.Conv1d(self.resnet_in_channels, self.resnet_hidden_channels, 5, padding=2, bias=True)
145
+
146
+ self.resblocks = nn.ModuleList([UnivNetKernelPredictorResidualBlock(config) for _ in range(self.num_blocks)])
147
+
148
+ self.kernel_conv = nn.Conv1d(
149
+ self.resnet_hidden_channels, self.kernel_channels, self.resnet_kernel_size, padding=padding, bias=True
150
+ )
151
+ self.bias_conv = nn.Conv1d(
152
+ self.resnet_hidden_channels, self.bias_channels, self.resnet_kernel_size, padding=padding, bias=True
153
+ )
154
+
155
+ def forward(self, spectrogram: torch.FloatTensor):
156
+ """
157
+ Maps a conditioning log-mel spectrogram to a tensor of convolutional kernels and biases, for use in location
158
+ variable convolutional layers. Note that the input spectrogram should have shape (batch_size, input_channels,
159
+ seq_length).
160
+
161
+ Args:
162
+ spectrogram (`torch.FloatTensor` of shape `(batch_size, input_channels, seq_length)`):
163
+ Tensor containing the log-mel spectrograms.
164
+
165
+ Returns:
166
+ tuple[`torch.FloatTensor, `torch.FloatTensor`]: tuple of tensors where the first element is the tensor of
167
+ location variable convolution kernels of shape `(batch_size, self.conv_layers, self.conv_in_channels,
168
+ self.conv_out_channels, self.conv_kernel_size, seq_length)` and the second element is the tensor of
169
+ location variable convolution biases of shape `(batch_size, self.conv_layers. self.conv_out_channels,
170
+ seq_length)`.
171
+ """
172
+ batch_size, _, seq_length = spectrogram.shape
173
+
174
+ hidden_states = self.input_conv(spectrogram)
175
+ hidden_states = nn.functional.leaky_relu(hidden_states, self.leaky_relu_slope)
176
+
177
+ for resblock in self.resblocks:
178
+ hidden_states = resblock(hidden_states)
179
+
180
+ kernel_hidden_states = self.kernel_conv(hidden_states)
181
+ bias_hidden_states = self.bias_conv(hidden_states)
182
+
183
+ # Reshape kernels and biases to appropriate shape
184
+ kernels = kernel_hidden_states.view(
185
+ batch_size,
186
+ self.conv_layers,
187
+ self.conv_in_channels,
188
+ self.conv_out_channels,
189
+ self.conv_kernel_size,
190
+ seq_length,
191
+ ).contiguous()
192
+ biases = bias_hidden_states.view(
193
+ batch_size,
194
+ self.conv_layers,
195
+ self.conv_out_channels,
196
+ seq_length,
197
+ ).contiguous()
198
+
199
+ return kernels, biases
200
+
201
+ def apply_weight_norm(self):
202
+ weight_norm = nn.utils.weight_norm
203
+ if hasattr(nn.utils.parametrizations, "weight_norm"):
204
+ weight_norm = nn.utils.parametrizations.weight_norm
205
+
206
+ weight_norm(self.input_conv)
207
+ for layer in self.resblocks:
208
+ layer.apply_weight_norm()
209
+ weight_norm(self.kernel_conv)
210
+ weight_norm(self.bias_conv)
211
+
212
+ def remove_weight_norm(self):
213
+ nn.utils.remove_weight_norm(self.input_conv)
214
+ for layer in self.resblocks:
215
+ layer.remove_weight_norm()
216
+ nn.utils.remove_weight_norm(self.kernel_conv)
217
+ nn.utils.remove_weight_norm(self.bias_conv)
218
+
219
+
220
+ class UnivNetLvcResidualBlock(nn.Module):
221
+ """
222
+ Implementation of the location variable convolution (LVC) residual block for the UnivNet residual network.
223
+
224
+ Parameters:
225
+ config: (`UnivNetConfig`):
226
+ Config for the `UnivNetModel` model.
227
+ kernel_size (`int`):
228
+ The kernel size for the dilated 1D convolutional layer.
229
+ dilation (`int`):
230
+ The dilation for the dilated 1D convolutional layer.
231
+ """
232
+
233
+ def __init__(
234
+ self,
235
+ config: UnivNetConfig,
236
+ kernel_size: int,
237
+ dilation: int,
238
+ ):
239
+ super().__init__()
240
+ self.hidden_channels = config.model_hidden_channels
241
+ self.kernel_size = kernel_size
242
+ self.dilation = dilation
243
+ self.leaky_relu_slope = config.leaky_relu_slope
244
+
245
+ padding = self.dilation * (self.kernel_size - 1) // 2
246
+
247
+ self.conv = nn.Conv1d(
248
+ self.hidden_channels,
249
+ self.hidden_channels,
250
+ self.kernel_size,
251
+ padding=padding,
252
+ dilation=self.dilation,
253
+ )
254
+
255
+ def forward(self, hidden_states, kernel, bias, hop_size=256):
256
+ residual = hidden_states
257
+ hidden_states = nn.functional.leaky_relu(hidden_states, self.leaky_relu_slope)
258
+ hidden_states = self.conv(hidden_states)
259
+ hidden_states = nn.functional.leaky_relu(hidden_states, self.leaky_relu_slope)
260
+ hidden_states = self.location_variable_convolution(hidden_states, kernel, bias, hop_size=hop_size)
261
+ # Gated activation unit
262
+ hidden_states = torch.sigmoid(hidden_states[:, : self.hidden_channels, :]) * torch.tanh(
263
+ hidden_states[:, self.hidden_channels :, :]
264
+ )
265
+ # Skip connection
266
+ hidden_states = residual + hidden_states
267
+
268
+ return hidden_states
269
+
270
+ # Based on https://github.com/maum-ai/univnet/blob/9bb2b54838bb6d7ce767131cc7b8b61198bc7558/model/lvcnet.py#L171
271
+ def location_variable_convolution(
272
+ self,
273
+ hidden_states: torch.FloatTensor,
274
+ kernel: torch.FloatTensor,
275
+ bias: torch.FloatTensor,
276
+ dilation: int = 1,
277
+ hop_size: int = 256,
278
+ ):
279
+ """
280
+ Performs location-variable convolution operation on the input sequence (hidden_states) using the local
281
+ convolution kernel. This was introduced in [LVCNet: Efficient Condition-Dependent Modeling Network for Waveform
282
+ Generation](https://huggingface.co/papers/2102.10815) by Zhen Zheng, Jianzong Wang, Ning Cheng, and Jing Xiao.
283
+
284
+ Time: 414 μs ± 309 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each), test on NVIDIA V100.
285
+
286
+ Args:
287
+ hidden_states (`torch.FloatTensor` of shape `(batch_size, in_channels, in_length)`):
288
+ The input sequence of shape (batch, in_channels, in_length).
289
+ kernel (`torch.FloatTensor` of shape `(batch_size, in_channels, out_channels, kernel_size, kernel_length)`):
290
+ The local convolution kernel of shape (batch, in_channels, out_channels, kernel_size, kernel_length).
291
+ bias (`torch.FloatTensor` of shape `(batch_size, out_channels, kernel_length)`):
292
+ The bias for the local convolution of shape (batch, out_channels, kernel_length).
293
+ dilation (`int`, *optional*, defaults to 1):
294
+ The dilation of convolution.
295
+ hop_size (`int`, *optional*, defaults to 256):
296
+ The hop_size of the conditioning sequence.
297
+ Returns:
298
+ `torch.FloatTensor`: the output sequence after performing local convolution with shape (batch_size,
299
+ out_channels, in_length).
300
+ """
301
+ batch, _, in_length = hidden_states.shape
302
+ batch, _, out_channels, kernel_size, kernel_length = kernel.shape
303
+ if in_length != (kernel_length * hop_size):
304
+ raise ValueError(
305
+ f"Dim 2 of `hidden_states` should be {kernel_length * hop_size}) but got {in_length}. Please check"
306
+ " `hidden_states` or `kernel` and `hop_size` to make sure they are correct."
307
+ )
308
+
309
+ padding = dilation * int((kernel_size - 1) / 2)
310
+
311
+ # (batch, in_channels, in_length + 2*padding)
312
+ hidden_states = nn.functional.pad(hidden_states, (padding, padding), "constant", 0)
313
+ # (batch, in_channels, kernel_length, hop_size + 2*padding)
314
+ hidden_states = hidden_states.unfold(2, hop_size + 2 * padding, hop_size)
315
+
316
+ if hop_size < dilation:
317
+ hidden_states = nn.functional.pad(hidden_states, (0, dilation), "constant", 0)
318
+ # (batch, in_channels, kernel_length, (hop_size + 2*padding)/dilation, dilation)
319
+ hidden_states = hidden_states.unfold(3, dilation, dilation)
320
+ hidden_states = hidden_states[:, :, :, :, :hop_size]
321
+ # (batch, in_channels, kernel_length, dilation, (hop_size + 2*padding)/dilation)
322
+ hidden_states = hidden_states.transpose(3, 4)
323
+ # (batch, in_channels, kernel_length, dilation, _, kernel_size)
324
+ hidden_states = hidden_states.unfold(4, kernel_size, 1)
325
+
326
+ # Apply local convolution kernel to hidden_states.
327
+ output_hidden_states = torch.einsum("bildsk,biokl->bolsd", hidden_states, kernel)
328
+
329
+ output_hidden_states = output_hidden_states.to(memory_format=torch.channels_last_3d)
330
+ bias = bias.unsqueeze(-1).unsqueeze(-1).to(memory_format=torch.channels_last_3d)
331
+ output_hidden_states = output_hidden_states + bias
332
+ output_hidden_states = output_hidden_states.contiguous().view(batch, out_channels, -1)
333
+
334
+ return output_hidden_states
335
+
336
+ def apply_weight_norm(self):
337
+ weight_norm = nn.utils.weight_norm
338
+ if hasattr(nn.utils.parametrizations, "weight_norm"):
339
+ weight_norm = nn.utils.parametrizations.weight_norm
340
+
341
+ weight_norm(self.conv)
342
+
343
+ def remove_weight_norm(self):
344
+ nn.utils.remove_weight_norm(self.conv)
345
+
346
+
347
+ class UnivNetLvcBlock(nn.Module):
348
+ """
349
+ Implementation of the location variable convolution (LVC) residual block of the UnivNet residual block. Includes a
350
+ `UnivNetKernelPredictor` inside to predict the kernels and biases of the LVC layers.
351
+
352
+ Based on LVCBlock in
353
+ [maum-ai/univnet](https://github.com/maum-ai/univnet/blob/9bb2b54838bb6d7ce767131cc7b8b61198bc7558/model/lvcnet.py#L98)
354
+
355
+ Parameters:
356
+ config (`UnivNetConfig`):
357
+ Config for the `UnivNetModel` model.
358
+ layer_id (`int`):
359
+ An integer corresponding to the index of the current LVC resnet block layer. This should be between 0 and
360
+ `len(config.resblock_stride_sizes) - 1)` inclusive.
361
+ lvc_hop_size (`int`, *optional*, defaults to 256):
362
+ The hop size for the location variable convolutional layers.
363
+ """
364
+
365
+ def __init__(
366
+ self,
367
+ config: UnivNetConfig,
368
+ layer_id: int,
369
+ lvc_hop_size: int = 256,
370
+ ):
371
+ super().__init__()
372
+ self.hidden_channels = config.model_hidden_channels
373
+ self.kernel_size = config.resblock_kernel_sizes[layer_id]
374
+ self.stride = config.resblock_stride_sizes[layer_id]
375
+ self.dilations = config.resblock_dilation_sizes[layer_id]
376
+ self.cond_hop_length = lvc_hop_size
377
+ self.leaky_relu_slope = config.leaky_relu_slope
378
+ self.num_blocks = len(self.dilations)
379
+
380
+ self.convt_pre = nn.ConvTranspose1d(
381
+ self.hidden_channels,
382
+ self.hidden_channels,
383
+ 2 * self.stride,
384
+ stride=self.stride,
385
+ padding=self.stride // 2 + self.stride % 2,
386
+ output_padding=self.stride % 2,
387
+ )
388
+
389
+ self.kernel_predictor = UnivNetKernelPredictor(config, self.kernel_size, self.num_blocks)
390
+
391
+ self.resblocks = nn.ModuleList(
392
+ [UnivNetLvcResidualBlock(config, self.kernel_size, self.dilations[i]) for i in range(self.num_blocks)]
393
+ )
394
+
395
+ def forward(self, hidden_states: torch.FloatTensor, spectrogram: torch.FloatTensor):
396
+ # hidden_states: (batch_size, hidden_channels, seq_length)
397
+ # spectrogram: (batch_size, cond_channels, cond_length)
398
+ hidden_states = nn.functional.leaky_relu(hidden_states, self.leaky_relu_slope)
399
+ hidden_states = self.convt_pre(hidden_states)
400
+
401
+ kernels, biases = self.kernel_predictor(spectrogram)
402
+
403
+ for i, resblock in enumerate(self.resblocks):
404
+ kernel = kernels[:, i, :, :, :, :]
405
+ bias = biases[:, i, :, :]
406
+ hidden_states = resblock(hidden_states, kernel, bias, hop_size=self.cond_hop_length)
407
+
408
+ return hidden_states
409
+
410
+ def apply_weight_norm(self):
411
+ weight_norm = nn.utils.weight_norm
412
+ if hasattr(nn.utils.parametrizations, "weight_norm"):
413
+ weight_norm = nn.utils.parametrizations.weight_norm
414
+
415
+ weight_norm(self.convt_pre)
416
+ self.kernel_predictor.apply_weight_norm()
417
+ for layer in self.resblocks:
418
+ layer.apply_weight_norm()
419
+
420
+ def remove_weight_norm(self):
421
+ nn.utils.remove_weight_norm(self.convt_pre)
422
+ self.kernel_predictor.remove_weight_norm()
423
+ for layer in self.resblocks:
424
+ layer.remove_weight_norm()
425
+
426
+
427
+ @auto_docstring
428
+ class UnivNetModel(PreTrainedModel):
429
+ config: UnivNetConfig
430
+ main_input_name = "input_features"
431
+
432
+ def __init__(self, config: UnivNetConfig):
433
+ super().__init__(config)
434
+
435
+ self.num_kernels = len(config.resblock_kernel_sizes)
436
+ self.leaky_relu_slope = config.leaky_relu_slope
437
+
438
+ self.conv_pre = nn.Conv1d(
439
+ config.model_in_channels,
440
+ config.model_hidden_channels,
441
+ kernel_size=7,
442
+ stride=1,
443
+ padding=3,
444
+ padding_mode="reflect",
445
+ )
446
+
447
+ # Initialize location-variable convolution ResNet Blocks.
448
+ num_layers = len(config.resblock_stride_sizes)
449
+ hop_length = 1
450
+ hop_lengths = []
451
+ for stride in config.resblock_stride_sizes:
452
+ hop_length = hop_length * stride
453
+ hop_lengths.append(hop_length)
454
+
455
+ self.resblocks = nn.ModuleList(
456
+ [
457
+ UnivNetLvcBlock(
458
+ config,
459
+ layer_id=i,
460
+ lvc_hop_size=hop_lengths[i],
461
+ )
462
+ for i in range(num_layers)
463
+ ]
464
+ )
465
+
466
+ self.conv_post = nn.Conv1d(config.model_hidden_channels, 1, 7, padding=3, padding_mode="reflect")
467
+
468
+ # Initialize weights and apply final processing
469
+ self.post_init()
470
+
471
+ @auto_docstring
472
+ def forward(
473
+ self,
474
+ input_features: torch.FloatTensor,
475
+ noise_sequence: Optional[torch.FloatTensor] = None,
476
+ padding_mask: Optional[torch.FloatTensor] = None,
477
+ generator: Optional[torch.Generator] = None,
478
+ return_dict: Optional[bool] = None,
479
+ ) -> Union[tuple[torch.FloatTensor], UnivNetModelOutput]:
480
+ r"""
481
+ noise_sequence (`torch.FloatTensor`, *optional*):
482
+ Tensor containing a noise sequence of standard Gaussian noise. Can be batched and of shape `(batch_size,
483
+ sequence_length, config.model_in_channels)`, or un-batched and of shape (sequence_length,
484
+ config.model_in_channels)`. If not supplied, will be randomly generated.
485
+ padding_mask (`torch.BoolTensor`, *optional*):
486
+ Mask indicating which parts of each sequence are padded. Mask values are selected in `[0, 1]`:
487
+
488
+ - 1 for tokens that are **not masked**
489
+ - 0 for tokens that are **masked**
490
+
491
+ The mask can be batched and of shape `(batch_size, sequence_length)` or un-batched and of shape
492
+ `(sequence_length,)`.
493
+ generator (`torch.Generator`, *optional*):
494
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
495
+ deterministic.
496
+ return_dict:
497
+ Whether to return a [`~utils.ModelOutput`] subclass instead of a plain tuple.
498
+
499
+ Example:
500
+
501
+ ```python
502
+ >>> from transformers import UnivNetFeatureExtractor, UnivNetModel
503
+ >>> from datasets import load_dataset, Audio
504
+
505
+ >>> model = UnivNetModel.from_pretrained("dg845/univnet-dev")
506
+ >>> feature_extractor = UnivNetFeatureExtractor.from_pretrained("dg845/univnet-dev")
507
+
508
+ >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
509
+ >>> # Resample the audio to the feature extractor's sampling rate.
510
+ >>> ds = ds.cast_column("audio", Audio(sampling_rate=feature_extractor.sampling_rate))
511
+ >>> inputs = feature_extractor(
512
+ ... ds[0]["audio"]["array"], sampling_rate=ds[0]["audio"]["sampling_rate"], return_tensors="pt"
513
+ ... )
514
+ >>> audio = model(**inputs).waveforms
515
+ >>> list(audio.shape)
516
+ [1, 140288]
517
+ ```
518
+ """
519
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
520
+
521
+ # Resolve batch sizes for noise_sequence and spectrogram
522
+ spectrogram_batched = input_features.dim() == 3
523
+ if not spectrogram_batched:
524
+ input_features = input_features.unsqueeze(0)
525
+ spectrogram_batch_size, spectrogram_length, _ = input_features.shape
526
+
527
+ if noise_sequence is not None:
528
+ noise_sequence_batched = noise_sequence.dim() == 3
529
+ if not noise_sequence_batched:
530
+ noise_sequence = noise_sequence.unsqueeze(0)
531
+ else:
532
+ # Randomly generate noise_sequence
533
+ noise_sequence_shape = (spectrogram_batch_size, spectrogram_length, self.config.model_in_channels)
534
+ noise_sequence = torch.randn(
535
+ noise_sequence_shape, generator=generator, dtype=input_features.dtype, device=input_features.device
536
+ )
537
+ noise_sequence_batch_size = noise_sequence.shape[0]
538
+
539
+ if spectrogram_batch_size > 1 and noise_sequence_batch_size == 1:
540
+ # Repeat noise_sequence spectrogram_batch_size times
541
+ noise_sequence = noise_sequence.repeat(spectrogram_batch_size, 1, 1)
542
+ elif noise_sequence_batch_size > 1 and spectrogram_batch_size == 1:
543
+ # Repeat spectrogram noise_sequence_batch_size times
544
+ input_features = input_features.repeat(noise_sequence_batch_size, 1, 1)
545
+
546
+ if noise_sequence_batch_size != spectrogram_batch_size:
547
+ raise ValueError(
548
+ f"The batch size of `noise_sequence` is {noise_sequence_batch_size} and the batch size of"
549
+ f" `input_features` is {spectrogram_batch_size}, but the two are expected to be equal."
550
+ )
551
+
552
+ if padding_mask is not None:
553
+ if padding_mask.dim() == 1:
554
+ padding_mask = padding_mask.unsqueeze(0)
555
+ padding_mask_batch_size = padding_mask.shape[0]
556
+ if padding_mask_batch_size != spectrogram_batch_size:
557
+ raise ValueError(
558
+ f"The batch size of `padding_mask` is {padding_mask_batch_size} and the batch size of"
559
+ f" `input_features` is {spectrogram_batch_size}, but the two are expected to be equal."
560
+ )
561
+
562
+ # Change shapes to have channels before sequence lengths
563
+ hidden_states = noise_sequence.transpose(2, 1)
564
+ input_features = input_features.transpose(2, 1)
565
+
566
+ hidden_states = self.conv_pre(hidden_states)
567
+
568
+ for resblock in self.resblocks:
569
+ hidden_states = resblock(hidden_states, input_features)
570
+
571
+ hidden_states = nn.functional.leaky_relu(hidden_states, self.leaky_relu_slope)
572
+ hidden_states = self.conv_post(hidden_states)
573
+ hidden_states = torch.tanh(hidden_states)
574
+
575
+ # Remove sequence length dimension since this collapses to 1
576
+ # NOTE: keep waveforms batched even if there's only one
577
+ waveform = hidden_states.squeeze(1)
578
+
579
+ # Get sequence lengths for UnivNetFeatureExtractor.batch_decode.
580
+ waveform_lengths = None
581
+ if padding_mask is not None:
582
+ # Padding is always contiguous and added on the right
583
+ waveform_lengths = torch.sum(padding_mask, dim=1)
584
+
585
+ if not return_dict:
586
+ outputs = (waveform, waveform_lengths)
587
+ return outputs
588
+
589
+ return UnivNetModelOutput(
590
+ waveforms=waveform,
591
+ waveform_lengths=waveform_lengths,
592
+ )
593
+
594
+ def _init_weights(self, module):
595
+ """Initialize the weights."""
596
+ if isinstance(module, (nn.Linear, nn.Conv1d, nn.ConvTranspose1d)):
597
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
598
+ if module.bias is not None:
599
+ module.bias.data.zero_()
600
+
601
+ def apply_weight_norm(self):
602
+ weight_norm = nn.utils.weight_norm
603
+ if hasattr(nn.utils.parametrizations, "weight_norm"):
604
+ weight_norm = nn.utils.parametrizations.weight_norm
605
+
606
+ weight_norm(self.conv_pre)
607
+ for layer in self.resblocks:
608
+ layer.apply_weight_norm()
609
+ weight_norm(self.conv_post)
610
+
611
+ def remove_weight_norm(self):
612
+ nn.utils.remove_weight_norm(self.conv_pre)
613
+ for layer in self.resblocks:
614
+ layer.remove_weight_norm()
615
+ nn.utils.remove_weight_norm(self.conv_post)
616
+
617
+
618
+ __all__ = ["UnivNetModel"]
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/upernet/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. 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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_upernet import *
22
+ from .modeling_upernet import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/upernet/configuration_upernet.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team. 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
+ """UperNet model configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+ from ...utils import logging
19
+ from ...utils.backbone_utils import verify_backbone_config_arguments
20
+ from ..auto.configuration_auto import CONFIG_MAPPING
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+
26
+ class UperNetConfig(PretrainedConfig):
27
+ r"""
28
+ This is the configuration class to store the configuration of an [`UperNetForSemanticSegmentation`]. It is used to
29
+ instantiate an UperNet model according to the specified arguments, defining the model architecture. Instantiating a
30
+ configuration with the defaults will yield a similar configuration to that of the UperNet
31
+ [openmmlab/upernet-convnext-tiny](https://huggingface.co/openmmlab/upernet-convnext-tiny) architecture.
32
+
33
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
34
+ documentation from [`PretrainedConfig`] for more information.
35
+
36
+ Args:
37
+ backbone_config (`PretrainedConfig` or `dict`, *optional*, defaults to `ResNetConfig()`):
38
+ The configuration of the backbone model.
39
+ backbone (`str`, *optional*):
40
+ Name of backbone to use when `backbone_config` is `None`. If `use_pretrained_backbone` is `True`, this
41
+ will load the corresponding pretrained weights from the timm or transformers library. If `use_pretrained_backbone`
42
+ is `False`, this loads the backbone's config and uses that to initialize the backbone with random weights.
43
+ use_pretrained_backbone (`bool`, *optional*, `False`):
44
+ Whether to use pretrained weights for the backbone.
45
+ use_timm_backbone (`bool`, *optional*, `False`):
46
+ Whether to load `backbone` from the timm library. If `False`, the backbone is loaded from the transformers
47
+ library.
48
+ backbone_kwargs (`dict`, *optional*):
49
+ Keyword arguments to be passed to AutoBackbone when loading from a checkpoint
50
+ e.g. `{'out_indices': (0, 1, 2, 3)}`. Cannot be specified if `backbone_config` is set.
51
+ hidden_size (`int`, *optional*, defaults to 512):
52
+ The number of hidden units in the convolutional layers.
53
+ initializer_range (`float`, *optional*, defaults to 0.02):
54
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
55
+ pool_scales (`tuple[int]`, *optional*, defaults to `[1, 2, 3, 6]`):
56
+ Pooling scales used in Pooling Pyramid Module applied on the last feature map.
57
+ use_auxiliary_head (`bool`, *optional*, defaults to `True`):
58
+ Whether to use an auxiliary head during training.
59
+ auxiliary_loss_weight (`float`, *optional*, defaults to 0.4):
60
+ Weight of the cross-entropy loss of the auxiliary head.
61
+ auxiliary_channels (`int`, *optional*, defaults to 256):
62
+ Number of channels to use in the auxiliary head.
63
+ auxiliary_num_convs (`int`, *optional*, defaults to 1):
64
+ Number of convolutional layers to use in the auxiliary head.
65
+ auxiliary_concat_input (`bool`, *optional*, defaults to `False`):
66
+ Whether to concatenate the output of the auxiliary head with the input before the classification layer.
67
+ loss_ignore_index (`int`, *optional*, defaults to 255):
68
+ The index that is ignored by the loss function.
69
+
70
+ Examples:
71
+
72
+ ```python
73
+ >>> from transformers import UperNetConfig, UperNetForSemanticSegmentation
74
+
75
+ >>> # Initializing a configuration
76
+ >>> configuration = UperNetConfig()
77
+
78
+ >>> # Initializing a model (with random weights) from the configuration
79
+ >>> model = UperNetForSemanticSegmentation(configuration)
80
+
81
+ >>> # Accessing the model configuration
82
+ >>> configuration = model.config
83
+ ```"""
84
+
85
+ model_type = "upernet"
86
+
87
+ def __init__(
88
+ self,
89
+ backbone_config=None,
90
+ backbone=None,
91
+ use_pretrained_backbone=False,
92
+ use_timm_backbone=False,
93
+ backbone_kwargs=None,
94
+ hidden_size=512,
95
+ initializer_range=0.02,
96
+ pool_scales=[1, 2, 3, 6],
97
+ use_auxiliary_head=True,
98
+ auxiliary_loss_weight=0.4,
99
+ auxiliary_in_channels=None,
100
+ auxiliary_channels=256,
101
+ auxiliary_num_convs=1,
102
+ auxiliary_concat_input=False,
103
+ loss_ignore_index=255,
104
+ **kwargs,
105
+ ):
106
+ super().__init__(**kwargs)
107
+ if backbone_config is None and backbone is None:
108
+ logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.")
109
+ backbone_config = CONFIG_MAPPING["resnet"](out_features=["stage1", "stage2", "stage3", "stage4"])
110
+ elif isinstance(backbone_config, dict):
111
+ backbone_model_type = backbone_config.get("model_type")
112
+ config_class = CONFIG_MAPPING[backbone_model_type]
113
+ backbone_config = config_class.from_dict(backbone_config)
114
+
115
+ verify_backbone_config_arguments(
116
+ use_timm_backbone=use_timm_backbone,
117
+ use_pretrained_backbone=use_pretrained_backbone,
118
+ backbone=backbone,
119
+ backbone_config=backbone_config,
120
+ backbone_kwargs=backbone_kwargs,
121
+ )
122
+
123
+ self.backbone_config = backbone_config
124
+ self.backbone = backbone
125
+ self.use_pretrained_backbone = use_pretrained_backbone
126
+ self.use_timm_backbone = use_timm_backbone
127
+ self.backbone_kwargs = backbone_kwargs
128
+ self.hidden_size = hidden_size
129
+ self.initializer_range = initializer_range
130
+ self.pool_scales = pool_scales
131
+ self.use_auxiliary_head = use_auxiliary_head
132
+ self.auxiliary_loss_weight = auxiliary_loss_weight
133
+ self.auxiliary_in_channels = auxiliary_in_channels
134
+ self.auxiliary_channels = auxiliary_channels
135
+ self.auxiliary_num_convs = auxiliary_num_convs
136
+ self.auxiliary_concat_input = auxiliary_concat_input
137
+ self.loss_ignore_index = loss_ignore_index
138
+
139
+ @property
140
+ def sub_configs(self):
141
+ return (
142
+ {"backbone_config": type(self.backbone_config)}
143
+ if getattr(self, "backbone_config", None) is not None
144
+ else {}
145
+ )
146
+
147
+
148
+ __all__ = ["UperNetConfig"]
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/upernet/convert_convnext_upernet_to_pytorch.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team.
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
+ """Convert ConvNext + UperNet checkpoints from mmsegmentation."""
16
+
17
+ import argparse
18
+ import json
19
+
20
+ import requests
21
+ import torch
22
+ from huggingface_hub import hf_hub_download
23
+ from PIL import Image
24
+
25
+ from transformers import ConvNextConfig, SegformerImageProcessor, UperNetConfig, UperNetForSemanticSegmentation
26
+
27
+
28
+ def get_upernet_config(model_name):
29
+ auxiliary_in_channels = 384
30
+ if "tiny" in model_name:
31
+ depths = [3, 3, 9, 3]
32
+ hidden_sizes = [96, 192, 384, 768]
33
+ if "small" in model_name:
34
+ depths = [3, 3, 27, 3]
35
+ hidden_sizes = [96, 192, 384, 768]
36
+ if "base" in model_name:
37
+ depths = [3, 3, 27, 3]
38
+ hidden_sizes = [128, 256, 512, 1024]
39
+ auxiliary_in_channels = 512
40
+ if "large" in model_name:
41
+ depths = [3, 3, 27, 3]
42
+ hidden_sizes = [192, 384, 768, 1536]
43
+ auxiliary_in_channels = 768
44
+ if "xlarge" in model_name:
45
+ depths = [3, 3, 27, 3]
46
+ hidden_sizes = [256, 512, 1024, 2048]
47
+ auxiliary_in_channels = 1024
48
+
49
+ # set label information
50
+ num_labels = 150
51
+ repo_id = "huggingface/label-files"
52
+ filename = "ade20k-id2label.json"
53
+ id2label = json.load(open(hf_hub_download(repo_id, filename, repo_type="dataset"), "r"))
54
+ id2label = {int(k): v for k, v in id2label.items()}
55
+ label2id = {v: k for k, v in id2label.items()}
56
+
57
+ backbone_config = ConvNextConfig(
58
+ depths=depths, hidden_sizes=hidden_sizes, out_features=["stage1", "stage2", "stage3", "stage4"]
59
+ )
60
+ config = UperNetConfig(
61
+ backbone_config=backbone_config,
62
+ auxiliary_in_channels=auxiliary_in_channels,
63
+ num_labels=num_labels,
64
+ id2label=id2label,
65
+ label2id=label2id,
66
+ )
67
+
68
+ return config
69
+
70
+
71
+ # here we list all keys to be renamed (original name on the left, our name on the right)
72
+ def create_rename_keys(config):
73
+ rename_keys = []
74
+
75
+ # fmt: off
76
+ # stem
77
+ rename_keys.append(("backbone.downsample_layers.0.0.weight", "backbone.embeddings.patch_embeddings.weight"))
78
+ rename_keys.append(("backbone.downsample_layers.0.0.bias", "backbone.embeddings.patch_embeddings.bias"))
79
+ rename_keys.append(("backbone.downsample_layers.0.1.weight", "backbone.embeddings.layernorm.weight"))
80
+ rename_keys.append(("backbone.downsample_layers.0.1.bias", "backbone.embeddings.layernorm.bias"))
81
+ # stages
82
+ for i in range(len(config.backbone_config.depths)):
83
+ for j in range(config.backbone_config.depths[i]):
84
+ rename_keys.append((f"backbone.stages.{i}.{j}.gamma", f"backbone.encoder.stages.{i}.layers.{j}.layer_scale_parameter"))
85
+ rename_keys.append((f"backbone.stages.{i}.{j}.depthwise_conv.weight", f"backbone.encoder.stages.{i}.layers.{j}.dwconv.weight"))
86
+ rename_keys.append((f"backbone.stages.{i}.{j}.depthwise_conv.bias", f"backbone.encoder.stages.{i}.layers.{j}.dwconv.bias"))
87
+ rename_keys.append((f"backbone.stages.{i}.{j}.norm.weight", f"backbone.encoder.stages.{i}.layers.{j}.layernorm.weight"))
88
+ rename_keys.append((f"backbone.stages.{i}.{j}.norm.bias", f"backbone.encoder.stages.{i}.layers.{j}.layernorm.bias"))
89
+ rename_keys.append((f"backbone.stages.{i}.{j}.pointwise_conv1.weight", f"backbone.encoder.stages.{i}.layers.{j}.pwconv1.weight"))
90
+ rename_keys.append((f"backbone.stages.{i}.{j}.pointwise_conv1.bias", f"backbone.encoder.stages.{i}.layers.{j}.pwconv1.bias"))
91
+ rename_keys.append((f"backbone.stages.{i}.{j}.pointwise_conv2.weight", f"backbone.encoder.stages.{i}.layers.{j}.pwconv2.weight"))
92
+ rename_keys.append((f"backbone.stages.{i}.{j}.pointwise_conv2.bias", f"backbone.encoder.stages.{i}.layers.{j}.pwconv2.bias"))
93
+ if i > 0:
94
+ rename_keys.append((f"backbone.downsample_layers.{i}.0.weight", f"backbone.encoder.stages.{i}.downsampling_layer.0.weight"))
95
+ rename_keys.append((f"backbone.downsample_layers.{i}.0.bias", f"backbone.encoder.stages.{i}.downsampling_layer.0.bias"))
96
+ rename_keys.append((f"backbone.downsample_layers.{i}.1.weight", f"backbone.encoder.stages.{i}.downsampling_layer.1.weight"))
97
+ rename_keys.append((f"backbone.downsample_layers.{i}.1.bias", f"backbone.encoder.stages.{i}.downsampling_layer.1.bias"))
98
+
99
+ rename_keys.append((f"backbone.norm{i}.weight", f"backbone.hidden_states_norms.stage{i+1}.weight"))
100
+ rename_keys.append((f"backbone.norm{i}.bias", f"backbone.hidden_states_norms.stage{i+1}.bias"))
101
+
102
+ # decode head
103
+ rename_keys.extend(
104
+ [
105
+ ("decode_head.conv_seg.weight", "decode_head.classifier.weight"),
106
+ ("decode_head.conv_seg.bias", "decode_head.classifier.bias"),
107
+ ("auxiliary_head.conv_seg.weight", "auxiliary_head.classifier.weight"),
108
+ ("auxiliary_head.conv_seg.bias", "auxiliary_head.classifier.bias"),
109
+ ]
110
+ )
111
+ # fmt: on
112
+
113
+ return rename_keys
114
+
115
+
116
+ def rename_key(dct, old, new):
117
+ val = dct.pop(old)
118
+ dct[new] = val
119
+
120
+
121
+ def convert_upernet_checkpoint(model_name, pytorch_dump_folder_path, push_to_hub):
122
+ model_name_to_url = {
123
+ "upernet-convnext-tiny": "https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_tiny_fp16_512x512_160k_ade20k/upernet_convnext_tiny_fp16_512x512_160k_ade20k_20220227_124553-cad485de.pth",
124
+ "upernet-convnext-small": "https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_small_fp16_512x512_160k_ade20k/upernet_convnext_small_fp16_512x512_160k_ade20k_20220227_131208-1b1e394f.pth",
125
+ "upernet-convnext-base": "https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_base_fp16_512x512_160k_ade20k/upernet_convnext_base_fp16_512x512_160k_ade20k_20220227_181227-02a24fc6.pth",
126
+ "upernet-convnext-large": "https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_large_fp16_640x640_160k_ade20k/upernet_convnext_large_fp16_640x640_160k_ade20k_20220226_040532-e57aa54d.pth",
127
+ "upernet-convnext-xlarge": "https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_xlarge_fp16_640x640_160k_ade20k/upernet_convnext_xlarge_fp16_640x640_160k_ade20k_20220226_080344-95fc38c2.pth",
128
+ }
129
+ checkpoint_url = model_name_to_url[model_name]
130
+ state_dict = torch.hub.load_state_dict_from_url(checkpoint_url, map_location="cpu")["state_dict"]
131
+
132
+ config = get_upernet_config(model_name)
133
+ model = UperNetForSemanticSegmentation(config)
134
+ model.eval()
135
+
136
+ # replace "bn" => "batch_norm"
137
+ for key in state_dict.copy():
138
+ val = state_dict.pop(key)
139
+ if "bn" in key:
140
+ key = key.replace("bn", "batch_norm")
141
+ state_dict[key] = val
142
+
143
+ # rename keys
144
+ rename_keys = create_rename_keys(config)
145
+ for src, dest in rename_keys:
146
+ rename_key(state_dict, src, dest)
147
+
148
+ model.load_state_dict(state_dict)
149
+
150
+ # verify on image
151
+ url = "https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg"
152
+ image = Image.open(requests.get(url, stream=True).raw).convert("RGB")
153
+
154
+ processor = SegformerImageProcessor()
155
+ pixel_values = processor(image, return_tensors="pt").pixel_values
156
+
157
+ with torch.no_grad():
158
+ outputs = model(pixel_values)
159
+
160
+ if model_name == "upernet-convnext-tiny":
161
+ expected_slice = torch.tensor(
162
+ [[-8.8110, -8.8110, -8.6521], [-8.8110, -8.8110, -8.6521], [-8.7746, -8.7746, -8.6130]]
163
+ )
164
+ elif model_name == "upernet-convnext-small":
165
+ expected_slice = torch.tensor(
166
+ [[-8.8236, -8.8236, -8.6771], [-8.8236, -8.8236, -8.6771], [-8.7638, -8.7638, -8.6240]]
167
+ )
168
+ elif model_name == "upernet-convnext-base":
169
+ expected_slice = torch.tensor(
170
+ [[-8.8558, -8.8558, -8.6905], [-8.8558, -8.8558, -8.6905], [-8.7669, -8.7669, -8.6021]]
171
+ )
172
+ elif model_name == "upernet-convnext-large":
173
+ expected_slice = torch.tensor(
174
+ [[-8.6660, -8.6660, -8.6210], [-8.6660, -8.6660, -8.6210], [-8.6310, -8.6310, -8.5964]]
175
+ )
176
+ elif model_name == "upernet-convnext-xlarge":
177
+ expected_slice = torch.tensor(
178
+ [[-8.4980, -8.4980, -8.3977], [-8.4980, -8.4980, -8.3977], [-8.4379, -8.4379, -8.3412]]
179
+ )
180
+ print("Logits:", outputs.logits[0, 0, :3, :3])
181
+ assert torch.allclose(outputs.logits[0, 0, :3, :3], expected_slice, atol=1e-4)
182
+ print("Looks ok!")
183
+
184
+ if pytorch_dump_folder_path is not None:
185
+ print(f"Saving model {model_name} to {pytorch_dump_folder_path}")
186
+ model.save_pretrained(pytorch_dump_folder_path)
187
+ print(f"Saving processor to {pytorch_dump_folder_path}")
188
+ processor.save_pretrained(pytorch_dump_folder_path)
189
+
190
+ if push_to_hub:
191
+ print(f"Pushing model and processor for {model_name} to hub")
192
+ model.push_to_hub(f"openmmlab/{model_name}")
193
+ processor.push_to_hub(f"openmmlab/{model_name}")
194
+
195
+
196
+ if __name__ == "__main__":
197
+ parser = argparse.ArgumentParser()
198
+ # Required parameters
199
+ parser.add_argument(
200
+ "--model_name",
201
+ default="upernet-convnext-tiny",
202
+ type=str,
203
+ choices=[f"upernet-convnext-{size}" for size in ["tiny", "small", "base", "large", "xlarge"]],
204
+ help="Name of the ConvNext UperNet model you'd like to convert.",
205
+ )
206
+ parser.add_argument(
207
+ "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory."
208
+ )
209
+ parser.add_argument(
210
+ "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub."
211
+ )
212
+
213
+ args = parser.parse_args()
214
+ convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/upernet/convert_swin_upernet_to_pytorch.py ADDED
@@ -0,0 +1,297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team.
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
+ """Convert Swin Transformer + UperNet checkpoints from mmsegmentation.
16
+
17
+ URL: https://github.com/open-mmlab/mmsegmentation/tree/master/configs/swin
18
+ """
19
+
20
+ import argparse
21
+ import json
22
+
23
+ import requests
24
+ import torch
25
+ from huggingface_hub import hf_hub_download
26
+ from PIL import Image
27
+
28
+ from transformers import SegformerImageProcessor, SwinConfig, UperNetConfig, UperNetForSemanticSegmentation
29
+
30
+
31
+ def get_upernet_config(model_name):
32
+ auxiliary_in_channels = 384
33
+ window_size = 7
34
+ if "tiny" in model_name:
35
+ embed_dim = 96
36
+ depths = (2, 2, 6, 2)
37
+ num_heads = (3, 6, 12, 24)
38
+ elif "small" in model_name:
39
+ embed_dim = 96
40
+ depths = (2, 2, 18, 2)
41
+ num_heads = (3, 6, 12, 24)
42
+ elif "base" in model_name:
43
+ embed_dim = 128
44
+ depths = (2, 2, 18, 2)
45
+ num_heads = (4, 8, 16, 32)
46
+ window_size = 12
47
+ auxiliary_in_channels = 512
48
+ elif "large" in model_name:
49
+ embed_dim = 192
50
+ depths = (2, 2, 18, 2)
51
+ num_heads = (6, 12, 24, 48)
52
+ window_size = 12
53
+ auxiliary_in_channels = 768
54
+
55
+ # set label information
56
+ num_labels = 150
57
+ repo_id = "huggingface/label-files"
58
+ filename = "ade20k-id2label.json"
59
+ id2label = json.load(open(hf_hub_download(repo_id, filename, repo_type="dataset"), "r"))
60
+ id2label = {int(k): v for k, v in id2label.items()}
61
+ label2id = {v: k for k, v in id2label.items()}
62
+
63
+ backbone_config = SwinConfig(
64
+ embed_dim=embed_dim,
65
+ depths=depths,
66
+ num_heads=num_heads,
67
+ window_size=window_size,
68
+ out_features=["stage1", "stage2", "stage3", "stage4"],
69
+ )
70
+ config = UperNetConfig(
71
+ backbone_config=backbone_config,
72
+ auxiliary_in_channels=auxiliary_in_channels,
73
+ num_labels=num_labels,
74
+ id2label=id2label,
75
+ label2id=label2id,
76
+ )
77
+
78
+ return config
79
+
80
+
81
+ # here we list all keys to be renamed (original name on the left, our name on the right)
82
+ def create_rename_keys(config):
83
+ rename_keys = []
84
+
85
+ # fmt: off
86
+ # stem
87
+ rename_keys.append(("backbone.patch_embed.projection.weight", "backbone.embeddings.patch_embeddings.projection.weight"))
88
+ rename_keys.append(("backbone.patch_embed.projection.bias", "backbone.embeddings.patch_embeddings.projection.bias"))
89
+ rename_keys.append(("backbone.patch_embed.norm.weight", "backbone.embeddings.norm.weight"))
90
+ rename_keys.append(("backbone.patch_embed.norm.bias", "backbone.embeddings.norm.bias"))
91
+ # stages
92
+ for i in range(len(config.backbone_config.depths)):
93
+ for j in range(config.backbone_config.depths[i]):
94
+ rename_keys.append((f"backbone.stages.{i}.blocks.{j}.norm1.weight", f"backbone.encoder.layers.{i}.blocks.{j}.layernorm_before.weight"))
95
+ rename_keys.append((f"backbone.stages.{i}.blocks.{j}.norm1.bias", f"backbone.encoder.layers.{i}.blocks.{j}.layernorm_before.bias"))
96
+ rename_keys.append((f"backbone.stages.{i}.blocks.{j}.attn.w_msa.relative_position_bias_table", f"backbone.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table"))
97
+ rename_keys.append((f"backbone.stages.{i}.blocks.{j}.attn.w_msa.relative_position_index", f"backbone.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index"))
98
+ rename_keys.append((f"backbone.stages.{i}.blocks.{j}.attn.w_msa.proj.weight", f"backbone.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight"))
99
+ rename_keys.append((f"backbone.stages.{i}.blocks.{j}.attn.w_msa.proj.bias", f"backbone.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias"))
100
+ rename_keys.append((f"backbone.stages.{i}.blocks.{j}.norm2.weight", f"backbone.encoder.layers.{i}.blocks.{j}.layernorm_after.weight"))
101
+ rename_keys.append((f"backbone.stages.{i}.blocks.{j}.norm2.bias", f"backbone.encoder.layers.{i}.blocks.{j}.layernorm_after.bias"))
102
+ rename_keys.append((f"backbone.stages.{i}.blocks.{j}.ffn.layers.0.0.weight", f"backbone.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight"))
103
+ rename_keys.append((f"backbone.stages.{i}.blocks.{j}.ffn.layers.0.0.bias", f"backbone.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias"))
104
+ rename_keys.append((f"backbone.stages.{i}.blocks.{j}.ffn.layers.1.weight", f"backbone.encoder.layers.{i}.blocks.{j}.output.dense.weight"))
105
+ rename_keys.append((f"backbone.stages.{i}.blocks.{j}.ffn.layers.1.bias", f"backbone.encoder.layers.{i}.blocks.{j}.output.dense.bias"))
106
+
107
+ if i < 3:
108
+ rename_keys.append((f"backbone.stages.{i}.downsample.reduction.weight", f"backbone.encoder.layers.{i}.downsample.reduction.weight"))
109
+ rename_keys.append((f"backbone.stages.{i}.downsample.norm.weight", f"backbone.encoder.layers.{i}.downsample.norm.weight"))
110
+ rename_keys.append((f"backbone.stages.{i}.downsample.norm.bias", f"backbone.encoder.layers.{i}.downsample.norm.bias"))
111
+ rename_keys.append((f"backbone.norm{i}.weight", f"backbone.hidden_states_norms.stage{i+1}.weight"))
112
+ rename_keys.append((f"backbone.norm{i}.bias", f"backbone.hidden_states_norms.stage{i+1}.bias"))
113
+
114
+ # decode head
115
+ rename_keys.extend(
116
+ [
117
+ ("decode_head.conv_seg.weight", "decode_head.classifier.weight"),
118
+ ("decode_head.conv_seg.bias", "decode_head.classifier.bias"),
119
+ ("auxiliary_head.conv_seg.weight", "auxiliary_head.classifier.weight"),
120
+ ("auxiliary_head.conv_seg.bias", "auxiliary_head.classifier.bias"),
121
+ ]
122
+ )
123
+ # fmt: on
124
+
125
+ return rename_keys
126
+
127
+
128
+ def rename_key(dct, old, new):
129
+ val = dct.pop(old)
130
+ dct[new] = val
131
+
132
+
133
+ # we split up the matrix of each encoder layer into queries, keys and values
134
+ def read_in_q_k_v(state_dict, backbone_config):
135
+ num_features = [int(backbone_config.embed_dim * 2**i) for i in range(len(backbone_config.depths))]
136
+ for i in range(len(backbone_config.depths)):
137
+ dim = num_features[i]
138
+ for j in range(backbone_config.depths[i]):
139
+ # fmt: off
140
+ # read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias)
141
+ in_proj_weight = state_dict.pop(f"backbone.stages.{i}.blocks.{j}.attn.w_msa.qkv.weight")
142
+ in_proj_bias = state_dict.pop(f"backbone.stages.{i}.blocks.{j}.attn.w_msa.qkv.bias")
143
+ # next, add query, keys and values (in that order) to the state dict
144
+ state_dict[f"backbone.encoder.layers.{i}.blocks.{j}.attention.self.query.weight"] = in_proj_weight[:dim, :]
145
+ state_dict[f"backbone.encoder.layers.{i}.blocks.{j}.attention.self.query.bias"] = in_proj_bias[: dim]
146
+ state_dict[f"backbone.encoder.layers.{i}.blocks.{j}.attention.self.key.weight"] = in_proj_weight[
147
+ dim : dim * 2, :
148
+ ]
149
+ state_dict[f"backbone.encoder.layers.{i}.blocks.{j}.attention.self.key.bias"] = in_proj_bias[
150
+ dim : dim * 2
151
+ ]
152
+ state_dict[f"backbone.encoder.layers.{i}.blocks.{j}.attention.self.value.weight"] = in_proj_weight[
153
+ -dim :, :
154
+ ]
155
+ state_dict[f"backbone.encoder.layers.{i}.blocks.{j}.attention.self.value.bias"] = in_proj_bias[-dim :]
156
+ # fmt: on
157
+
158
+
159
+ def correct_unfold_reduction_order(x):
160
+ out_channel, in_channel = x.shape
161
+ x = x.reshape(out_channel, 4, in_channel // 4)
162
+ x = x[:, [0, 2, 1, 3], :].transpose(1, 2).reshape(out_channel, in_channel)
163
+ return x
164
+
165
+
166
+ def reverse_correct_unfold_reduction_order(x):
167
+ out_channel, in_channel = x.shape
168
+ x = x.reshape(out_channel, in_channel // 4, 4)
169
+ x = x[:, :, [0, 2, 1, 3]].transpose(1, 2).reshape(out_channel, in_channel)
170
+
171
+ return x
172
+
173
+
174
+ def correct_unfold_norm_order(x):
175
+ in_channel = x.shape[0]
176
+ x = x.reshape(4, in_channel // 4)
177
+ x = x[[0, 2, 1, 3], :].transpose(0, 1).reshape(in_channel)
178
+ return x
179
+
180
+
181
+ # there was an incompatibility with this version, due to a new implementation of their downsampling operation using nn.Unfold.
182
+ # was resolved as seen here:
183
+ # https://github.com/open-mmlab/mmdetection/blob/31c84958f54287a8be2b99cbf87a6dcf12e57753/mmdet/models/utils/ckpt_convert.py#L96.
184
+ def reverse_correct_unfold_norm_order(x):
185
+ in_channel = x.shape[0]
186
+ x = x.reshape(in_channel // 4, 4)
187
+ x = x[:, [0, 2, 1, 3]].transpose(0, 1).reshape(in_channel)
188
+ return x
189
+
190
+
191
+ def convert_upernet_checkpoint(model_name, pytorch_dump_folder_path, push_to_hub):
192
+ model_name_to_url = {
193
+ "upernet-swin-tiny": "https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_tiny_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K/upernet_swin_tiny_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K_20210531_112542-e380ad3e.pth",
194
+ "upernet-swin-small": "https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_small_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K/upernet_swin_small_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K_20210526_192015-ee2fff1c.pth",
195
+ "upernet-swin-base": "https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_base_patch4_window12_512x512_160k_ade20k_pretrain_384x384_22K/upernet_swin_base_patch4_window12_512x512_160k_ade20k_pretrain_384x384_22K_20210531_125459-429057bf.pth",
196
+ "upernet-swin-large": "https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_large_patch4_window12_512x512_pretrain_384x384_22K_160k_ade20k/upernet_swin_large_patch4_window12_512x512_pretrain_384x384_22K_160k_ade20k_20220318_091743-9ba68901.pth",
197
+ }
198
+ checkpoint_url = model_name_to_url[model_name]
199
+ state_dict = torch.hub.load_state_dict_from_url(checkpoint_url, map_location="cpu", file_name=model_name)[
200
+ "state_dict"
201
+ ]
202
+
203
+ for name, param in state_dict.items():
204
+ print(name, param.shape)
205
+
206
+ config = get_upernet_config(model_name)
207
+ model = UperNetForSemanticSegmentation(config)
208
+ model.eval()
209
+
210
+ # replace "bn" => "batch_norm"
211
+ for key in state_dict.copy():
212
+ val = state_dict.pop(key)
213
+ if "bn" in key:
214
+ key = key.replace("bn", "batch_norm")
215
+ state_dict[key] = val
216
+
217
+ # rename keys
218
+ rename_keys = create_rename_keys(config)
219
+ for src, dest in rename_keys:
220
+ rename_key(state_dict, src, dest)
221
+ read_in_q_k_v(state_dict, config.backbone_config)
222
+
223
+ # fix downsample parameters
224
+ for key, value in state_dict.items():
225
+ if "downsample" in key:
226
+ if "reduction" in key:
227
+ state_dict[key] = reverse_correct_unfold_reduction_order(value)
228
+ if "norm" in key:
229
+ state_dict[key] = reverse_correct_unfold_norm_order(value)
230
+
231
+ model.load_state_dict(state_dict)
232
+
233
+ # verify on image
234
+ url = "https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg"
235
+ image = Image.open(requests.get(url, stream=True).raw).convert("RGB")
236
+
237
+ processor = SegformerImageProcessor()
238
+ pixel_values = processor(image, return_tensors="pt").pixel_values
239
+
240
+ with torch.no_grad():
241
+ outputs = model(pixel_values)
242
+ logits = outputs.logits
243
+
244
+ print(logits.shape)
245
+ print("First values of logits:", logits[0, 0, :3, :3])
246
+ # assert values
247
+ if model_name == "upernet-swin-tiny":
248
+ expected_slice = torch.tensor(
249
+ [[-7.5958, -7.5958, -7.4302], [-7.5958, -7.5958, -7.4302], [-7.4797, -7.4797, -7.3068]]
250
+ )
251
+ elif model_name == "upernet-swin-small":
252
+ expected_slice = torch.tensor(
253
+ [[-7.1921, -7.1921, -6.9532], [-7.1921, -7.1921, -6.9532], [-7.0908, -7.0908, -6.8534]]
254
+ )
255
+ elif model_name == "upernet-swin-base":
256
+ expected_slice = torch.tensor(
257
+ [[-6.5851, -6.5851, -6.4330], [-6.5851, -6.5851, -6.4330], [-6.4763, -6.4763, -6.3254]]
258
+ )
259
+ elif model_name == "upernet-swin-large":
260
+ expected_slice = torch.tensor(
261
+ [[-7.5297, -7.5297, -7.3802], [-7.5297, -7.5297, -7.3802], [-7.4044, -7.4044, -7.2586]]
262
+ )
263
+ print("Logits:", outputs.logits[0, 0, :3, :3])
264
+ assert torch.allclose(outputs.logits[0, 0, :3, :3], expected_slice, atol=1e-4)
265
+ print("Looks ok!")
266
+
267
+ if pytorch_dump_folder_path is not None:
268
+ print(f"Saving model {model_name} to {pytorch_dump_folder_path}")
269
+ model.save_pretrained(pytorch_dump_folder_path)
270
+ print(f"Saving processor to {pytorch_dump_folder_path}")
271
+ processor.save_pretrained(pytorch_dump_folder_path)
272
+
273
+ if push_to_hub:
274
+ print(f"Pushing model and processor for {model_name} to hub")
275
+ model.push_to_hub(f"openmmlab/{model_name}")
276
+ processor.push_to_hub(f"openmmlab/{model_name}")
277
+
278
+
279
+ if __name__ == "__main__":
280
+ parser = argparse.ArgumentParser()
281
+ # Required parameters
282
+ parser.add_argument(
283
+ "--model_name",
284
+ default="upernet-swin-tiny",
285
+ type=str,
286
+ choices=[f"upernet-swin-{size}" for size in ["tiny", "small", "base", "large"]],
287
+ help="Name of the Swin + UperNet model you'd like to convert.",
288
+ )
289
+ parser.add_argument(
290
+ "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory."
291
+ )
292
+ parser.add_argument(
293
+ "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub."
294
+ )
295
+
296
+ args = parser.parse_args()
297
+ convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/upernet/modeling_upernet.py ADDED
@@ -0,0 +1,388 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team. 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
+ """PyTorch UperNet model. Based on OpenMMLab's implementation, found in https://github.com/open-mmlab/mmsegmentation."""
16
+
17
+ from typing import Optional, Union
18
+
19
+ import torch
20
+ from torch import nn
21
+ from torch.nn import CrossEntropyLoss
22
+
23
+ from ...modeling_outputs import SemanticSegmenterOutput
24
+ from ...modeling_utils import PreTrainedModel
25
+ from ...utils import auto_docstring
26
+ from ...utils.backbone_utils import load_backbone
27
+ from .configuration_upernet import UperNetConfig
28
+
29
+
30
+ class UperNetConvModule(nn.Module):
31
+ """
32
+ A convolutional block that bundles conv/norm/activation layers. This block simplifies the usage of convolution
33
+ layers, which are commonly used with a norm layer (e.g., BatchNorm) and activation layer (e.g., ReLU).
34
+ """
35
+
36
+ def __init__(
37
+ self,
38
+ in_channels: int,
39
+ out_channels: int,
40
+ kernel_size: Union[int, tuple[int, int]],
41
+ padding: Union[int, tuple[int, int], str] = 0,
42
+ bias: bool = False,
43
+ dilation: Union[int, tuple[int, int]] = 1,
44
+ ) -> None:
45
+ super().__init__()
46
+ self.conv = nn.Conv2d(
47
+ in_channels=in_channels,
48
+ out_channels=out_channels,
49
+ kernel_size=kernel_size,
50
+ padding=padding,
51
+ bias=bias,
52
+ dilation=dilation,
53
+ )
54
+ self.batch_norm = nn.BatchNorm2d(out_channels)
55
+ self.activation = nn.ReLU()
56
+
57
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
58
+ output = self.conv(input)
59
+ output = self.batch_norm(output)
60
+ output = self.activation(output)
61
+
62
+ return output
63
+
64
+
65
+ class UperNetPyramidPoolingBlock(nn.Module):
66
+ def __init__(self, pool_scale: int, in_channels: int, channels: int) -> None:
67
+ super().__init__()
68
+ self.layers = [
69
+ nn.AdaptiveAvgPool2d(pool_scale),
70
+ UperNetConvModule(in_channels, channels, kernel_size=1),
71
+ ]
72
+ for i, layer in enumerate(self.layers):
73
+ self.add_module(str(i), layer)
74
+
75
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
76
+ hidden_state = input
77
+ for layer in self.layers:
78
+ hidden_state = layer(hidden_state)
79
+ return hidden_state
80
+
81
+
82
+ class UperNetPyramidPoolingModule(nn.Module):
83
+ """
84
+ Pyramid Pooling Module (PPM) used in PSPNet.
85
+
86
+ Args:
87
+ pool_scales (`tuple[int]`):
88
+ Pooling scales used in Pooling Pyramid Module.
89
+ in_channels (`int`):
90
+ Input channels.
91
+ channels (`int`):
92
+ Channels after modules, before conv_seg.
93
+ align_corners (`bool`):
94
+ align_corners argument of F.interpolate.
95
+ """
96
+
97
+ def __init__(self, pool_scales: tuple[int, ...], in_channels: int, channels: int, align_corners: bool) -> None:
98
+ super().__init__()
99
+ self.pool_scales = pool_scales
100
+ self.align_corners = align_corners
101
+ self.in_channels = in_channels
102
+ self.channels = channels
103
+ self.blocks = []
104
+ for i, pool_scale in enumerate(pool_scales):
105
+ block = UperNetPyramidPoolingBlock(pool_scale=pool_scale, in_channels=in_channels, channels=channels)
106
+ self.blocks.append(block)
107
+ self.add_module(str(i), block)
108
+
109
+ def forward(self, x: torch.Tensor) -> list[torch.Tensor]:
110
+ ppm_outs = []
111
+ for ppm in self.blocks:
112
+ ppm_out = ppm(x)
113
+ upsampled_ppm_out = nn.functional.interpolate(
114
+ ppm_out, size=x.size()[2:], mode="bilinear", align_corners=self.align_corners
115
+ )
116
+ ppm_outs.append(upsampled_ppm_out)
117
+ return ppm_outs
118
+
119
+
120
+ class UperNetHead(nn.Module):
121
+ """
122
+ Unified Perceptual Parsing for Scene Understanding. This head is the implementation of
123
+ [UPerNet](https://huggingface.co/papers/1807.10221).
124
+ """
125
+
126
+ def __init__(self, config, in_channels):
127
+ super().__init__()
128
+
129
+ self.config = config
130
+ self.pool_scales = config.pool_scales # e.g. (1, 2, 3, 6)
131
+ self.in_channels = in_channels
132
+ self.channels = config.hidden_size
133
+ self.align_corners = False
134
+ self.classifier = nn.Conv2d(self.channels, config.num_labels, kernel_size=1)
135
+
136
+ # PSP Module
137
+ self.psp_modules = UperNetPyramidPoolingModule(
138
+ self.pool_scales,
139
+ self.in_channels[-1],
140
+ self.channels,
141
+ align_corners=self.align_corners,
142
+ )
143
+ self.bottleneck = UperNetConvModule(
144
+ self.in_channels[-1] + len(self.pool_scales) * self.channels,
145
+ self.channels,
146
+ kernel_size=3,
147
+ padding=1,
148
+ )
149
+ # FPN Module
150
+ self.lateral_convs = nn.ModuleList()
151
+ self.fpn_convs = nn.ModuleList()
152
+ for in_channels in self.in_channels[:-1]: # skip the top layer
153
+ l_conv = UperNetConvModule(in_channels, self.channels, kernel_size=1)
154
+ fpn_conv = UperNetConvModule(self.channels, self.channels, kernel_size=3, padding=1)
155
+ self.lateral_convs.append(l_conv)
156
+ self.fpn_convs.append(fpn_conv)
157
+
158
+ self.fpn_bottleneck = UperNetConvModule(
159
+ len(self.in_channels) * self.channels,
160
+ self.channels,
161
+ kernel_size=3,
162
+ padding=1,
163
+ )
164
+
165
+ def psp_forward(self, inputs):
166
+ x = inputs[-1]
167
+ psp_outs = [x]
168
+ psp_outs.extend(self.psp_modules(x))
169
+ psp_outs = torch.cat(psp_outs, dim=1)
170
+ output = self.bottleneck(psp_outs)
171
+
172
+ return output
173
+
174
+ def forward(self, encoder_hidden_states: torch.Tensor) -> torch.Tensor:
175
+ # build laterals
176
+ laterals = [lateral_conv(encoder_hidden_states[i]) for i, lateral_conv in enumerate(self.lateral_convs)]
177
+
178
+ laterals.append(self.psp_forward(encoder_hidden_states))
179
+
180
+ # build top-down path
181
+ used_backbone_levels = len(laterals)
182
+ for i in range(used_backbone_levels - 1, 0, -1):
183
+ prev_shape = laterals[i - 1].shape[2:]
184
+ laterals[i - 1] = laterals[i - 1] + nn.functional.interpolate(
185
+ laterals[i], size=prev_shape, mode="bilinear", align_corners=self.align_corners
186
+ )
187
+
188
+ # build outputs
189
+ fpn_outs = [self.fpn_convs[i](laterals[i]) for i in range(used_backbone_levels - 1)]
190
+ # append psp feature
191
+ fpn_outs.append(laterals[-1])
192
+
193
+ for i in range(used_backbone_levels - 1, 0, -1):
194
+ fpn_outs[i] = nn.functional.interpolate(
195
+ fpn_outs[i], size=fpn_outs[0].shape[2:], mode="bilinear", align_corners=self.align_corners
196
+ )
197
+ fpn_outs = torch.cat(fpn_outs, dim=1)
198
+ output = self.fpn_bottleneck(fpn_outs)
199
+ output = self.classifier(output)
200
+
201
+ return output
202
+
203
+
204
+ class UperNetFCNHead(nn.Module):
205
+ """
206
+ Fully Convolution Networks for Semantic Segmentation. This head is the implementation of
207
+ [FCNNet](https://huggingface.co/papers/1411.4038>).
208
+
209
+ Args:
210
+ config:
211
+ Configuration.
212
+ in_channels (int):
213
+ Number of input channels.
214
+ kernel_size (int):
215
+ The kernel size for convs in the head. Default: 3.
216
+ dilation (int):
217
+ The dilation rate for convs in the head. Default: 1.
218
+ """
219
+
220
+ def __init__(
221
+ self, config, in_channels, in_index: int = 2, kernel_size: int = 3, dilation: Union[int, tuple[int, int]] = 1
222
+ ) -> None:
223
+ super().__init__()
224
+
225
+ self.config = config
226
+ self.in_channels = (
227
+ in_channels[in_index] if config.auxiliary_in_channels is None else config.auxiliary_in_channels
228
+ )
229
+ self.channels = config.auxiliary_channels
230
+ self.num_convs = config.auxiliary_num_convs
231
+ self.concat_input = config.auxiliary_concat_input
232
+ self.in_index = in_index
233
+
234
+ conv_padding = (kernel_size // 2) * dilation
235
+ convs = []
236
+ convs.append(
237
+ UperNetConvModule(
238
+ self.in_channels, self.channels, kernel_size=kernel_size, padding=conv_padding, dilation=dilation
239
+ )
240
+ )
241
+ for i in range(self.num_convs - 1):
242
+ convs.append(
243
+ UperNetConvModule(
244
+ self.channels, self.channels, kernel_size=kernel_size, padding=conv_padding, dilation=dilation
245
+ )
246
+ )
247
+ if self.num_convs == 0:
248
+ self.convs = nn.Identity()
249
+ else:
250
+ self.convs = nn.Sequential(*convs)
251
+ if self.concat_input:
252
+ self.conv_cat = UperNetConvModule(
253
+ self.in_channels + self.channels, self.channels, kernel_size=kernel_size, padding=kernel_size // 2
254
+ )
255
+
256
+ self.classifier = nn.Conv2d(self.channels, config.num_labels, kernel_size=1)
257
+
258
+ def forward(self, encoder_hidden_states: torch.Tensor) -> torch.Tensor:
259
+ # just take the relevant feature maps
260
+ hidden_states = encoder_hidden_states[self.in_index]
261
+ output = self.convs(hidden_states)
262
+ if self.concat_input:
263
+ output = self.conv_cat(torch.cat([hidden_states, output], dim=1))
264
+ output = self.classifier(output)
265
+ return output
266
+
267
+
268
+ @auto_docstring
269
+ class UperNetPreTrainedModel(PreTrainedModel):
270
+ config: UperNetConfig
271
+ main_input_name = "pixel_values"
272
+ _no_split_modules = []
273
+
274
+ def _init_weights(self, module):
275
+ if isinstance(module, nn.Conv2d):
276
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
277
+ if module.bias is not None:
278
+ module.bias.data.zero_()
279
+ elif isinstance(module, nn.BatchNorm2d):
280
+ module.weight.data.fill_(1.0)
281
+ module.bias.data.zero_()
282
+
283
+
284
+ @auto_docstring(
285
+ custom_intro="""
286
+ UperNet framework leveraging any vision backbone e.g. for ADE20k, CityScapes.
287
+ """
288
+ )
289
+ class UperNetForSemanticSegmentation(UperNetPreTrainedModel):
290
+ def __init__(self, config):
291
+ super().__init__(config)
292
+
293
+ self.backbone = load_backbone(config)
294
+
295
+ # Semantic segmentation head(s)
296
+ self.decode_head = UperNetHead(config, in_channels=self.backbone.channels)
297
+ self.auxiliary_head = (
298
+ UperNetFCNHead(config, in_channels=self.backbone.channels) if config.use_auxiliary_head else None
299
+ )
300
+
301
+ # Initialize weights and apply final processing
302
+ self.post_init()
303
+
304
+ @auto_docstring
305
+ def forward(
306
+ self,
307
+ pixel_values: Optional[torch.Tensor] = None,
308
+ output_attentions: Optional[bool] = None,
309
+ output_hidden_states: Optional[bool] = None,
310
+ labels: Optional[torch.Tensor] = None,
311
+ return_dict: Optional[bool] = None,
312
+ ) -> Union[tuple, SemanticSegmenterOutput]:
313
+ r"""
314
+ labels (`torch.LongTensor` of shape `(batch_size, height, width)`, *optional*):
315
+ Ground truth semantic segmentation maps for computing the loss. Indices should be in `[0, ...,
316
+ config.num_labels - 1]`. If `config.num_labels > 1`, a classification loss is computed (Cross-Entropy).
317
+
318
+ Examples:
319
+ ```python
320
+ >>> from transformers import AutoImageProcessor, UperNetForSemanticSegmentation
321
+ >>> from PIL import Image
322
+ >>> from huggingface_hub import hf_hub_download
323
+
324
+ >>> image_processor = AutoImageProcessor.from_pretrained("openmmlab/upernet-convnext-tiny")
325
+ >>> model = UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-convnext-tiny")
326
+
327
+ >>> filepath = hf_hub_download(
328
+ ... repo_id="hf-internal-testing/fixtures_ade20k", filename="ADE_val_00000001.jpg", repo_type="dataset"
329
+ ... )
330
+ >>> image = Image.open(filepath).convert("RGB")
331
+
332
+ >>> inputs = image_processor(images=image, return_tensors="pt")
333
+
334
+ >>> outputs = model(**inputs)
335
+
336
+ >>> logits = outputs.logits # shape (batch_size, num_labels, height, width)
337
+ >>> list(logits.shape)
338
+ [1, 150, 512, 512]
339
+ ```"""
340
+ if labels is not None and self.config.num_labels == 1:
341
+ raise ValueError("The number of labels should be greater than one")
342
+
343
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
344
+ output_hidden_states = (
345
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
346
+ )
347
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
348
+
349
+ outputs = self.backbone.forward_with_filtered_kwargs(
350
+ pixel_values, output_hidden_states=output_hidden_states, output_attentions=output_attentions
351
+ )
352
+ features = outputs.feature_maps
353
+
354
+ logits = self.decode_head(features)
355
+ logits = nn.functional.interpolate(logits, size=pixel_values.shape[2:], mode="bilinear", align_corners=False)
356
+
357
+ auxiliary_logits = None
358
+ if self.auxiliary_head is not None:
359
+ auxiliary_logits = self.auxiliary_head(features)
360
+ auxiliary_logits = nn.functional.interpolate(
361
+ auxiliary_logits, size=pixel_values.shape[2:], mode="bilinear", align_corners=False
362
+ )
363
+
364
+ loss = None
365
+ if labels is not None:
366
+ # compute weighted loss
367
+ loss_fct = CrossEntropyLoss(ignore_index=self.config.loss_ignore_index)
368
+ loss = loss_fct(logits, labels)
369
+ if auxiliary_logits is not None:
370
+ auxiliary_loss = loss_fct(auxiliary_logits, labels)
371
+ loss += self.config.auxiliary_loss_weight * auxiliary_loss
372
+
373
+ if not return_dict:
374
+ if output_hidden_states:
375
+ output = (logits,) + outputs[1:]
376
+ else:
377
+ output = (logits,) + outputs[2:]
378
+ return ((loss,) + output) if loss is not None else output
379
+
380
+ return SemanticSegmenterOutput(
381
+ loss=loss,
382
+ logits=logits,
383
+ hidden_states=outputs.hidden_states,
384
+ attentions=outputs.attentions,
385
+ )
386
+
387
+
388
+ __all__ = ["UperNetForSemanticSegmentation", "UperNetPreTrainedModel"]
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/video_llava/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. 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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_video_llava import *
22
+ from .image_processing_video_llava import *
23
+ from .modeling_video_llava import *
24
+ from .processing_video_llava import *
25
+ else:
26
+ import sys
27
+
28
+ _file = globals()["__file__"]
29
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/video_llava/configuration_video_llava.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Microsoft Research & University of Wisconsin-Madison and the HuggingFace Inc. team. All rights reserved.
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
+ """VideoLlava model configuration"""
15
+
16
+ from ...configuration_utils import PretrainedConfig
17
+ from ...utils import logging
18
+ from ..auto import CONFIG_MAPPING, AutoConfig
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ class VideoLlavaConfig(PretrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`VideoLlavaForConditionalGeneration`]. It is used to instantiate an
27
+ VideoLlava model according to the specified arguments, defining the model architecture. Instantiating a configuration
28
+ with the defaults will yield a similar configuration to that of the like LanguageBind/Video-LLaVA-7B-hf.
29
+
30
+ e.g. [LanguageBind/Video-LLaVA-7B-hf](https://huggingface.co/LanguageBind/Video-LLaVA-7B-hf)
31
+
32
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
33
+ documentation from [`PretrainedConfig`] for more information.
34
+
35
+ Args:
36
+ vision_config (`VideoLlavaVisionConfig`, *optional*):
37
+ Custom vision config or dict. Defaults to `CLIPVisionConfig` if not indicated.
38
+ text_config (`Union[AutoConfig, dict]`, *optional*):
39
+ The config object of the text backbone. Can be any of `LlamaConfig` or `MistralConfig`.
40
+ Defaults to `LlamaConfig` if not indicated.
41
+ image_token_index (`int`, *optional*, defaults to 32000):
42
+ The image token index to encode the image prompt.
43
+ video_token_index (`int`, *optional*, defaults to 32001):
44
+ The video token index to encode the image prompt.
45
+ projector_hidden_act (`str`, *optional*, defaults to `"gelu"`):
46
+ The activation function used by the multimodal projector.
47
+ vision_feature_select_strategy (`str`, *optional*, defaults to `"default"`):
48
+ The feature selection strategy used to select the vision feature from the CLIP backbone.
49
+ Can be either "full" to select all features or "default" to select features without `CLS`.
50
+ vision_feature_layer (`Union[int, list[int]]`, *optional*, defaults to -2):
51
+ The index of the layer to select the vision feature. If multiple indices are provided,
52
+ the vision feature of the corresponding indices will be concatenated to form the
53
+ vision features.
54
+ image_seq_length (`int`, *optional*, defaults to 256):
55
+ Sequence length of one image embedding.
56
+ video_seq_length (`int`, *optional*, defaults to 2056):
57
+ Sequence length of one video embedding.
58
+ multimodal_projector_bias (`bool`, *optional*, defaults to `True`):
59
+ Whether to use bias in the multimodal projector.
60
+
61
+ Example:
62
+
63
+ ```python
64
+ >>> from transformers import VideoLlavaForConditionalGeneration, VideoLlavaConfig, CLIPVisionConfig, LlamaConfig
65
+
66
+ >>> # Initializing a CLIP-vision config
67
+ >>> vision_config = CLIPVisionConfig()
68
+
69
+ >>> # Initializing a Llama config
70
+ >>> text_config = LlamaConfig()
71
+
72
+ >>> # Initializing a VideoLlava video_llava-1.5-7b style configuration
73
+ >>> configuration = VideoLlavaConfig(vision_config, text_config)
74
+
75
+ >>> # Initializing a model from the video_llava-1.5-7b style configuration
76
+ >>> model = VideoLlavaForConditionalGeneration(configuration)
77
+
78
+ >>> # Accessing the model configuration
79
+ >>> configuration = model.config
80
+ ```"""
81
+
82
+ model_type = "video_llava"
83
+ attribute_map = {
84
+ "image_token_id": "image_token_index",
85
+ "video_token_id": "video_token_index",
86
+ }
87
+ sub_configs = {"text_config": AutoConfig, "vision_config": AutoConfig}
88
+
89
+ def __init__(
90
+ self,
91
+ vision_config=None,
92
+ text_config=None,
93
+ image_token_index=32000,
94
+ video_token_index=32001,
95
+ projector_hidden_act="gelu",
96
+ vision_feature_select_strategy="default",
97
+ vision_feature_layer=-2,
98
+ image_seq_length=256,
99
+ video_seq_length=2056,
100
+ multimodal_projector_bias=True,
101
+ **kwargs,
102
+ ):
103
+ self.image_token_index = image_token_index
104
+ self.video_token_index = video_token_index
105
+ self.projector_hidden_act = projector_hidden_act
106
+ self.vision_feature_select_strategy = vision_feature_select_strategy
107
+ self.vision_feature_layer = vision_feature_layer
108
+ self.image_seq_length = image_seq_length
109
+ self.video_seq_length = video_seq_length
110
+ self.multimodal_projector_bias = multimodal_projector_bias
111
+
112
+ self.vision_config = vision_config
113
+
114
+ if isinstance(self.vision_config, dict):
115
+ if "model_type" not in vision_config:
116
+ vision_config["model_type"] = "clip_vision_model"
117
+ logger.warning("Key=`model_type` not found in vision config, setting it to `clip_vision_model`")
118
+ self.vision_config = CONFIG_MAPPING[vision_config["model_type"]](**vision_config)
119
+ elif vision_config is None:
120
+ self.vision_config = CONFIG_MAPPING["clip_vision_model"](
121
+ intermediate_size=4096,
122
+ hidden_size=1024,
123
+ patch_size=14,
124
+ image_size=224,
125
+ num_hidden_layers=24,
126
+ num_attention_heads=16,
127
+ vocab_size=32000,
128
+ projection_dim=768,
129
+ )
130
+
131
+ if isinstance(text_config, dict):
132
+ if "model_type" not in text_config:
133
+ text_config["model_type"] = "llama"
134
+ logger.warning("Key=`model_type` not found in text config, setting it to `llama`")
135
+ text_config = CONFIG_MAPPING[text_config["model_type"]](**text_config)
136
+ elif text_config is None:
137
+ text_config = CONFIG_MAPPING["llama"]()
138
+
139
+ self.text_config = text_config
140
+ super().__init__(**kwargs)
141
+
142
+
143
+ __all__ = ["VideoLlavaConfig"]
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/video_llava/convert_video_llava_weights_to_hf.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Inc. team. 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
+ import argparse
15
+
16
+ import torch
17
+ from huggingface_hub import hf_hub_download
18
+
19
+ from transformers import (
20
+ AddedToken,
21
+ AutoConfig,
22
+ AutoTokenizer,
23
+ VideoLlavaConfig,
24
+ VideoLlavaForConditionalGeneration,
25
+ VideoLlavaImageProcessor,
26
+ VideoLlavaProcessor,
27
+ )
28
+
29
+
30
+ EPILOG_TXT = """Example:
31
+ python transformers/src/transformers/models/video_llava/convert_video_llava_weights_to_hf.py --text_model_id lmsys/vicuna-7b-v1.5 --vision_model_id openai/clip-vit-large-patch14 --output_hub_path org/video_llava-7b --old_state_dict_id LanguageBind/Video-LLaVA-7B
32
+
33
+ Example for creating the old state dict file with Python:
34
+
35
+ import torch
36
+ from video_llava.model.language_model.video_llava import VideoLlavaForCausalLM
37
+
38
+ # load model
39
+ kwargs = {"device_map": "auto", "torch_dtype": torch.float16}
40
+ model = VideoLlavaForCausalLM.from_pretrained("LanguageBind/Video-LLaVA-7B-hf", **kwargs)
41
+
42
+ # load vision tower
43
+ model.get_vision_tower().load_model()
44
+
45
+ # Save state dict
46
+ torch.save(model.state_dict(), "tmp/hf_models/video_llava-7b/model_state_dict.bin")
47
+ """
48
+
49
+ KEYS_TO_MODIFY_MAPPING = {
50
+ "model.video_tower.video_tower": "video_tower",
51
+ "model.image_tower.image_tower": "image_tower",
52
+ "model.mm_projector": "multi_modal_projector",
53
+ "model": "language_model.model",
54
+ "lm_head": "language_model.lm_head",
55
+ "video_tower": "video_tower.vision_model",
56
+ "image_tower": "image_tower.vision_model",
57
+ "multi_modal_projector.0": "multi_modal_projector.linear_1",
58
+ "multi_modal_projector.2": "multi_modal_projector.linear_2",
59
+ }
60
+
61
+
62
+ def convert_state_dict_to_hf(state_dict):
63
+ new_state_dict = {}
64
+ for key, value in state_dict.items():
65
+ if key.endswith(".inv_freq"):
66
+ continue
67
+ for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items():
68
+ if key_to_modify in key:
69
+ key = key.replace(key_to_modify, new_key)
70
+
71
+ new_state_dict[key] = value
72
+ return new_state_dict
73
+
74
+
75
+ def convert_video_llava_llama_to_hf(text_model_id, vision_model_id, output_hub_path, old_state_dict_id):
76
+ torch.set_default_dtype(torch.float16)
77
+ text_config = AutoConfig.from_pretrained(text_model_id)
78
+
79
+ tokenizer = AutoTokenizer.from_pretrained(text_model_id)
80
+ tokenizer.add_tokens(AddedToken("<image>", special=True, normalized=False), special_tokens=True)
81
+ tokenizer.add_tokens(AddedToken("<video>", special=True, normalized=False), special_tokens=True)
82
+ tokenizer.add_special_tokens({"pad_token": "<pad>"})
83
+ tokenizer.padding_side = "left"
84
+
85
+ image_processor = VideoLlavaImageProcessor.from_pretrained(vision_model_id)
86
+
87
+ processor = VideoLlavaProcessor(tokenizer=tokenizer, image_processor=image_processor)
88
+
89
+ config = VideoLlavaConfig(text_config=text_config)
90
+ config.pad_token_id = 32002
91
+
92
+ with torch.device("meta"):
93
+ model = VideoLlavaForConditionalGeneration(config)
94
+
95
+ model_state_dict = set(model.state_dict().keys())
96
+
97
+ # Pad to 64 for performance reasons
98
+ pad_shape = 64
99
+ state_dict_temp = "pytorch_model-0000{i}-of-00002.bin"
100
+ for shard in range(1, 3):
101
+ state_dict_path = hf_hub_download(old_state_dict_id, state_dict_temp.format(i=shard))
102
+ state_dict = torch.load(state_dict_path, map_location="cpu", weights_only=True)
103
+ state_dict = convert_state_dict_to_hf(state_dict)
104
+ model.load_state_dict(state_dict, strict=False, assign=True)
105
+ model_state_dict -= set(state_dict.keys())
106
+
107
+ if len(model_state_dict) > 0:
108
+ raise RuntimeError(f"Missing keys in state dict: {model_state_dict}")
109
+
110
+ pre_expansion_embeddings = model.language_model.model.embed_tokens.weight.data
111
+ mu = torch.mean(pre_expansion_embeddings, dim=0).float()
112
+ n = pre_expansion_embeddings.size()[0]
113
+ sigma = ((pre_expansion_embeddings - mu).T @ (pre_expansion_embeddings - mu)) / n
114
+ dist = torch.distributions.multivariate_normal.MultivariateNormal(mu, covariance_matrix=1e-5 * sigma)
115
+
116
+ # We add an image and video token so we resize the model
117
+ model.resize_token_embeddings(config.text_config.vocab_size + 3, pad_shape)
118
+ model.language_model.model.embed_tokens.weight.data[32000:] = torch.stack(
119
+ tuple(dist.sample() for _ in range(model.language_model.model.embed_tokens.weight.data[32000:].shape[0])),
120
+ dim=0,
121
+ )
122
+ model.language_model.lm_head.weight.data[32000:] = torch.stack(
123
+ tuple(dist.sample() for _ in range(model.language_model.lm_head.weight.data[32000:].shape[0])),
124
+ dim=0,
125
+ )
126
+
127
+ model.push_to_hub(output_hub_path)
128
+ processor.push_to_hub(output_hub_path)
129
+
130
+
131
+ def main():
132
+ parser = argparse.ArgumentParser(
133
+ epilog=EPILOG_TXT,
134
+ formatter_class=argparse.RawDescriptionHelpFormatter,
135
+ )
136
+ parser.add_argument(
137
+ "--text_model_id",
138
+ help="Hub location of the text model",
139
+ )
140
+ parser.add_argument(
141
+ "--vision_model_id",
142
+ help="Hub location of the vision model",
143
+ )
144
+ parser.add_argument(
145
+ "--output_hub_path",
146
+ help="Location on the hub of the converted model",
147
+ )
148
+ parser.add_argument(
149
+ "--old_state_dict_id",
150
+ help="Location on the hub of the raw state dict of the original model. The filename needs to be `model_state_dict.bin`",
151
+ )
152
+ args = parser.parse_args()
153
+ convert_video_llava_llama_to_hf(
154
+ args.text_model_id, args.vision_model_id, args.output_hub_path, args.old_state_dict_id
155
+ )
156
+
157
+
158
+ if __name__ == "__main__":
159
+ main()
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/video_llava/image_processing_video_llava.py ADDED
@@ -0,0 +1,390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The HuggingFace Inc. team. 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
+ """Image processor class for Video-LLaVA."""
16
+
17
+ from typing import Optional, Union
18
+
19
+ import numpy as np
20
+
21
+ from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
22
+ from ...image_transforms import (
23
+ convert_to_rgb,
24
+ get_resize_output_image_size,
25
+ resize,
26
+ to_channel_dimension_format,
27
+ )
28
+ from ...image_utils import (
29
+ OPENAI_CLIP_MEAN,
30
+ OPENAI_CLIP_STD,
31
+ ChannelDimension,
32
+ ImageInput,
33
+ PILImageResampling,
34
+ infer_channel_dimension_format,
35
+ is_scaled_image,
36
+ make_list_of_images,
37
+ to_numpy_array,
38
+ valid_images,
39
+ validate_preprocess_arguments,
40
+ )
41
+ from ...utils import TensorType, filter_out_non_signature_kwargs, logging
42
+ from ...video_utils import VideoInput, make_batched_videos
43
+
44
+
45
+ logger = logging.get_logger(__name__)
46
+
47
+
48
+ class VideoLlavaImageProcessor(BaseImageProcessor):
49
+ r"""
50
+ Constructs a CLIP image processor.
51
+
52
+ Args:
53
+ do_resize (`bool`, *optional*, defaults to `True`):
54
+ Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by
55
+ `do_resize` in the `preprocess` method.
56
+ size (`dict[str, int]` *optional*, defaults to `{"shortest_edge": 224}`):
57
+ Size of the image after resizing. The shortest edge of the image is resized to size["shortest_edge"], with
58
+ the longest edge resized to keep the input aspect ratio. Can be overridden by `size` in the `preprocess`
59
+ method.
60
+ resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`):
61
+ Resampling filter to use if resizing the image. Can be overridden by `resample` in the `preprocess` method.
62
+ do_center_crop (`bool`, *optional*, defaults to `True`):
63
+ Whether to center crop the image to the specified `crop_size`. Can be overridden by `do_center_crop` in the
64
+ `preprocess` method.
65
+ crop_size (`dict[str, int]` *optional*, defaults to 224):
66
+ Size of the output image after applying `center_crop`. Can be overridden by `crop_size` in the `preprocess`
67
+ method.
68
+ do_rescale (`bool`, *optional*, defaults to `True`):
69
+ Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by `do_rescale` in
70
+ the `preprocess` method.
71
+ rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
72
+ Scale factor to use if rescaling the image. Can be overridden by `rescale_factor` in the `preprocess`
73
+ method.
74
+ do_normalize (`bool`, *optional*, defaults to `True`):
75
+ Whether to normalize the image. Can be overridden by `do_normalize` in the `preprocess` method.
76
+ image_mean (`float` or `list[float]`, *optional*, defaults to `[0.48145466, 0.4578275, 0.40821073]`):
77
+ Mean to use if normalizing the image. This is a float or list of floats the length of the number of
78
+ channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
79
+ image_std (`float` or `list[float]`, *optional*, defaults to `[0.26862954, 0.26130258, 0.27577711]`):
80
+ Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
81
+ number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
82
+ Can be overridden by the `image_std` parameter in the `preprocess` method.
83
+ do_convert_rgb (`bool`, *optional*, defaults to `True`):
84
+ Whether to convert the image to RGB.
85
+ """
86
+
87
+ model_input_names = ["pixel_values"]
88
+
89
+ def __init__(
90
+ self,
91
+ do_resize: bool = True,
92
+ size: Optional[dict[str, int]] = None,
93
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
94
+ do_center_crop: bool = True,
95
+ crop_size: Optional[dict[str, int]] = None,
96
+ do_rescale: bool = True,
97
+ rescale_factor: Union[int, float] = 1 / 255,
98
+ do_normalize: bool = True,
99
+ image_mean: Optional[Union[float, list[float]]] = None,
100
+ image_std: Optional[Union[float, list[float]]] = None,
101
+ do_convert_rgb: bool = True,
102
+ **kwargs,
103
+ ) -> None:
104
+ super().__init__(**kwargs)
105
+ size = size if size is not None else {"shortest_edge": 224}
106
+ size = get_size_dict(size, default_to_square=False)
107
+ crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
108
+ crop_size = get_size_dict(crop_size, default_to_square=True, param_name="crop_size")
109
+
110
+ self.do_resize = do_resize
111
+ self.size = size
112
+ self.resample = resample
113
+ self.do_center_crop = do_center_crop
114
+ self.crop_size = crop_size
115
+ self.do_rescale = do_rescale
116
+ self.rescale_factor = rescale_factor
117
+ self.do_normalize = do_normalize
118
+ self.image_mean = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
119
+ self.image_std = image_std if image_std is not None else OPENAI_CLIP_STD
120
+ self.do_convert_rgb = do_convert_rgb
121
+
122
+ def resize(
123
+ self,
124
+ image: np.ndarray,
125
+ size: dict[str, int],
126
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
127
+ data_format: Optional[Union[str, ChannelDimension]] = None,
128
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
129
+ **kwargs,
130
+ ) -> np.ndarray:
131
+ """
132
+ Resize an image. The shortest edge of the image is resized to size["shortest_edge"], with the longest edge
133
+ resized to keep the input aspect ratio.
134
+
135
+ Args:
136
+ image (`np.ndarray`):
137
+ Image to resize.
138
+ size (`dict[str, int]`):
139
+ Size of the output image.
140
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
141
+ Resampling filter to use when resiizing the image.
142
+ data_format (`str` or `ChannelDimension`, *optional*):
143
+ The channel dimension format of the image. If not provided, it will be the same as the input image.
144
+ input_data_format (`ChannelDimension` or `str`, *optional*):
145
+ The channel dimension format of the input image. If not provided, it will be inferred.
146
+ """
147
+ default_to_square = True
148
+ if "shortest_edge" in size:
149
+ size = size["shortest_edge"]
150
+ default_to_square = False
151
+ elif "height" in size and "width" in size:
152
+ size = (size["height"], size["width"])
153
+ else:
154
+ raise ValueError("Size must contain either 'shortest_edge' or 'height' and 'width'.")
155
+
156
+ output_size = get_resize_output_image_size(
157
+ image,
158
+ size=size,
159
+ default_to_square=default_to_square,
160
+ input_data_format=input_data_format,
161
+ )
162
+ return resize(
163
+ image,
164
+ size=output_size,
165
+ resample=resample,
166
+ data_format=data_format,
167
+ input_data_format=input_data_format,
168
+ **kwargs,
169
+ )
170
+
171
+ @filter_out_non_signature_kwargs()
172
+ def preprocess(
173
+ self,
174
+ images: Optional[list[ImageInput]] = None,
175
+ videos: Optional[list[VideoInput]] = None,
176
+ do_resize: Optional[bool] = None,
177
+ size: Optional[dict[str, int]] = None,
178
+ resample: PILImageResampling = None,
179
+ do_center_crop: Optional[bool] = None,
180
+ crop_size: Optional[int] = None,
181
+ do_rescale: Optional[bool] = None,
182
+ rescale_factor: Optional[float] = None,
183
+ do_normalize: Optional[bool] = None,
184
+ image_mean: Optional[Union[float, list[float]]] = None,
185
+ image_std: Optional[Union[float, list[float]]] = None,
186
+ do_convert_rgb: Optional[bool] = None,
187
+ return_tensors: Optional[Union[str, TensorType]] = None,
188
+ data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
189
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
190
+ ) -> BatchFeature:
191
+ """
192
+ Preprocess an image or batch of images.
193
+
194
+ Args:
195
+ images (`ImageInput`, *optional*):
196
+ List of images to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
197
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
198
+ videos (`VideoInput`, *optional*):
199
+ List of videos to preprocess. Expects a single or batch of videos with pixel values ranging from 0 to 255. If
200
+ passing in videos with pixel values between 0 and 1, set `do_rescale=False`.
201
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
202
+ Whether to resize the image.
203
+ size (`dict[str, int]`, *optional*, defaults to `self.size`):
204
+ Size of the image after resizing. Shortest edge of the image is resized to size["shortest_edge"], with
205
+ the longest edge resized to keep the input aspect ratio.
206
+ resample (`int`, *optional*, defaults to `self.resample`):
207
+ Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
208
+ has an effect if `do_resize` is set to `True`.
209
+ do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`):
210
+ Whether to center crop the image.
211
+ crop_size (`dict[str, int]`, *optional*, defaults to `self.crop_size`):
212
+ Size of the center crop. Only has an effect if `do_center_crop` is set to `True`.
213
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
214
+ Whether to rescale the image.
215
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
216
+ Rescale factor to rescale the image by if `do_rescale` is set to `True`.
217
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
218
+ Whether to normalize the image.
219
+ image_mean (`float` or `list[float]`, *optional*, defaults to `self.image_mean`):
220
+ Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
221
+ image_std (`float` or `list[float]`, *optional*, defaults to `self.image_std`):
222
+ Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
223
+ `True`.
224
+ do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
225
+ Whether to convert the image to RGB.
226
+ return_tensors (`str` or `TensorType`, *optional*):
227
+ The type of tensors to return. Can be one of:
228
+ - Unset: Return a list of `np.ndarray`.
229
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
230
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
231
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
232
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
233
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
234
+ The channel dimension format for the output image. Can be one of:
235
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
236
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
237
+ - Unset: Use the channel dimension format of the input image.
238
+ input_data_format (`ChannelDimension` or `str`, *optional*):
239
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
240
+ from the input image. Can be one of:
241
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
242
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
243
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
244
+ """
245
+ do_resize = do_resize if do_resize is not None else self.do_resize
246
+ size = size if size is not None else self.size
247
+ size = get_size_dict(size, param_name="size", default_to_square=False)
248
+ resample = resample if resample is not None else self.resample
249
+ do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
250
+ crop_size = crop_size if crop_size is not None else self.crop_size
251
+ crop_size = get_size_dict(crop_size, param_name="crop_size", default_to_square=True)
252
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
253
+ rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
254
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
255
+ image_mean = image_mean if image_mean is not None else self.image_mean
256
+ image_std = image_std if image_std is not None else self.image_std
257
+ do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
258
+
259
+ if images is not None:
260
+ images = make_list_of_images(images)
261
+
262
+ if images is not None and not valid_images(images):
263
+ raise ValueError(
264
+ "Invalid input type. Must be of type PIL.Image.Image, numpy.ndarray, "
265
+ "torch.Tensor, tf.Tensor or jax.ndarray."
266
+ )
267
+
268
+ data = {}
269
+ if videos is not None:
270
+ logger.warning(
271
+ "`VideoLlavaImageProcessor` works only with image inputs and doesn't process videos anymore. "
272
+ "This is a deprecated behavior and will be removed in v5.0. "
273
+ "Your videos should be forwarded to `VideoLlavaVideoProcessor`. "
274
+ )
275
+ videos = make_batched_videos(videos)
276
+ pixel_values_videos = [
277
+ [
278
+ self._preprocess_image(
279
+ image=frame,
280
+ do_resize=do_resize,
281
+ size=size,
282
+ resample=resample,
283
+ do_rescale=do_rescale,
284
+ rescale_factor=rescale_factor,
285
+ do_normalize=do_normalize,
286
+ image_mean=image_mean,
287
+ image_std=image_std,
288
+ do_center_crop=do_center_crop,
289
+ crop_size=crop_size,
290
+ do_convert_rgb=do_convert_rgb,
291
+ data_format=data_format,
292
+ input_data_format=input_data_format,
293
+ )
294
+ for frame in video
295
+ ]
296
+ for video in videos
297
+ ]
298
+ data["pixel_values_videos"] = pixel_values_videos
299
+
300
+ if images is not None:
301
+ pixel_values_images = [
302
+ self._preprocess_image(
303
+ image=image,
304
+ do_resize=do_resize,
305
+ size=size,
306
+ resample=resample,
307
+ do_rescale=do_rescale,
308
+ rescale_factor=rescale_factor,
309
+ do_normalize=do_normalize,
310
+ image_mean=image_mean,
311
+ image_std=image_std,
312
+ do_center_crop=do_center_crop,
313
+ crop_size=crop_size,
314
+ do_convert_rgb=do_convert_rgb,
315
+ data_format=data_format,
316
+ input_data_format=input_data_format,
317
+ )
318
+ for image in images
319
+ ]
320
+ data["pixel_values_images"] = pixel_values_images
321
+
322
+ encoded_outputs = BatchFeature(data, tensor_type=return_tensors)
323
+
324
+ return encoded_outputs
325
+
326
+ def _preprocess_image(
327
+ self,
328
+ image: ImageInput = None,
329
+ do_resize: Optional[bool] = None,
330
+ size: Optional[dict[str, int]] = None,
331
+ resample: PILImageResampling = None,
332
+ do_rescale: Optional[bool] = None,
333
+ rescale_factor: Optional[float] = None,
334
+ do_normalize: Optional[bool] = None,
335
+ image_mean: Optional[Union[float, list[float]]] = None,
336
+ image_std: Optional[Union[float, list[float]]] = None,
337
+ do_center_crop: Optional[bool] = None,
338
+ crop_size: Optional[int] = None,
339
+ do_convert_rgb: Optional[bool] = None,
340
+ data_format: ChannelDimension = ChannelDimension.FIRST,
341
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
342
+ ) -> np.ndarray:
343
+ validate_preprocess_arguments(
344
+ do_rescale=do_rescale,
345
+ rescale_factor=rescale_factor,
346
+ do_normalize=do_normalize,
347
+ image_mean=image_mean,
348
+ image_std=image_std,
349
+ do_center_crop=do_center_crop,
350
+ crop_size=crop_size,
351
+ do_resize=do_resize,
352
+ size=size,
353
+ resample=resample,
354
+ )
355
+
356
+ # PIL RGBA images are converted to RGB
357
+ if do_convert_rgb:
358
+ image = convert_to_rgb(image)
359
+
360
+ # All transformations expect numpy arrays.
361
+ image = to_numpy_array(image)
362
+
363
+ if do_rescale and is_scaled_image(image):
364
+ logger.warning_once(
365
+ "It looks like you are trying to rescale already rescaled images/video frames. If the input"
366
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
367
+ )
368
+
369
+ if input_data_format is None:
370
+ # We assume that all images have the same channel dimension format.
371
+ input_data_format = infer_channel_dimension_format(image)
372
+
373
+ if do_resize:
374
+ image = self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
375
+
376
+ if do_center_crop:
377
+ image = self.center_crop(image=image, size=crop_size, input_data_format=input_data_format)
378
+
379
+ if do_rescale:
380
+ image = self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
381
+
382
+ if do_normalize:
383
+ image = self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
384
+
385
+ image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
386
+
387
+ return image
388
+
389
+
390
+ __all__ = ["VideoLlavaImageProcessor"]
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/video_llava/modeling_video_llava.py ADDED
@@ -0,0 +1,721 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 the HuggingFace Inc. team. 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
+ """PyTorch VideoLlava model."""
16
+
17
+ from dataclasses import dataclass
18
+ from typing import Optional, Union
19
+
20
+ import torch
21
+ import torch.utils.checkpoint
22
+ from torch import nn
23
+
24
+ from ...activations import ACT2FN
25
+ from ...cache_utils import Cache
26
+ from ...generation import GenerationMixin
27
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
28
+ from ...modeling_outputs import ModelOutput
29
+ from ...modeling_utils import PreTrainedModel
30
+ from ...processing_utils import Unpack
31
+ from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, logging
32
+ from ..auto import AutoModel
33
+ from .configuration_video_llava import VideoLlavaConfig
34
+
35
+
36
+ logger = logging.get_logger(__name__)
37
+
38
+
39
+ @dataclass
40
+ @auto_docstring(
41
+ custom_intro="""
42
+ Base class for VideoLlava base model outputs.
43
+ """
44
+ )
45
+ class VideoLlavaModelOutputWithPast(ModelOutput):
46
+ r"""
47
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
48
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
49
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`)
50
+
51
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
52
+ `past_key_values` input) to speed up sequential decoding.
53
+ image_hidden_states (`torch.FloatTensor`, *optional*):
54
+ A `torch.FloatTensor` of size (batch_size, num_images, sequence_length, hidden_size)`.
55
+ image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
56
+ video_hidden_states (`torch.FloatTensor`, *optional*):
57
+ A `torch.FloatTensor` of size `(batch_size * num_frames, num_videos, sequence_length, hidden_size)`.
58
+ video_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
59
+ """
60
+
61
+ last_hidden_state: torch.FloatTensor = None
62
+ past_key_values: Optional[list[torch.FloatTensor]] = None
63
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
64
+ attentions: Optional[tuple[torch.FloatTensor]] = None
65
+ image_hidden_states: Optional[torch.FloatTensor] = None
66
+ video_hidden_states: Optional[torch.FloatTensor] = None
67
+
68
+
69
+ @dataclass
70
+ @auto_docstring(
71
+ custom_intro="""
72
+ Base class for VideoLlava causal language model (or autoregressive) outputs.
73
+ """
74
+ )
75
+ class VideoLlavaCausalLMOutputWithPast(ModelOutput):
76
+ r"""
77
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
78
+ Language modeling loss (for next-token prediction).
79
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
80
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
81
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
82
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
83
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`)
84
+
85
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
86
+ `past_key_values` input) to speed up sequential decoding.
87
+ image_hidden_states (`torch.FloatTensor`, *optional*):
88
+ A `torch.FloatTensor` of size (batch_size, num_images, sequence_length, hidden_size)`.
89
+ image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
90
+ video_hidden_states (`torch.FloatTensor`, *optional*):
91
+ A `torch.FloatTensor` of size `(batch_size * num_frames, num_videos, sequence_length, hidden_size)`.
92
+ video_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
93
+ """
94
+
95
+ loss: Optional[torch.FloatTensor] = None
96
+ logits: Optional[torch.FloatTensor] = None
97
+ past_key_values: Optional[list[torch.FloatTensor]] = None
98
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
99
+ attentions: Optional[tuple[torch.FloatTensor]] = None
100
+ image_hidden_states: Optional[torch.FloatTensor] = None
101
+ video_hidden_states: Optional[torch.FloatTensor] = None
102
+
103
+
104
+ # Copied from transformers.models.llava.modeling_llava.LlavaMultiModalProjector with Llava->VideoLlava
105
+ class VideoLlavaMultiModalProjector(nn.Module):
106
+ def __init__(self, config: VideoLlavaConfig):
107
+ super().__init__()
108
+ # We have hidden_size * the number of vision feature layers
109
+ num_feature_layers = 1 if isinstance(config.vision_feature_layer, int) else len(config.vision_feature_layer)
110
+ self.linear_1 = nn.Linear(
111
+ config.vision_config.hidden_size * num_feature_layers,
112
+ config.text_config.hidden_size,
113
+ bias=config.multimodal_projector_bias,
114
+ )
115
+ self.act = ACT2FN[config.projector_hidden_act]
116
+ self.linear_2 = nn.Linear(
117
+ config.text_config.hidden_size, config.text_config.hidden_size, bias=config.multimodal_projector_bias
118
+ )
119
+
120
+ def forward(self, image_features):
121
+ hidden_states = self.linear_1(image_features)
122
+ hidden_states = self.act(hidden_states)
123
+ hidden_states = self.linear_2(hidden_states)
124
+ return hidden_states
125
+
126
+
127
+ @auto_docstring
128
+ class VideoLlavaPreTrainedModel(PreTrainedModel):
129
+ config: VideoLlavaConfig
130
+ base_model_prefix = ""
131
+ supports_gradient_checkpointing = True
132
+ _no_split_modules = ["VideoLlavaVisionAttention"]
133
+ _skip_keys_device_placement = "past_key_values"
134
+
135
+ _supports_flash_attn = True
136
+ _supports_sdpa = True
137
+
138
+ _can_compile_fullgraph = True
139
+ _supports_attention_backend = True
140
+
141
+ def _init_weights(self, module):
142
+ std = (
143
+ self.config.initializer_range
144
+ if hasattr(self.config, "initializer_range")
145
+ else self.config.text_config.initializer_range
146
+ )
147
+
148
+ if hasattr(module, "class_embedding"):
149
+ module.class_embedding.data.normal_(mean=0.0, std=std)
150
+
151
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
152
+ module.weight.data.normal_(mean=0.0, std=std)
153
+ if module.bias is not None:
154
+ module.bias.data.zero_()
155
+ elif isinstance(module, nn.Embedding):
156
+ module.weight.data.normal_(mean=0.0, std=std)
157
+ if module.padding_idx is not None:
158
+ module.weight.data[module.padding_idx].zero_()
159
+
160
+
161
+ @auto_docstring(
162
+ custom_intro="""
163
+ The VideoLlava model which consists of a vision backbone and a language model without language modeling head.
164
+ """,
165
+ )
166
+ class VideoLlavaModel(VideoLlavaPreTrainedModel):
167
+ _checkpoint_conversion_mapping = {"language_model.model": "language_model"}
168
+
169
+ def __init__(self, config: VideoLlavaConfig):
170
+ super().__init__(config)
171
+ self.video_tower = AutoModel.from_config(config.vision_config)
172
+ self.image_tower = AutoModel.from_config(config.vision_config)
173
+
174
+ self.multi_modal_projector = VideoLlavaMultiModalProjector(config)
175
+ self.vocab_size = config.text_config.vocab_size
176
+ self.language_model = AutoModel.from_config(config.text_config)
177
+ self.pad_token_id = self.config.pad_token_id if self.config.pad_token_id is not None else -1
178
+ self.post_init()
179
+
180
+ def get_input_embeddings(self):
181
+ return self.language_model.get_input_embeddings()
182
+
183
+ def set_input_embeddings(self, value):
184
+ self.language_model.set_input_embeddings(value)
185
+
186
+ def set_decoder(self, decoder):
187
+ self.language_model = decoder
188
+
189
+ def get_decoder(self):
190
+ return self.language_model
191
+
192
+ def get_image_features(
193
+ self,
194
+ pixel_values_images: torch.FloatTensor,
195
+ vision_feature_layer: Optional[Union[int, list[int]]] = None,
196
+ vision_feature_select_strategy: Optional[str] = None,
197
+ ):
198
+ """
199
+ Obtains image last hidden states from the vision tower and apply multimodal projection.
200
+
201
+ Args:
202
+ pixel_values_images (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`)
203
+ The tensors corresponding to the input images.
204
+ vision_feature_layer (`Union[int, list[int]]`, *optional*):
205
+ The index of the layer to select the vision feature. If multiple indices are provided,
206
+ the vision feature of the corresponding indices will be concatenated to form the
207
+ vision features.
208
+ vision_feature_select_strategy (`str`, *optional*):
209
+ The feature selection strategy used to select the vision feature from the vision backbone.
210
+ Can be one of `"default"` or `"full"`
211
+ Returns:
212
+ image_features (`torch.Tensor`): Image feature tensor of shape `(num_images, image_length, embed_dim)`).
213
+ """
214
+ vision_feature_layer = (
215
+ vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
216
+ )
217
+ vision_feature_select_strategy = (
218
+ vision_feature_select_strategy
219
+ if vision_feature_select_strategy is not None
220
+ else self.config.vision_feature_select_strategy
221
+ )
222
+
223
+ if vision_feature_select_strategy not in ["default", "full"]:
224
+ raise ValueError(f"Unexpected select feature strategy: {self.config.vision_feature_select_strategy}")
225
+
226
+ image_outputs = self.image_tower(pixel_values_images, output_hidden_states=True)
227
+
228
+ # If we have one vision feature layer, return the corresponding hidden states,
229
+ # otherwise, select the hidden states of each feature layer and concatenate them
230
+ if isinstance(vision_feature_layer, int):
231
+ image_outputs = image_outputs.hidden_states[vision_feature_layer]
232
+ if vision_feature_select_strategy == "default":
233
+ image_outputs = image_outputs[:, 1:]
234
+ else:
235
+ hs_pool = [image_outputs.hidden_states[layer_idx] for layer_idx in vision_feature_layer]
236
+ # For default; crop CLS from each hidden state in the hidden state pool
237
+ if vision_feature_select_strategy == "default":
238
+ hs_pool = [hs[:, 1:] for hs in hs_pool]
239
+ image_outputs = torch.cat(hs_pool, dim=-1)
240
+
241
+ image_features = self.multi_modal_projector(image_outputs)
242
+
243
+ return image_features
244
+
245
+ def get_video_features(
246
+ self,
247
+ pixel_values_videos: torch.FloatTensor,
248
+ vision_feature_layer: Optional[Union[int, list[int]]] = None,
249
+ ):
250
+ """
251
+ Obtains video last hidden states from the vision tower and apply multimodal projection.
252
+
253
+ Args:
254
+ pixel_values_videos (`torch.FloatTensor]` of shape `(batch_size, num_frames, channels, height, width)`)
255
+ The tensors corresponding to the input videos.
256
+ vision_feature_layer (`Union[int, list[int]]`, *optional*):
257
+ The index of the layer to select the vision feature. If multiple indices are provided,
258
+ the vision feature of the corresponding indices will be concatenated to form the
259
+ vision features.
260
+ Returns:
261
+ video_features (`torch.Tensor`): Video feature tensor of shape `(num_videos * num_frames, image_length, embed_dim)`).
262
+ frames (`int`): Number of frames the videos have.
263
+ """
264
+ vision_feature_layer = (
265
+ vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
266
+ )
267
+
268
+ batch_size_vid, num_frames, channels, height, width = pixel_values_videos.shape
269
+
270
+ pixel_values = pixel_values_videos.reshape(batch_size_vid * num_frames, channels, height, width)
271
+ video_outputs = self.video_tower(pixel_values, output_hidden_states=True)
272
+
273
+ # If we have one vision feature layer, return the corresponding hidden states,
274
+ # otherwise, select the hidden states of each feature layer and concatenate them
275
+ if isinstance(vision_feature_layer, int):
276
+ video_features = video_outputs.hidden_states[vision_feature_layer]
277
+ else:
278
+ hs_pool = [video_outputs.hidden_states[layer_idx] for layer_idx in vision_feature_layer]
279
+ video_features = torch.cat(hs_pool, dim=-1)
280
+
281
+ video_features = self.multi_modal_projector(video_features)
282
+
283
+ return video_features, num_frames
284
+
285
+ def get_placeholder_mask(
286
+ self,
287
+ input_ids: torch.LongTensor,
288
+ inputs_embeds: torch.FloatTensor,
289
+ image_features: torch.FloatTensor = None,
290
+ video_features: torch.FloatTensor = None,
291
+ ):
292
+ """
293
+ Obtains multimodal placeholdr mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
294
+ equal to the length of multimodal features. If the lengths are different, an error is raised.
295
+ """
296
+ if input_ids is None:
297
+ special_image_mask = inputs_embeds == self.get_input_embeddings()(
298
+ torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
299
+ )
300
+ special_image_mask = special_image_mask.all(-1)
301
+ special_video_mask = inputs_embeds == self.get_input_embeddings()(
302
+ torch.tensor(self.config.video_token_id, dtype=torch.long, device=inputs_embeds.device)
303
+ )
304
+ special_video_mask = special_video_mask.all(-1)
305
+ else:
306
+ special_image_mask = input_ids == self.config.image_token_id
307
+ special_video_mask = input_ids == self.config.video_token_id
308
+
309
+ n_image_tokens = special_image_mask.sum()
310
+ special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
311
+ if image_features is not None and inputs_embeds[special_image_mask].numel() != image_features.numel():
312
+ raise ValueError(
313
+ f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {image_features.shape[0] * image_features.shape[1]}"
314
+ )
315
+
316
+ n_video_tokens = special_video_mask.sum()
317
+ special_video_mask = special_video_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
318
+ if video_features is not None and inputs_embeds[special_video_mask].numel() != video_features.numel():
319
+ raise ValueError(
320
+ f"Videos features and image tokens do not match: tokens: {n_video_tokens}, features {video_features.shape[0] * video_features.shape[1]}"
321
+ )
322
+
323
+ return special_image_mask, special_video_mask
324
+
325
+ @can_return_tuple
326
+ @auto_docstring
327
+ def forward(
328
+ self,
329
+ input_ids: torch.LongTensor = None,
330
+ pixel_values_images: torch.FloatTensor = None,
331
+ pixel_values_videos: torch.FloatTensor = None,
332
+ attention_mask: Optional[torch.Tensor] = None,
333
+ position_ids: Optional[torch.LongTensor] = None,
334
+ past_key_values: Optional[Cache] = None,
335
+ inputs_embeds: Optional[torch.FloatTensor] = None,
336
+ vision_feature_layer: Optional[Union[int, list[int]]] = None,
337
+ vision_feature_select_strategy: Optional[str] = None,
338
+ use_cache: Optional[bool] = None,
339
+ output_attentions: Optional[bool] = None,
340
+ output_hidden_states: Optional[bool] = None,
341
+ return_dict: Optional[bool] = None,
342
+ cache_position: Optional[torch.LongTensor] = None,
343
+ **kwargs: Unpack[FlashAttentionKwargs],
344
+ ) -> Union[tuple, VideoLlavaModelOutputWithPast]:
345
+ r"""
346
+ pixel_values_images (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)):
347
+ The tensors corresponding to the input images. Pixel values can be obtained using
348
+ [`AutoImageProcessor`]. See [`VideoLlavaImageProcessor.__call__`] for details ([]`LlavaProcessor`] uses
349
+ [`VideoLlavaImageProcessor`] for processing images).
350
+ """
351
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
352
+ output_hidden_states = (
353
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
354
+ )
355
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
356
+ vision_feature_layer = (
357
+ vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
358
+ )
359
+ vision_feature_select_strategy = (
360
+ vision_feature_select_strategy
361
+ if vision_feature_select_strategy is not None
362
+ else self.config.vision_feature_select_strategy
363
+ )
364
+
365
+ if (input_ids is None) ^ (inputs_embeds is not None):
366
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
367
+
368
+ if inputs_embeds is None:
369
+ inputs_embeds = self.get_input_embeddings()(input_ids)
370
+
371
+ if pixel_values_images is not None:
372
+ image_features = self.get_image_features(
373
+ pixel_values_images,
374
+ vision_feature_layer=vision_feature_layer,
375
+ vision_feature_select_strategy=vision_feature_select_strategy,
376
+ )
377
+ image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
378
+ special_image_mask, _ = self.get_placeholder_mask(
379
+ input_ids, inputs_embeds=inputs_embeds, image_features=image_features
380
+ )
381
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
382
+
383
+ if pixel_values_videos is not None:
384
+ video_features, num_frames = self.get_video_features(
385
+ pixel_values_videos=pixel_values_videos, vision_feature_layer=vision_feature_layer
386
+ )
387
+ video_features = video_features.to(inputs_embeds.device, inputs_embeds.dtype)
388
+ _, special_video_mask = self.get_placeholder_mask(
389
+ input_ids, inputs_embeds=inputs_embeds, video_features=video_features
390
+ )
391
+ inputs_embeds = inputs_embeds.masked_scatter(special_video_mask, video_features)
392
+
393
+ outputs = self.language_model(
394
+ attention_mask=attention_mask,
395
+ position_ids=position_ids,
396
+ past_key_values=past_key_values,
397
+ inputs_embeds=inputs_embeds,
398
+ use_cache=use_cache,
399
+ output_attentions=output_attentions,
400
+ output_hidden_states=output_hidden_states,
401
+ return_dict=True,
402
+ cache_position=cache_position,
403
+ **kwargs,
404
+ )
405
+
406
+ return VideoLlavaModelOutputWithPast(
407
+ last_hidden_state=outputs.last_hidden_state,
408
+ past_key_values=outputs.past_key_values,
409
+ hidden_states=outputs.hidden_states,
410
+ attentions=outputs.attentions,
411
+ image_hidden_states=image_features if pixel_values_images is not None else None,
412
+ video_hidden_states=video_features if pixel_values_videos is not None else None,
413
+ )
414
+
415
+
416
+ @auto_docstring(
417
+ custom_intro="""
418
+ The VideoLlava model which consists of a vision backbone and a language model.
419
+ """
420
+ )
421
+ class VideoLlavaForConditionalGeneration(VideoLlavaPreTrainedModel, GenerationMixin):
422
+ _checkpoint_conversion_mapping = {
423
+ "^language_model.model": "model.language_model",
424
+ "^image_tower": "model.image_tower",
425
+ "^video_tower": "model.video_tower",
426
+ "^multi_modal_projector": "model.multi_modal_projector",
427
+ "^language_model.lm_head": "lm_head",
428
+ }
429
+ _tied_weights_keys = ["lm_head.weight"]
430
+
431
+ def __init__(self, config: VideoLlavaConfig):
432
+ super().__init__(config)
433
+ self.model = VideoLlavaModel(config)
434
+ self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
435
+ self.post_init()
436
+
437
+ def get_input_embeddings(self):
438
+ return self.model.get_input_embeddings()
439
+
440
+ def set_input_embeddings(self, value):
441
+ self.model.set_input_embeddings(value)
442
+
443
+ def get_output_embeddings(self) -> nn.Module:
444
+ return self.lm_head
445
+
446
+ def set_decoder(self, decoder):
447
+ self.model.set_decoder(decoder)
448
+
449
+ def get_decoder(self):
450
+ return self.model.get_decoder()
451
+
452
+ def get_image_features(
453
+ self,
454
+ pixel_values_images: torch.FloatTensor,
455
+ vision_feature_layer: Optional[Union[int, list[int]]] = None,
456
+ vision_feature_select_strategy: Optional[str] = None,
457
+ ):
458
+ return self.model.get_image_features(
459
+ pixel_values_images=pixel_values_images,
460
+ vision_feature_layer=vision_feature_layer,
461
+ vision_feature_select_strategy=vision_feature_select_strategy,
462
+ )
463
+
464
+ # Make modules available through conditional class for BC
465
+ @property
466
+ def language_model(self):
467
+ return self.model.language_model
468
+
469
+ @property
470
+ def video_tower(self):
471
+ return self.model.video_tower
472
+
473
+ @property
474
+ def image_tower(self):
475
+ return self.model.image_tower
476
+
477
+ @property
478
+ def multi_modal_projector(self):
479
+ return self.model.multi_modal_projector
480
+
481
+ @can_return_tuple
482
+ @auto_docstring
483
+ def forward(
484
+ self,
485
+ input_ids: torch.LongTensor = None,
486
+ pixel_values_images: torch.FloatTensor = None,
487
+ pixel_values_videos: torch.FloatTensor = None,
488
+ attention_mask: Optional[torch.Tensor] = None,
489
+ position_ids: Optional[torch.LongTensor] = None,
490
+ past_key_values: Optional[Cache] = None,
491
+ inputs_embeds: Optional[torch.FloatTensor] = None,
492
+ vision_feature_layer: Optional[Union[int, list[int]]] = None,
493
+ vision_feature_select_strategy: Optional[str] = None,
494
+ labels: Optional[torch.LongTensor] = None,
495
+ use_cache: Optional[bool] = None,
496
+ output_attentions: Optional[bool] = None,
497
+ output_hidden_states: Optional[bool] = None,
498
+ return_dict: Optional[bool] = None,
499
+ cache_position: Optional[torch.LongTensor] = None,
500
+ logits_to_keep: Union[int, torch.Tensor] = 0,
501
+ **kwargs: Unpack[TransformersKwargs],
502
+ ) -> Union[tuple, VideoLlavaCausalLMOutputWithPast]:
503
+ r"""
504
+ pixel_values_images (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)):
505
+ The tensors corresponding to the input images. Pixel values can be obtained using
506
+ [`AutoImageProcessor`]. See [`VideoLlavaImageProcessor.__call__`] for details ([]`LlavaProcessor`] uses
507
+ [`VideoLlavaImageProcessor`] for processing images).
508
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
509
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
510
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
511
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
512
+
513
+ Example:
514
+
515
+ ```python
516
+ >>> from PIL import Image
517
+ >>> import requests
518
+ >>> import numpy as np
519
+ >>> import av
520
+ >>> from huggingface_hub import hf_hub_download
521
+ >>> from transformers import VideoLlavaProcessor, VideoLlavaForConditionalGeneration
522
+
523
+
524
+ >>> def read_video_pyav(container, indices):
525
+ ... '''
526
+ ... Decode the video with PyAV decoder.
527
+ ... Args:
528
+ ... container (`av.container.input.InputContainer`): PyAV container.
529
+ ... indices (`list[int]`): List of frame indices to decode.
530
+ ... Returns:
531
+ ... result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).
532
+ ... '''
533
+ ... frames = []
534
+ ... container.seek(0)
535
+ ... start_index = indices[0]
536
+ ... end_index = indices[-1]
537
+ ... for i, frame in enumerate(container.decode(video=0)):
538
+ ... if i > end_index:
539
+ ... break
540
+ ... if i >= start_index and i in indices:
541
+ ... frames.append(frame)
542
+ ... return np.stack([x.to_ndarray(format="rgb24") for x in frames])
543
+
544
+ >>> model = VideoLlavaForConditionalGeneration.from_pretrained("LanguageBind/Video-LLaVA-7B-hf")
545
+ >>> processor = VideoLlavaProcessor.from_pretrained("LanguageBind/Video-LLaVA-7B-hf")
546
+
547
+ >>> prompt = "USER: <video>\nWhy is this video funny? ASSISTANT:"
548
+ >>> video_path = hf_hub_download(repo_id="raushan-testing-hf/videos-test", filename="sample_demo_1.mp4", repo_type="dataset")
549
+ >>> container = av.open(video_path)
550
+
551
+ >>> # sample uniformly 8 frames from the video
552
+ >>> total_frames = container.streams.video[0].frames
553
+ >>> indices = np.arange(0, total_frames, total_frames / 8).astype(int)
554
+ >>> clip = read_video_pyav(container, indices)
555
+
556
+ >>> inputs = processor(text=prompt, videos=clip, return_tensors="pt")
557
+
558
+ >>> # Generate
559
+ >>> generate_ids = model.generate(**inputs, max_length=80)
560
+ >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
561
+ "USER: Why is this video funny? ASSISTANT: The video is funny because the baby is playing with a Wii remote while sitting on the floor, and the baby is wearing glasses.Ъ. The baby's actions are amusing because it is a young child trying to interact with a video game, which is not a typical activity for a"
562
+
563
+ >>> # to generate from image and video mix
564
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
565
+ >>> image = Image.open(requests.get(url, stream=True).raw)
566
+ >>> prompt = [
567
+ ... "USER: <image>\nHow many cats do you see? ASSISTANT:",
568
+ ... "USER: <video>\nWhy is this video funny? ASSISTANT:"
569
+ ... ]
570
+ >>> inputs = processor(text=prompt, images=image, videos=clip, padding=True, return_tensors="pt")
571
+
572
+ >>> # Generate
573
+ >>> generate_ids = model.generate(**inputs, max_length=50)
574
+ >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True)
575
+ ['USER: How many cats do you see? ASSISTANT: There are two cats visible in the image. (or three, if you count the one in the background).', 'USER: Why is this video funny? ASSISTANT: The video is funny because it shows a baby sitting on a bed and playing with a Wii remote.Ъ. The baby is holding the remote']
576
+ ```
577
+ """
578
+
579
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
580
+ output_hidden_states = (
581
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
582
+ )
583
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
584
+ vision_feature_layer = (
585
+ vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
586
+ )
587
+ vision_feature_select_strategy = (
588
+ vision_feature_select_strategy
589
+ if vision_feature_select_strategy is not None
590
+ else self.config.vision_feature_select_strategy
591
+ )
592
+
593
+ outputs = self.model(
594
+ input_ids=input_ids,
595
+ pixel_values_images=pixel_values_images,
596
+ pixel_values_videos=pixel_values_videos,
597
+ attention_mask=attention_mask,
598
+ position_ids=position_ids,
599
+ past_key_values=past_key_values,
600
+ inputs_embeds=inputs_embeds,
601
+ use_cache=use_cache,
602
+ vision_feature_layer=vision_feature_layer,
603
+ vision_feature_select_strategy=vision_feature_select_strategy,
604
+ output_attentions=output_attentions,
605
+ output_hidden_states=output_hidden_states,
606
+ return_dict=True,
607
+ cache_position=cache_position,
608
+ **kwargs,
609
+ )
610
+
611
+ hidden_states = outputs[0]
612
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
613
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
614
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
615
+
616
+ loss = None
617
+ if labels is not None:
618
+ loss = self.loss_function(
619
+ logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs
620
+ )
621
+
622
+ return VideoLlavaCausalLMOutputWithPast(
623
+ loss=loss,
624
+ logits=logits,
625
+ past_key_values=outputs.past_key_values,
626
+ hidden_states=outputs.hidden_states,
627
+ attentions=outputs.attentions,
628
+ image_hidden_states=outputs.image_hidden_states,
629
+ video_hidden_states=outputs.video_hidden_states,
630
+ )
631
+
632
+ def prepare_inputs_for_generation(
633
+ self,
634
+ input_ids,
635
+ past_key_values=None,
636
+ inputs_embeds=None,
637
+ pixel_values_images=None,
638
+ pixel_values_videos=None,
639
+ attention_mask=None,
640
+ cache_position=None,
641
+ logits_to_keep=None,
642
+ **kwargs,
643
+ ):
644
+ # Overwritten -- in specific circumstances we don't want to forward image inputs to the model
645
+
646
+ model_inputs = super().prepare_inputs_for_generation(
647
+ input_ids,
648
+ past_key_values=past_key_values,
649
+ inputs_embeds=inputs_embeds,
650
+ attention_mask=attention_mask,
651
+ cache_position=cache_position,
652
+ logits_to_keep=logits_to_keep,
653
+ **kwargs,
654
+ )
655
+
656
+ if cache_position[0] == 0:
657
+ # If we're in cached decoding stage, pixel values should be None because input ids do not contain special image token anymore
658
+ # Otherwise we need pixel values to be passed to model
659
+ model_inputs["pixel_values_images"] = pixel_values_images
660
+ model_inputs["pixel_values_videos"] = pixel_values_videos
661
+
662
+ return model_inputs
663
+
664
+ @staticmethod
665
+ # Copied from transformers.models.gptj.modeling_gptj.GPTJModel._prepare_4d_causal_attention_mask_with_cache_position
666
+ def _prepare_4d_causal_attention_mask_with_cache_position(
667
+ attention_mask: torch.Tensor,
668
+ sequence_length: int,
669
+ target_length: int,
670
+ dtype: torch.dtype,
671
+ cache_position: torch.Tensor,
672
+ batch_size: int,
673
+ **kwargs,
674
+ ):
675
+ """
676
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
677
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
678
+
679
+ Args:
680
+ attention_mask (`torch.Tensor`):
681
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
682
+ `(batch_size, 1, query_length, key_value_length)`.
683
+ sequence_length (`int`):
684
+ The sequence length being processed.
685
+ target_length (`int`):
686
+ The target length: when generating with static cache, the mask should be as long as the static cache,
687
+ to account for the 0 padding, the part of the cache that is not filled yet.
688
+ dtype (`torch.dtype`):
689
+ The dtype to use for the 4D attention mask.
690
+ cache_position (`torch.Tensor`):
691
+ Indices depicting the position of the input sequence tokens in the sequence.
692
+ batch_size (`torch.Tensor`):
693
+ Batch size.
694
+ """
695
+ if attention_mask is not None and attention_mask.dim() == 4:
696
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
697
+ causal_mask = attention_mask
698
+ else:
699
+ min_dtype = torch.finfo(dtype).min
700
+ causal_mask = torch.full(
701
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=cache_position.device
702
+ )
703
+ if sequence_length != 1:
704
+ causal_mask = torch.triu(causal_mask, diagonal=1)
705
+ causal_mask *= torch.arange(target_length, device=cache_position.device) > cache_position.reshape(-1, 1)
706
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
707
+ if attention_mask is not None:
708
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
709
+ mask_length = attention_mask.shape[-1]
710
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
711
+ causal_mask.device
712
+ )
713
+ padding_mask = padding_mask == 0
714
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
715
+ padding_mask, min_dtype
716
+ )
717
+
718
+ return causal_mask
719
+
720
+
721
+ __all__ = ["VideoLlavaPreTrainedModel", "VideoLlavaModel", "VideoLlavaForConditionalGeneration"]
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/video_llava/processing_video_llava.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The HuggingFace Inc. team.
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
+ Processor class for VideoLlava.
17
+ """
18
+
19
+ from typing import Optional, Union
20
+
21
+ import numpy as np
22
+
23
+ from ...feature_extraction_utils import BatchFeature
24
+ from ...image_utils import ImageInput, get_image_size, to_numpy_array
25
+ from ...processing_utils import ProcessorMixin
26
+ from ...tokenization_utils_base import PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
27
+ from ...utils import TensorType, logging
28
+
29
+
30
+ logger = logging.get_logger(__name__)
31
+
32
+
33
+ class VideoLlavaProcessor(ProcessorMixin):
34
+ r"""
35
+ Constructs a VideoLlava processor which wraps a VideoLlava image processor and a Llava tokenizer into a single processor.
36
+
37
+ [`VideoLlavaProcessor`] offers all the functionalities of [`VideoLlavaImageProcessor`] and [`LlamaTokenizerFast`]. See the
38
+ [`~VideoLlavaProcessor.__call__`] and [`~VideoLlavaProcessor.decode`] for more information.
39
+
40
+ Args:
41
+ image_processor ([`VideoLlavaImageProcessor`], *optional*):
42
+ The image processor is a required input.
43
+ video_processor ([`VideoLlavaVideoProcessor`], *optional*):
44
+ The video processor is a required input.
45
+ tokenizer ([`LlamaTokenizerFast`], *optional*):
46
+ The tokenizer is a required input.
47
+ patch_size (`int`, *optional*, defaults to 14):
48
+ Patch size from the vision tower.
49
+ vision_feature_select_strategy (`str`, *optional*, defaults to `"default"`):
50
+ The feature selection strategy used to select the vision feature from the vision backbone.
51
+ Should be same as in model's config
52
+ image_token (`str`, *optional*, defaults to `"<image>"`):
53
+ Special token used to denote image location.
54
+ video_token (`str`, *optional*, defaults to `"<video>"`):
55
+ Special token used to denote video location.
56
+ chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
57
+ in a chat into a tokenizable string.
58
+ num_additional_image_tokens (`int`, *optional*, defaults to 1):
59
+ Number of additional tokens added to the image embeddings, such as CLS (+1). If the backbone has no CLS or other
60
+ extra tokens appended, no need to set this arg.
61
+ """
62
+
63
+ attributes = ["image_processor", "video_processor", "tokenizer"]
64
+ image_processor_class = "VideoLlavaImageProcessor"
65
+ video_processor_class = "AutoVideoProcessor"
66
+ tokenizer_class = "AutoTokenizer"
67
+
68
+ def __init__(
69
+ self,
70
+ image_processor=None,
71
+ video_processor=None,
72
+ tokenizer=None,
73
+ patch_size=14,
74
+ vision_feature_select_strategy="default",
75
+ image_token="<image>", # set the default and let users change if they have peculiar special tokens in rare cases
76
+ video_token="<video>",
77
+ chat_template=None,
78
+ num_additional_image_tokens=1,
79
+ **kwargs,
80
+ ):
81
+ self.patch_size = patch_size
82
+ self.num_additional_image_tokens = num_additional_image_tokens
83
+ self.vision_feature_select_strategy = vision_feature_select_strategy
84
+ self.image_token = tokenizer.image_token if hasattr(tokenizer, "image_token") else image_token
85
+ self.video_token = tokenizer.video_token if hasattr(tokenizer, "video_token") else video_token
86
+ self.image_token_id = tokenizer.convert_tokens_to_ids(self.image_token)
87
+ self.video_token_id = tokenizer.convert_tokens_to_ids(self.video_token)
88
+ super().__init__(image_processor, video_processor, tokenizer, chat_template=chat_template)
89
+
90
+ def __call__(
91
+ self,
92
+ text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None,
93
+ images: ImageInput = None,
94
+ videos: ImageInput = None,
95
+ padding: Union[bool, str, PaddingStrategy] = False,
96
+ truncation: Union[bool, str, TruncationStrategy] = None,
97
+ max_length=None,
98
+ return_tensors: Optional[Union[str, TensorType]] = TensorType.PYTORCH,
99
+ ) -> BatchFeature:
100
+ """
101
+ Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
102
+ and `kwargs` arguments to LlamaTokenizerFast's [`~LlamaTokenizerFast.__call__`] if `text` is not `None` to encode
103
+ the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to
104
+ VideoLlavaImageProcessor's [`~VideoLlavaImageProcessor.__call__`] if `images` is not `None`. Please refer to the docstring
105
+ of the above two methods for more information.
106
+
107
+ Args:
108
+ text (`TextInput`, `PreTokenizedInput`, `list[TextInput]`, `list[PreTokenizedInput]`):
109
+ The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
110
+ (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
111
+ `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
112
+ images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
113
+ The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
114
+ tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape (C, H, W), where C is a
115
+ number of channels, H and W are image height and width.
116
+ videos (`np.ndarray`, `torch.Tensor`, `list[np.ndarray]`, `list[torch.Tensor]`):
117
+ Video frames to preprocess. Expects a single or batch of video frames in NumPy array or PyTorch
118
+ tensor. Each video should be of shape (T, C, H, W), where T is number of frames, C is
119
+ number of channels, H and W are image height and width.
120
+ padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):
121
+ Select a strategy to pad the returned sequences (according to the model's padding side and padding
122
+ index) among:
123
+ - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
124
+ sequence if provided).
125
+ - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
126
+ acceptable input length for the model if that argument is not provided.
127
+ - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
128
+ lengths).
129
+ max_length (`int`, *optional*):
130
+ Maximum length of the returned list and optionally padding length (see above).
131
+ truncation (`bool`, *optional*):
132
+ Activates truncation to cut input sequences longer than `max_length` to `max_length`.
133
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
134
+ If set, will return tensors of a particular framework. Acceptable values are:
135
+
136
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
137
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
138
+ - `'np'`: Return NumPy `np.ndarray` objects.
139
+ - `'jax'`: Return JAX `jnp.ndarray` objects.
140
+
141
+ Returns:
142
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
143
+
144
+ - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
145
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
146
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
147
+ `None`).
148
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
149
+ - **pixel_values_videos** -- Pixel values to be fed to a model. Returned when `videos` is not `None`.
150
+ """
151
+
152
+ if isinstance(text, str):
153
+ text = [text]
154
+ elif not isinstance(text, list) and not isinstance(text[0], str):
155
+ raise TypeError("Invalid input text. Please provide a string, or a list of strings")
156
+
157
+ data = {}
158
+ if images is not None:
159
+ encoded_images = self.image_processor(images=images, return_tensors=return_tensors)
160
+ data.update(encoded_images)
161
+
162
+ height, width = get_image_size(to_numpy_array(encoded_images.get("pixel_values_images")[0]))
163
+ num_image_tokens = (height // self.patch_size) * (width // self.patch_size)
164
+ num_image_tokens += self.num_additional_image_tokens
165
+ if self.vision_feature_select_strategy == "default":
166
+ num_image_tokens -= 1
167
+ text = [sample.replace(self.image_token, self.image_token * num_image_tokens) for sample in text]
168
+
169
+ if videos is not None:
170
+ encoded_videos = self.video_processor(videos=videos, return_tensors=return_tensors)
171
+ data.update(encoded_videos)
172
+
173
+ one_video = encoded_videos.get("pixel_values_videos")[0]
174
+ if isinstance(encoded_videos.get("pixel_values_videos")[0], (list, tuple)):
175
+ one_video = np.array(one_video)
176
+ else:
177
+ one_video = to_numpy_array(one_video)
178
+ height, width = get_image_size(one_video[0])
179
+ num_frames = one_video.shape[0] # frame dim is always after batch dim
180
+
181
+ num_image_tokens = (height // self.patch_size) * (width // self.patch_size)
182
+ num_image_tokens += self.num_additional_image_tokens
183
+ num_video_tokens = num_image_tokens * num_frames
184
+ text = [sample.replace(self.video_token, self.video_token * num_video_tokens) for sample in text]
185
+
186
+ text_inputs = self.tokenizer(
187
+ text,
188
+ return_tensors=None,
189
+ padding=padding,
190
+ truncation=truncation,
191
+ max_length=max_length,
192
+ )
193
+ self._check_special_mm_tokens(text, text_inputs, modalities=["image", "video"])
194
+
195
+ data.update(text_inputs)
196
+
197
+ return BatchFeature(data=data, tensor_type=return_tensors)
198
+
199
+ # Copied from transformers.models.clip.processing_clip.CLIPProcessor.batch_decode with CLIP->Llama
200
+ def batch_decode(self, *args, **kwargs):
201
+ """
202
+ This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
203
+ refer to the docstring of this method for more information.
204
+ """
205
+ return self.tokenizer.batch_decode(*args, **kwargs)
206
+
207
+ # Copied from transformers.models.clip.processing_clip.CLIPProcessor.decode with CLIP->Llama
208
+ def decode(self, *args, **kwargs):
209
+ """
210
+ This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
211
+ the docstring of this method for more information.
212
+ """
213
+ return self.tokenizer.decode(*args, **kwargs)
214
+
215
+ @property
216
+ # Copied from transformers.models.clip.processing_clip.CLIPProcessor.model_input_names
217
+ def model_input_names(self):
218
+ tokenizer_input_names = self.tokenizer.model_input_names
219
+ image_processor_input_names = self.image_processor.model_input_names
220
+ return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
221
+
222
+
223
+ __all__ = ["VideoLlavaProcessor"]
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/video_llava/video_processing_video_llava.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 The HuggingFace Inc. team. 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
+ """Video processor class for Video-LLaVA."""
16
+
17
+ from ...image_utils import (
18
+ OPENAI_CLIP_MEAN,
19
+ OPENAI_CLIP_STD,
20
+ )
21
+ from ...processing_utils import Unpack, VideosKwargs
22
+ from ...utils import is_vision_available
23
+ from ...utils.import_utils import requires
24
+ from ...video_processing_utils import (
25
+ BaseVideoProcessor,
26
+ )
27
+
28
+
29
+ if is_vision_available():
30
+ from ...image_utils import PILImageResampling
31
+
32
+
33
+ class VideoLlavaFastVideoProcessorInitKwargs(VideosKwargs): ...
34
+
35
+
36
+ @requires(backends=("torchvision",))
37
+ class VideoLlavaVideoProcessor(BaseVideoProcessor):
38
+ resample = PILImageResampling.BICUBIC
39
+ image_mean = OPENAI_CLIP_MEAN
40
+ image_std = OPENAI_CLIP_STD
41
+ size = {"shortest_edge": 224}
42
+ default_to_square = False
43
+ crop_size = {"height": 224, "width": 224}
44
+ do_resize = True
45
+ do_center_crop = True
46
+ do_rescale = True
47
+ do_normalize = True
48
+ do_convert_rgb = True
49
+ do_sample_frames = False # Set to False for BC, recommended to set `True` in new models
50
+ valid_kwargs = VideoLlavaFastVideoProcessorInitKwargs
51
+ model_input_names = ["pixel_values_videos"]
52
+
53
+ def __init__(self, **kwargs: Unpack[VideoLlavaFastVideoProcessorInitKwargs]):
54
+ super().__init__(**kwargs)
55
+
56
+
57
+ __all__ = ["VideoLlavaVideoProcessor"]
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/videomae/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. 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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_videomae import *
22
+ from .feature_extraction_videomae import *
23
+ from .image_processing_videomae import *
24
+ from .modeling_videomae import *
25
+ else:
26
+ import sys
27
+
28
+ _file = globals()["__file__"]
29
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/videomae/configuration_videomae.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team. 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
+ """VideoMAE model configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+ from ...utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ class VideoMAEConfig(PretrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`VideoMAEModel`]. It is used to instantiate a
27
+ VideoMAE model according to the specified arguments, defining the model architecture. Instantiating a configuration
28
+ with the defaults will yield a similar configuration to that of the VideoMAE
29
+ [MCG-NJU/videomae-base](https://huggingface.co/MCG-NJU/videomae-base) architecture.
30
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+ Args:
35
+ image_size (`int`, *optional*, defaults to 224):
36
+ The size (resolution) of each image.
37
+ patch_size (`int`, *optional*, defaults to 16):
38
+ The size (resolution) of each patch.
39
+ num_channels (`int`, *optional*, defaults to 3):
40
+ The number of input channels.
41
+ num_frames (`int`, *optional*, defaults to 16):
42
+ The number of frames in each video.
43
+ tubelet_size (`int`, *optional*, defaults to 2):
44
+ The number of tubelets.
45
+ hidden_size (`int`, *optional*, defaults to 768):
46
+ Dimensionality of the encoder layers and the pooler layer.
47
+ num_hidden_layers (`int`, *optional*, defaults to 12):
48
+ Number of hidden layers in the Transformer encoder.
49
+ num_attention_heads (`int`, *optional*, defaults to 12):
50
+ Number of attention heads for each attention layer in the Transformer encoder.
51
+ intermediate_size (`int`, *optional*, defaults to 3072):
52
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
53
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
54
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
55
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
56
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
57
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
58
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
59
+ The dropout ratio for the attention probabilities.
60
+ initializer_range (`float`, *optional*, defaults to 0.02):
61
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
62
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
63
+ The epsilon used by the layer normalization layers.
64
+ qkv_bias (`bool`, *optional*, defaults to `True`):
65
+ Whether to add a bias to the queries, keys and values.
66
+ use_mean_pooling (`bool`, *optional*, defaults to `True`):
67
+ Whether to mean pool the final hidden states instead of using the final hidden state of the [CLS] token.
68
+ decoder_num_attention_heads (`int`, *optional*, defaults to 6):
69
+ Number of attention heads for each attention layer in the decoder.
70
+ decoder_hidden_size (`int`, *optional*, defaults to 384):
71
+ Dimensionality of the decoder.
72
+ decoder_num_hidden_layers (`int`, *optional*, defaults to 4):
73
+ Number of hidden layers in the decoder.
74
+ decoder_intermediate_size (`int`, *optional*, defaults to 1536):
75
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the decoder.
76
+ norm_pix_loss (`bool`, *optional*, defaults to `True`):
77
+ Whether to normalize the target patch pixels.
78
+
79
+ Example:
80
+
81
+ ```python
82
+ >>> from transformers import VideoMAEConfig, VideoMAEModel
83
+
84
+ >>> # Initializing a VideoMAE videomae-base style configuration
85
+ >>> configuration = VideoMAEConfig()
86
+
87
+ >>> # Randomly initializing a model from the configuration
88
+ >>> model = VideoMAEModel(configuration)
89
+
90
+ >>> # Accessing the model configuration
91
+ >>> configuration = model.config
92
+ ```"""
93
+
94
+ model_type = "videomae"
95
+
96
+ def __init__(
97
+ self,
98
+ image_size=224,
99
+ patch_size=16,
100
+ num_channels=3,
101
+ num_frames=16,
102
+ tubelet_size=2,
103
+ hidden_size=768,
104
+ num_hidden_layers=12,
105
+ num_attention_heads=12,
106
+ intermediate_size=3072,
107
+ hidden_act="gelu",
108
+ hidden_dropout_prob=0.0,
109
+ attention_probs_dropout_prob=0.0,
110
+ initializer_range=0.02,
111
+ layer_norm_eps=1e-12,
112
+ qkv_bias=True,
113
+ use_mean_pooling=True,
114
+ decoder_num_attention_heads=6,
115
+ decoder_hidden_size=384,
116
+ decoder_num_hidden_layers=4,
117
+ decoder_intermediate_size=1536,
118
+ norm_pix_loss=True,
119
+ **kwargs,
120
+ ):
121
+ super().__init__(**kwargs)
122
+
123
+ self.image_size = image_size
124
+ self.patch_size = patch_size
125
+ self.num_channels = num_channels
126
+ self.num_frames = num_frames
127
+ self.tubelet_size = tubelet_size
128
+
129
+ self.hidden_size = hidden_size
130
+ self.num_hidden_layers = num_hidden_layers
131
+ self.num_attention_heads = num_attention_heads
132
+ self.intermediate_size = intermediate_size
133
+ self.hidden_act = hidden_act
134
+ self.hidden_dropout_prob = hidden_dropout_prob
135
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
136
+ self.initializer_range = initializer_range
137
+ self.layer_norm_eps = layer_norm_eps
138
+ self.qkv_bias = qkv_bias
139
+ self.use_mean_pooling = use_mean_pooling
140
+
141
+ self.decoder_num_attention_heads = decoder_num_attention_heads
142
+ self.decoder_hidden_size = decoder_hidden_size
143
+ self.decoder_num_hidden_layers = decoder_num_hidden_layers
144
+ self.decoder_intermediate_size = decoder_intermediate_size
145
+ self.norm_pix_loss = norm_pix_loss
146
+
147
+
148
+ __all__ = ["VideoMAEConfig"]
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/videomae/convert_videomae_to_pytorch.py ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team.
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
+ """Convert VideoMAE checkpoints from the original repository: https://github.com/MCG-NJU/VideoMAE"""
16
+
17
+ import argparse
18
+ import json
19
+
20
+ import gdown
21
+ import numpy as np
22
+ import torch
23
+ from huggingface_hub import hf_hub_download
24
+
25
+ from transformers import (
26
+ VideoMAEConfig,
27
+ VideoMAEForPreTraining,
28
+ VideoMAEForVideoClassification,
29
+ VideoMAEImageProcessor,
30
+ )
31
+
32
+
33
+ def get_videomae_config(model_name):
34
+ config = VideoMAEConfig()
35
+
36
+ set_architecture_configs(model_name, config)
37
+
38
+ if "finetuned" not in model_name:
39
+ config.use_mean_pooling = False
40
+
41
+ if "finetuned" in model_name:
42
+ repo_id = "huggingface/label-files"
43
+ if "kinetics" in model_name:
44
+ config.num_labels = 400
45
+ filename = "kinetics400-id2label.json"
46
+ elif "ssv2" in model_name:
47
+ config.num_labels = 174
48
+ filename = "something-something-v2-id2label.json"
49
+ else:
50
+ raise ValueError("Model name should either contain 'kinetics' or 'ssv2' in case it's fine-tuned.")
51
+ id2label = json.load(open(hf_hub_download(repo_id, filename, repo_type="dataset"), "r"))
52
+ id2label = {int(k): v for k, v in id2label.items()}
53
+ config.id2label = id2label
54
+ config.label2id = {v: k for k, v in id2label.items()}
55
+
56
+ return config
57
+
58
+
59
+ def set_architecture_configs(model_name, config):
60
+ if "small" in model_name:
61
+ config.hidden_size = 384
62
+ config.intermediate_size = 1536
63
+ config.num_hidden_layers = 12
64
+ config.num_attention_heads = 16
65
+ config.decoder_num_hidden_layers = 12
66
+ config.decoder_num_attention_heads = 3
67
+ config.decoder_hidden_size = 192
68
+ config.decoder_intermediate_size = 768
69
+ elif "large" in model_name:
70
+ config.hidden_size = 1024
71
+ config.intermediate_size = 4096
72
+ config.num_hidden_layers = 24
73
+ config.num_attention_heads = 16
74
+ config.decoder_num_hidden_layers = 12
75
+ config.decoder_num_attention_heads = 8
76
+ config.decoder_hidden_size = 512
77
+ config.decoder_intermediate_size = 2048
78
+ elif "huge" in model_name:
79
+ config.hidden_size = 1280
80
+ config.intermediate_size = 5120
81
+ config.num_hidden_layers = 32
82
+ config.num_attention_heads = 16
83
+ config.decoder_num_hidden_layers = 12
84
+ config.decoder_num_attention_heads = 8
85
+ config.decoder_hidden_size = 640
86
+ config.decoder_intermediate_size = 2560
87
+ elif "base" not in model_name:
88
+ raise ValueError('Model name should include either "small", "base", "large", or "huge"')
89
+
90
+
91
+ def rename_key(name):
92
+ if "encoder." in name:
93
+ name = name.replace("encoder.", "")
94
+ if "cls_token" in name:
95
+ name = name.replace("cls_token", "videomae.embeddings.cls_token")
96
+ if "decoder_pos_embed" in name:
97
+ name = name.replace("decoder_pos_embed", "decoder.decoder_pos_embed")
98
+ if "pos_embed" in name and "decoder" not in name:
99
+ name = name.replace("pos_embed", "videomae.embeddings.position_embeddings")
100
+ if "patch_embed.proj" in name:
101
+ name = name.replace("patch_embed.proj", "videomae.embeddings.patch_embeddings.projection")
102
+ if "patch_embed.norm" in name:
103
+ name = name.replace("patch_embed.norm", "videomae.embeddings.norm")
104
+ if "decoder.blocks" in name:
105
+ name = name.replace("decoder.blocks", "decoder.decoder_layers")
106
+ if "blocks" in name:
107
+ name = name.replace("blocks", "videomae.encoder.layer")
108
+ if "attn.proj" in name:
109
+ name = name.replace("attn.proj", "attention.output.dense")
110
+ if "attn" in name and "bias" not in name:
111
+ name = name.replace("attn", "attention.self")
112
+ if "attn" in name:
113
+ name = name.replace("attn", "attention.attention")
114
+ if "norm1" in name:
115
+ name = name.replace("norm1", "layernorm_before")
116
+ if "norm2" in name:
117
+ name = name.replace("norm2", "layernorm_after")
118
+ if "mlp.fc1" in name:
119
+ name = name.replace("mlp.fc1", "intermediate.dense")
120
+ if "mlp.fc2" in name:
121
+ name = name.replace("mlp.fc2", "output.dense")
122
+ if "decoder_embed" in name:
123
+ name = name.replace("decoder_embed", "decoder.decoder_embed")
124
+ if "decoder_norm" in name:
125
+ name = name.replace("decoder_norm", "decoder.decoder_norm")
126
+ if "decoder_pred" in name:
127
+ name = name.replace("decoder_pred", "decoder.decoder_pred")
128
+ if "norm.weight" in name and "decoder" not in name and "fc" not in name:
129
+ name = name.replace("norm.weight", "videomae.layernorm.weight")
130
+ if "norm.bias" in name and "decoder" not in name and "fc" not in name:
131
+ name = name.replace("norm.bias", "videomae.layernorm.bias")
132
+ if "head" in name and "decoder" not in name:
133
+ name = name.replace("head", "classifier")
134
+
135
+ return name
136
+
137
+
138
+ def convert_state_dict(orig_state_dict, config):
139
+ for key in orig_state_dict.copy():
140
+ val = orig_state_dict.pop(key)
141
+
142
+ if key.startswith("encoder."):
143
+ key = key.replace("encoder.", "")
144
+
145
+ if "qkv" in key:
146
+ key_split = key.split(".")
147
+ if key.startswith("decoder.blocks"):
148
+ dim = config.decoder_hidden_size
149
+ layer_num = int(key_split[2])
150
+ prefix = "decoder.decoder_layers."
151
+ if "weight" in key:
152
+ orig_state_dict[f"{prefix}{layer_num}.attention.attention.query.weight"] = val[:dim, :]
153
+ orig_state_dict[f"{prefix}{layer_num}.attention.attention.key.weight"] = val[dim : dim * 2, :]
154
+ orig_state_dict[f"{prefix}{layer_num}.attention.attention.value.weight"] = val[-dim:, :]
155
+ else:
156
+ dim = config.hidden_size
157
+ layer_num = int(key_split[1])
158
+ prefix = "videomae.encoder.layer."
159
+ if "weight" in key:
160
+ orig_state_dict[f"{prefix}{layer_num}.attention.attention.query.weight"] = val[:dim, :]
161
+ orig_state_dict[f"{prefix}{layer_num}.attention.attention.key.weight"] = val[dim : dim * 2, :]
162
+ orig_state_dict[f"{prefix}{layer_num}.attention.attention.value.weight"] = val[-dim:, :]
163
+ else:
164
+ orig_state_dict[rename_key(key)] = val
165
+
166
+ return orig_state_dict
167
+
168
+
169
+ # We will verify our results on a video of eating spaghetti
170
+ # Frame indices used: [164 168 172 176 181 185 189 193 198 202 206 210 215 219 223 227]
171
+ def prepare_video():
172
+ file = hf_hub_download(
173
+ repo_id="hf-internal-testing/spaghetti-video", filename="eating_spaghetti.npy", repo_type="dataset"
174
+ )
175
+ video = np.load(file)
176
+ return list(video)
177
+
178
+
179
+ def convert_videomae_checkpoint(checkpoint_url, pytorch_dump_folder_path, model_name, push_to_hub):
180
+ config = get_videomae_config(model_name)
181
+
182
+ if "finetuned" in model_name:
183
+ model = VideoMAEForVideoClassification(config)
184
+ else:
185
+ model = VideoMAEForPreTraining(config)
186
+
187
+ # download original checkpoint, hosted on Google Drive
188
+ output = "pytorch_model.bin"
189
+ gdown.cached_download(checkpoint_url, output, quiet=False)
190
+ files = torch.load(output, map_location="cpu", weights_only=True)
191
+ if "model" in files:
192
+ state_dict = files["model"]
193
+ else:
194
+ state_dict = files["module"]
195
+ new_state_dict = convert_state_dict(state_dict, config)
196
+
197
+ model.load_state_dict(new_state_dict)
198
+ model.eval()
199
+
200
+ # verify model on basic input
201
+ image_processor = VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5], image_std=[0.5, 0.5, 0.5])
202
+ video = prepare_video()
203
+ inputs = image_processor(video, return_tensors="pt")
204
+
205
+ if "finetuned" not in model_name:
206
+ local_path = hf_hub_download(repo_id="hf-internal-testing/bool-masked-pos", filename="bool_masked_pos.pt")
207
+ inputs["bool_masked_pos"] = torch.load(local_path, weights_only=True)
208
+
209
+ outputs = model(**inputs)
210
+ logits = outputs.logits
211
+
212
+ model_names = [
213
+ "videomae-small-finetuned-kinetics",
214
+ "videomae-small-finetuned-ssv2",
215
+ # Kinetics-400 checkpoints (short = pretrained only for 800 epochs instead of 1600)
216
+ "videomae-base-short",
217
+ "videomae-base-short-finetuned-kinetics",
218
+ "videomae-base",
219
+ "videomae-base-finetuned-kinetics",
220
+ "videomae-large",
221
+ "videomae-large-finetuned-kinetics",
222
+ "videomae-huge-finetuned-kinetics",
223
+ # Something-Something-v2 checkpoints (short = pretrained only for 800 epochs instead of 2400)
224
+ "videomae-base-short-ssv2",
225
+ "videomae-base-short-finetuned-ssv2",
226
+ "videomae-base-ssv2",
227
+ "videomae-base-finetuned-ssv2",
228
+ ]
229
+
230
+ # NOTE: logits were tested with image_mean and image_std equal to [0.5, 0.5, 0.5] and [0.5, 0.5, 0.5]
231
+ if model_name == "videomae-small-finetuned-kinetics":
232
+ expected_shape = torch.Size([1, 400])
233
+ expected_slice = torch.tensor([-0.9291, -0.4061, -0.9307])
234
+ elif model_name == "videomae-small-finetuned-ssv2":
235
+ expected_shape = torch.Size([1, 174])
236
+ expected_slice = torch.tensor([0.2671, -0.4689, -0.8235])
237
+ elif model_name == "videomae-base":
238
+ expected_shape = torch.Size([1, 1408, 1536])
239
+ expected_slice = torch.tensor([[0.7739, 0.7968, 0.7089], [0.6701, 0.7487, 0.6209], [0.4287, 0.5158, 0.4773]])
240
+ elif model_name == "videomae-base-short":
241
+ expected_shape = torch.Size([1, 1408, 1536])
242
+ expected_slice = torch.tensor([[0.7994, 0.9612, 0.8508], [0.7401, 0.8958, 0.8302], [0.5862, 0.7468, 0.7325]])
243
+ # we verified the loss both for normalized and unnormalized targets for this one
244
+ expected_loss = torch.tensor([0.5142]) if config.norm_pix_loss else torch.tensor([0.6469])
245
+ elif model_name == "videomae-large":
246
+ expected_shape = torch.Size([1, 1408, 1536])
247
+ expected_slice = torch.tensor([[0.7149, 0.7997, 0.6966], [0.6768, 0.7869, 0.6948], [0.5139, 0.6221, 0.5605]])
248
+ elif model_name == "videomae-large-finetuned-kinetics":
249
+ expected_shape = torch.Size([1, 400])
250
+ expected_slice = torch.tensor([0.0771, 0.0011, -0.3625])
251
+ elif model_name == "videomae-huge-finetuned-kinetics":
252
+ expected_shape = torch.Size([1, 400])
253
+ expected_slice = torch.tensor([0.2433, 0.1632, -0.4894])
254
+ elif model_name == "videomae-base-short-finetuned-kinetics":
255
+ expected_shape = torch.Size([1, 400])
256
+ expected_slice = torch.tensor([0.6588, 0.0990, -0.2493])
257
+ elif model_name == "videomae-base-finetuned-kinetics":
258
+ expected_shape = torch.Size([1, 400])
259
+ expected_slice = torch.tensor([0.3669, -0.0688, -0.2421])
260
+ elif model_name == "videomae-base-short-ssv2":
261
+ expected_shape = torch.Size([1, 1408, 1536])
262
+ expected_slice = torch.tensor([[0.4712, 0.5296, 0.5786], [0.2278, 0.2729, 0.4026], [0.0352, 0.0730, 0.2506]])
263
+ elif model_name == "videomae-base-short-finetuned-ssv2":
264
+ expected_shape = torch.Size([1, 174])
265
+ expected_slice = torch.tensor([-0.0537, -0.1539, -0.3266])
266
+ elif model_name == "videomae-base-ssv2":
267
+ expected_shape = torch.Size([1, 1408, 1536])
268
+ expected_slice = torch.tensor([[0.8131, 0.8727, 0.8546], [0.7366, 0.9377, 0.8870], [0.5935, 0.8874, 0.8564]])
269
+ elif model_name == "videomae-base-finetuned-ssv2":
270
+ expected_shape = torch.Size([1, 174])
271
+ expected_slice = torch.tensor([0.1961, -0.8337, -0.6389])
272
+ else:
273
+ raise ValueError(f"Model name not supported. Should be one of {model_names}")
274
+
275
+ # verify logits
276
+ assert logits.shape == expected_shape
277
+ if "finetuned" in model_name:
278
+ assert torch.allclose(logits[0, :3], expected_slice, atol=1e-4)
279
+ else:
280
+ print("Logits:", logits[0, :3, :3])
281
+ assert torch.allclose(logits[0, :3, :3], expected_slice, atol=1e-4)
282
+ print("Logits ok!")
283
+
284
+ # verify loss, if applicable
285
+ if model_name == "videomae-base-short":
286
+ loss = outputs.loss
287
+ assert torch.allclose(loss, expected_loss, atol=1e-4)
288
+ print("Loss ok!")
289
+
290
+ if pytorch_dump_folder_path is not None:
291
+ print(f"Saving model and image processor to {pytorch_dump_folder_path}")
292
+ image_processor.save_pretrained(pytorch_dump_folder_path)
293
+ model.save_pretrained(pytorch_dump_folder_path)
294
+
295
+ if push_to_hub:
296
+ print("Pushing to the hub...")
297
+ model.push_to_hub(model_name, organization="nielsr")
298
+
299
+
300
+ if __name__ == "__main__":
301
+ parser = argparse.ArgumentParser()
302
+ # Required parameters
303
+ parser.add_argument(
304
+ "--checkpoint_url",
305
+ default="https://drive.google.com/u/1/uc?id=1tEhLyskjb755TJ65ptsrafUG2llSwQE1&amp;export=download&amp;confirm=t&amp;uuid=aa3276eb-fb7e-482a-adec-dc7171df14c4",
306
+ type=str,
307
+ help=(
308
+ "URL of the original PyTorch checkpoint (on Google Drive) you'd like to convert. Should be a direct"
309
+ " download link."
310
+ ),
311
+ )
312
+ parser.add_argument(
313
+ "--pytorch_dump_folder_path",
314
+ default="/Users/nielsrogge/Documents/VideoMAE/Test",
315
+ type=str,
316
+ help="Path to the output PyTorch model directory.",
317
+ )
318
+ parser.add_argument("--model_name", default="videomae-base", type=str, help="Name of the model.")
319
+ parser.add_argument(
320
+ "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub."
321
+ )
322
+
323
+ args = parser.parse_args()
324
+ convert_videomae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.model_name, args.push_to_hub)
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/videomae/feature_extraction_videomae.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team. 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
+ """Feature extractor class for VideoMAE."""
16
+
17
+ import warnings
18
+
19
+ from ...utils import logging
20
+ from ...utils.import_utils import requires
21
+ from .image_processing_videomae import VideoMAEImageProcessor
22
+
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+
27
+ @requires(backends=("vision",))
28
+ class VideoMAEFeatureExtractor(VideoMAEImageProcessor):
29
+ def __init__(self, *args, **kwargs) -> None:
30
+ warnings.warn(
31
+ "The class VideoMAEFeatureExtractor is deprecated and will be removed in version 5 of Transformers."
32
+ " Please use VideoMAEImageProcessor instead.",
33
+ FutureWarning,
34
+ )
35
+ super().__init__(*args, **kwargs)
36
+
37
+
38
+ __all__ = ["VideoMAEFeatureExtractor"]
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/videomae/image_processing_videomae.py ADDED
@@ -0,0 +1,350 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team. 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
+ """Image processor class for VideoMAE."""
16
+
17
+ from typing import Optional, Union
18
+
19
+ import numpy as np
20
+
21
+ from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
22
+ from ...image_transforms import (
23
+ get_resize_output_image_size,
24
+ resize,
25
+ to_channel_dimension_format,
26
+ )
27
+ from ...image_utils import (
28
+ IMAGENET_STANDARD_MEAN,
29
+ IMAGENET_STANDARD_STD,
30
+ ChannelDimension,
31
+ ImageInput,
32
+ PILImageResampling,
33
+ infer_channel_dimension_format,
34
+ is_scaled_image,
35
+ is_valid_image,
36
+ to_numpy_array,
37
+ valid_images,
38
+ validate_preprocess_arguments,
39
+ )
40
+ from ...utils import TensorType, filter_out_non_signature_kwargs, is_vision_available, logging
41
+ from ...utils.import_utils import requires
42
+
43
+
44
+ if is_vision_available():
45
+ import PIL
46
+
47
+
48
+ logger = logging.get_logger(__name__)
49
+
50
+
51
+ def make_batched(videos) -> list[list[ImageInput]]:
52
+ if isinstance(videos, (list, tuple)) and isinstance(videos[0], (list, tuple)) and is_valid_image(videos[0][0]):
53
+ return videos
54
+
55
+ elif isinstance(videos, (list, tuple)) and is_valid_image(videos[0]):
56
+ return [videos]
57
+
58
+ elif is_valid_image(videos):
59
+ return [[videos]]
60
+
61
+ raise ValueError(f"Could not make batched video from {videos}")
62
+
63
+
64
+ @requires(backends=("vision",))
65
+ class VideoMAEImageProcessor(BaseImageProcessor):
66
+ r"""
67
+ Constructs a VideoMAE image processor.
68
+
69
+ Args:
70
+ do_resize (`bool`, *optional*, defaults to `True`):
71
+ Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by the
72
+ `do_resize` parameter in the `preprocess` method.
73
+ size (`dict[str, int]` *optional*, defaults to `{"shortest_edge": 224}`):
74
+ Size of the output image after resizing. The shortest edge of the image will be resized to
75
+ `size["shortest_edge"]` while maintaining the aspect ratio of the original image. Can be overridden by
76
+ `size` in the `preprocess` method.
77
+ resample (`PILImageResampling`, *optional*, defaults to `Resampling.BILINEAR`):
78
+ Resampling filter to use if resizing the image. Can be overridden by the `resample` parameter in the
79
+ `preprocess` method.
80
+ do_center_crop (`bool`, *optional*, defaults to `True`):
81
+ Whether to center crop the image to the specified `crop_size`. Can be overridden by the `do_center_crop`
82
+ parameter in the `preprocess` method.
83
+ crop_size (`dict[str, int]`, *optional*, defaults to `{"height": 224, "width": 224}`):
84
+ Size of the image after applying the center crop. Can be overridden by the `crop_size` parameter in the
85
+ `preprocess` method.
86
+ do_rescale (`bool`, *optional*, defaults to `True`):
87
+ Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the `do_rescale`
88
+ parameter in the `preprocess` method.
89
+ rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
90
+ Defines the scale factor to use if rescaling the image. Can be overridden by the `rescale_factor` parameter
91
+ in the `preprocess` method.
92
+ do_normalize (`bool`, *optional*, defaults to `True`):
93
+ Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
94
+ method.
95
+ image_mean (`float` or `list[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
96
+ Mean to use if normalizing the image. This is a float or list of floats the length of the number of
97
+ channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
98
+ image_std (`float` or `list[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
99
+ Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
100
+ number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
101
+ """
102
+
103
+ model_input_names = ["pixel_values"]
104
+
105
+ def __init__(
106
+ self,
107
+ do_resize: bool = True,
108
+ size: Optional[dict[str, int]] = None,
109
+ resample: PILImageResampling = PILImageResampling.BILINEAR,
110
+ do_center_crop: bool = True,
111
+ crop_size: Optional[dict[str, int]] = None,
112
+ do_rescale: bool = True,
113
+ rescale_factor: Union[int, float] = 1 / 255,
114
+ do_normalize: bool = True,
115
+ image_mean: Optional[Union[float, list[float]]] = None,
116
+ image_std: Optional[Union[float, list[float]]] = None,
117
+ **kwargs,
118
+ ) -> None:
119
+ super().__init__(**kwargs)
120
+ size = size if size is not None else {"shortest_edge": 224}
121
+ size = get_size_dict(size, default_to_square=False)
122
+ crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
123
+ crop_size = get_size_dict(crop_size, param_name="crop_size")
124
+
125
+ self.do_resize = do_resize
126
+ self.size = size
127
+ self.do_center_crop = do_center_crop
128
+ self.crop_size = crop_size
129
+ self.resample = resample
130
+ self.do_rescale = do_rescale
131
+ self.rescale_factor = rescale_factor
132
+ self.do_normalize = do_normalize
133
+ self.image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
134
+ self.image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD
135
+
136
+ def resize(
137
+ self,
138
+ image: np.ndarray,
139
+ size: dict[str, int],
140
+ resample: PILImageResampling = PILImageResampling.BILINEAR,
141
+ data_format: Optional[Union[str, ChannelDimension]] = None,
142
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
143
+ **kwargs,
144
+ ) -> np.ndarray:
145
+ """
146
+ Resize an image.
147
+
148
+ Args:
149
+ image (`np.ndarray`):
150
+ Image to resize.
151
+ size (`dict[str, int]`):
152
+ Size of the output image. If `size` is of the form `{"height": h, "width": w}`, the output image will
153
+ have the size `(h, w)`. If `size` is of the form `{"shortest_edge": s}`, the output image will have its
154
+ shortest edge of length `s` while keeping the aspect ratio of the original image.
155
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
156
+ Resampling filter to use when resiizing the image.
157
+ data_format (`str` or `ChannelDimension`, *optional*):
158
+ The channel dimension format of the image. If not provided, it will be the same as the input image.
159
+ input_data_format (`str` or `ChannelDimension`, *optional*):
160
+ The channel dimension format of the input image. If not provided, it will be inferred.
161
+ """
162
+ size = get_size_dict(size, default_to_square=False)
163
+ if "shortest_edge" in size:
164
+ output_size = get_resize_output_image_size(
165
+ image, size["shortest_edge"], default_to_square=False, input_data_format=input_data_format
166
+ )
167
+ elif "height" in size and "width" in size:
168
+ output_size = (size["height"], size["width"])
169
+ else:
170
+ raise ValueError(f"Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}")
171
+ return resize(
172
+ image,
173
+ size=output_size,
174
+ resample=resample,
175
+ data_format=data_format,
176
+ input_data_format=input_data_format,
177
+ **kwargs,
178
+ )
179
+
180
+ def _preprocess_image(
181
+ self,
182
+ image: ImageInput,
183
+ do_resize: Optional[bool] = None,
184
+ size: Optional[dict[str, int]] = None,
185
+ resample: PILImageResampling = None,
186
+ do_center_crop: Optional[bool] = None,
187
+ crop_size: Optional[dict[str, int]] = None,
188
+ do_rescale: Optional[bool] = None,
189
+ rescale_factor: Optional[float] = None,
190
+ do_normalize: Optional[bool] = None,
191
+ image_mean: Optional[Union[float, list[float]]] = None,
192
+ image_std: Optional[Union[float, list[float]]] = None,
193
+ data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
194
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
195
+ ) -> np.ndarray:
196
+ """Preprocesses a single image."""
197
+ validate_preprocess_arguments(
198
+ do_rescale=do_rescale,
199
+ rescale_factor=rescale_factor,
200
+ do_normalize=do_normalize,
201
+ image_mean=image_mean,
202
+ image_std=image_std,
203
+ do_center_crop=do_center_crop,
204
+ crop_size=crop_size,
205
+ do_resize=do_resize,
206
+ size=size,
207
+ resample=resample,
208
+ )
209
+
210
+ # All transformations expect numpy arrays.
211
+ image = to_numpy_array(image)
212
+
213
+ if do_rescale and is_scaled_image(image):
214
+ logger.warning_once(
215
+ "It looks like you are trying to rescale already rescaled images. If the input"
216
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
217
+ )
218
+
219
+ if input_data_format is None:
220
+ input_data_format = infer_channel_dimension_format(image)
221
+
222
+ if do_resize:
223
+ image = self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
224
+
225
+ if do_center_crop:
226
+ image = self.center_crop(image, size=crop_size, input_data_format=input_data_format)
227
+
228
+ if do_rescale:
229
+ image = self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
230
+
231
+ if do_normalize:
232
+ image = self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
233
+
234
+ image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
235
+ return image
236
+
237
+ @filter_out_non_signature_kwargs()
238
+ def preprocess(
239
+ self,
240
+ videos: ImageInput,
241
+ do_resize: Optional[bool] = None,
242
+ size: Optional[dict[str, int]] = None,
243
+ resample: PILImageResampling = None,
244
+ do_center_crop: Optional[bool] = None,
245
+ crop_size: Optional[dict[str, int]] = None,
246
+ do_rescale: Optional[bool] = None,
247
+ rescale_factor: Optional[float] = None,
248
+ do_normalize: Optional[bool] = None,
249
+ image_mean: Optional[Union[float, list[float]]] = None,
250
+ image_std: Optional[Union[float, list[float]]] = None,
251
+ return_tensors: Optional[Union[str, TensorType]] = None,
252
+ data_format: ChannelDimension = ChannelDimension.FIRST,
253
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
254
+ ) -> PIL.Image.Image:
255
+ """
256
+ Preprocess an image or batch of images.
257
+
258
+ Args:
259
+ images (`ImageInput`):
260
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
261
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
262
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
263
+ Whether to resize the image.
264
+ size (`dict[str, int]`, *optional*, defaults to `self.size`):
265
+ Size of the image after applying resize.
266
+ resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
267
+ Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`, Only
268
+ has an effect if `do_resize` is set to `True`.
269
+ do_center_crop (`bool`, *optional*, defaults to `self.do_centre_crop`):
270
+ Whether to centre crop the image.
271
+ crop_size (`dict[str, int]`, *optional*, defaults to `self.crop_size`):
272
+ Size of the image after applying the centre crop.
273
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
274
+ Whether to rescale the image values between [0 - 1].
275
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
276
+ Rescale factor to rescale the image by if `do_rescale` is set to `True`.
277
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
278
+ Whether to normalize the image.
279
+ image_mean (`float` or `list[float]`, *optional*, defaults to `self.image_mean`):
280
+ Image mean.
281
+ image_std (`float` or `list[float]`, *optional*, defaults to `self.image_std`):
282
+ Image standard deviation.
283
+ return_tensors (`str` or `TensorType`, *optional*):
284
+ The type of tensors to return. Can be one of:
285
+ - Unset: Return a list of `np.ndarray`.
286
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
287
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
288
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
289
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
290
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
291
+ The channel dimension format for the output image. Can be one of:
292
+ - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
293
+ - `ChannelDimension.LAST`: image in (height, width, num_channels) format.
294
+ - Unset: Use the inferred channel dimension format of the input image.
295
+ input_data_format (`ChannelDimension` or `str`, *optional*):
296
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
297
+ from the input image. Can be one of:
298
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
299
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
300
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
301
+ """
302
+ do_resize = do_resize if do_resize is not None else self.do_resize
303
+ resample = resample if resample is not None else self.resample
304
+ do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
305
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
306
+ rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
307
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
308
+ image_mean = image_mean if image_mean is not None else self.image_mean
309
+ image_std = image_std if image_std is not None else self.image_std
310
+
311
+ size = size if size is not None else self.size
312
+ size = get_size_dict(size, default_to_square=False)
313
+ crop_size = crop_size if crop_size is not None else self.crop_size
314
+ crop_size = get_size_dict(crop_size, param_name="crop_size")
315
+
316
+ if not valid_images(videos):
317
+ raise ValueError(
318
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
319
+ "torch.Tensor, tf.Tensor or jax.ndarray."
320
+ )
321
+
322
+ videos = make_batched(videos)
323
+
324
+ videos = [
325
+ [
326
+ self._preprocess_image(
327
+ image=img,
328
+ do_resize=do_resize,
329
+ size=size,
330
+ resample=resample,
331
+ do_center_crop=do_center_crop,
332
+ crop_size=crop_size,
333
+ do_rescale=do_rescale,
334
+ rescale_factor=rescale_factor,
335
+ do_normalize=do_normalize,
336
+ image_mean=image_mean,
337
+ image_std=image_std,
338
+ data_format=data_format,
339
+ input_data_format=input_data_format,
340
+ )
341
+ for img in video
342
+ ]
343
+ for video in videos
344
+ ]
345
+
346
+ data = {"pixel_values": videos}
347
+ return BatchFeature(data=data, tensor_type=return_tensors)
348
+
349
+
350
+ __all__ = ["VideoMAEImageProcessor"]
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/videomae/modeling_videomae.py ADDED
@@ -0,0 +1,1048 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 Multimedia Computing Group, Nanjing University and The HuggingFace Inc. team. 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
+ """PyTorch VideoMAE (masked autoencoder) model."""
16
+
17
+ import collections.abc
18
+ from copy import deepcopy
19
+ from dataclasses import dataclass
20
+ from typing import Callable, Optional, Union
21
+
22
+ import numpy as np
23
+ import torch
24
+ import torch.utils.checkpoint
25
+ from torch import nn
26
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
27
+
28
+ from ...activations import ACT2FN
29
+ from ...modeling_layers import GradientCheckpointingLayer
30
+ from ...modeling_outputs import BaseModelOutput, ImageClassifierOutput
31
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
32
+ from ...pytorch_utils import find_pruneable_heads_and_indices, prune_linear_layer
33
+ from ...utils import (
34
+ ModelOutput,
35
+ auto_docstring,
36
+ logging,
37
+ )
38
+ from ...utils.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
39
+ from .configuration_videomae import VideoMAEConfig
40
+
41
+
42
+ logger = logging.get_logger(__name__)
43
+
44
+
45
+ @dataclass
46
+ @auto_docstring(
47
+ custom_intro="""
48
+ Class for VideoMAEDecoder's outputs, with potential hidden states and attentions.
49
+ """
50
+ )
51
+ class VideoMAEDecoderOutput(ModelOutput):
52
+ r"""
53
+ logits (`torch.FloatTensor` of shape `(batch_size, patch_size ** 2 * num_channels)`):
54
+ Pixel reconstruction logits.
55
+ """
56
+
57
+ logits: Optional[torch.FloatTensor] = None
58
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
59
+ attentions: Optional[tuple[torch.FloatTensor]] = None
60
+
61
+
62
+ @dataclass
63
+ @auto_docstring(
64
+ custom_intro="""
65
+ Class for VideoMAEForPreTraining's outputs, with potential hidden states and attentions.
66
+ """
67
+ )
68
+ class VideoMAEForPreTrainingOutput(ModelOutput):
69
+ r"""
70
+ loss (`torch.FloatTensor` of shape `(1,)`):
71
+ Pixel reconstruction loss.
72
+ logits (`torch.FloatTensor` of shape `(batch_size, patch_size ** 2 * num_channels)`):
73
+ Pixel reconstruction logits.
74
+ """
75
+
76
+ loss: Optional[torch.FloatTensor] = None
77
+ logits: Optional[torch.FloatTensor] = None
78
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
79
+ attentions: Optional[tuple[torch.FloatTensor]] = None
80
+
81
+
82
+ # sin-cos position encoding
83
+ # https://github.com/jadore801120/attention-is-all-you-need-pytorch/blob/master/transformer/Models.py#L31
84
+ def get_sinusoid_encoding_table(n_position, d_hid):
85
+ """Sinusoid position encoding table"""
86
+
87
+ # TODO: make it with torch instead of numpy
88
+ def get_position_angle_vec(position):
89
+ return [position / np.power(10000, 2 * (hid_j // 2) / d_hid) for hid_j in range(d_hid)]
90
+
91
+ sinusoid_table = np.array([get_position_angle_vec(pos_i) for pos_i in range(n_position)])
92
+ sinusoid_table[:, 0::2] = np.sin(sinusoid_table[:, 0::2]) # dim 2i
93
+ sinusoid_table[:, 1::2] = np.cos(sinusoid_table[:, 1::2]) # dim 2i+1
94
+
95
+ return torch.FloatTensor(sinusoid_table).unsqueeze(0)
96
+
97
+
98
+ class VideoMAEEmbeddings(nn.Module):
99
+ """
100
+ Construct the patch and position embeddings.
101
+
102
+ """
103
+
104
+ def __init__(self, config):
105
+ super().__init__()
106
+
107
+ self.patch_embeddings = VideoMAEPatchEmbeddings(config)
108
+ self.num_patches = self.patch_embeddings.num_patches
109
+ # fixed sin-cos embedding
110
+ self.position_embeddings = get_sinusoid_encoding_table(self.num_patches, config.hidden_size)
111
+ self.config = config
112
+
113
+ def forward(self, pixel_values, bool_masked_pos):
114
+ # create patch embeddings
115
+ embeddings = self.patch_embeddings(pixel_values)
116
+
117
+ # add position embeddings
118
+ embeddings = embeddings + self.position_embeddings.detach().type_as(embeddings).to(
119
+ device=embeddings.device, copy=True
120
+ )
121
+ # only keep visible patches
122
+ # ~bool_masked_pos means visible
123
+ if bool_masked_pos is not None:
124
+ batch_size, _, num_channels = embeddings.shape
125
+ embeddings = embeddings[~bool_masked_pos]
126
+ embeddings = embeddings.reshape(batch_size, -1, num_channels)
127
+
128
+ return embeddings
129
+
130
+
131
+ class VideoMAEPatchEmbeddings(nn.Module):
132
+ """
133
+ Video to Patch Embedding. This module turns a batch of videos of shape (batch_size, num_frames, num_channels,
134
+ height, width) into a tensor of shape (batch_size, seq_len, hidden_size) to be consumed by a Transformer encoder.
135
+
136
+ The seq_len (the number of patches) equals (number of frames // tubelet_size) * (height // patch_size) * (width //
137
+ patch_size).
138
+
139
+ """
140
+
141
+ def __init__(self, config):
142
+ super().__init__()
143
+
144
+ image_size = config.image_size
145
+ patch_size = config.patch_size
146
+ num_channels = config.num_channels
147
+ hidden_size = config.hidden_size
148
+ num_frames = config.num_frames
149
+ tubelet_size = config.tubelet_size
150
+
151
+ image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
152
+ patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
153
+ self.image_size = image_size
154
+ self.patch_size = patch_size
155
+ self.tubelet_size = int(tubelet_size)
156
+ num_patches = (
157
+ (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) * (num_frames // self.tubelet_size)
158
+ )
159
+ self.num_channels = num_channels
160
+ self.num_patches = num_patches
161
+ self.projection = nn.Conv3d(
162
+ in_channels=num_channels,
163
+ out_channels=hidden_size,
164
+ kernel_size=(self.tubelet_size, patch_size[0], patch_size[1]),
165
+ stride=(self.tubelet_size, patch_size[0], patch_size[1]),
166
+ )
167
+
168
+ def forward(self, pixel_values):
169
+ batch_size, num_frames, num_channels, height, width = pixel_values.shape
170
+ if num_channels != self.num_channels:
171
+ raise ValueError(
172
+ "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
173
+ )
174
+ if height != self.image_size[0] or width != self.image_size[1]:
175
+ raise ValueError(
176
+ f"Input image size ({height}*{width}) doesn't match model ({self.image_size[0]}*{self.image_size[1]})."
177
+ )
178
+ # permute to (batch_size, num_channels, num_frames, height, width)
179
+ pixel_values = pixel_values.permute(0, 2, 1, 3, 4)
180
+ embeddings = self.projection(pixel_values).flatten(2).transpose(1, 2)
181
+ return embeddings
182
+
183
+
184
+ # Copied from transformers.models.vit.modeling_vit.eager_attention_forward
185
+ def eager_attention_forward(
186
+ module: nn.Module,
187
+ query: torch.Tensor,
188
+ key: torch.Tensor,
189
+ value: torch.Tensor,
190
+ attention_mask: Optional[torch.Tensor],
191
+ scaling: float,
192
+ dropout: float = 0.0,
193
+ **kwargs,
194
+ ):
195
+ # Take the dot product between "query" and "key" to get the raw attention scores.
196
+ attn_weights = torch.matmul(query, key.transpose(-1, -2)) * scaling
197
+
198
+ # Normalize the attention scores to probabilities.
199
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
200
+
201
+ # This is actually dropping out entire tokens to attend to, which might
202
+ # seem a bit unusual, but is taken from the original Transformer paper.
203
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
204
+
205
+ # Mask heads if we want to
206
+ if attention_mask is not None:
207
+ attn_weights = attn_weights * attention_mask
208
+
209
+ attn_output = torch.matmul(attn_weights, value)
210
+ attn_output = attn_output.transpose(1, 2).contiguous()
211
+
212
+ return attn_output, attn_weights
213
+
214
+
215
+ class VideoMAESelfAttention(nn.Module):
216
+ def __init__(self, config: VideoMAEConfig) -> None:
217
+ super().__init__()
218
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
219
+ raise ValueError(
220
+ f"The hidden size {config.hidden_size} is not a multiple of the number of attention "
221
+ f"heads {config.num_attention_heads}."
222
+ )
223
+ self.config = config
224
+ self.num_attention_heads = config.num_attention_heads
225
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
226
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
227
+ self.dropout_prob = config.attention_probs_dropout_prob
228
+ self.scaling = self.attention_head_size**-0.5
229
+ self.is_causal = False
230
+
231
+ self.query = nn.Linear(config.hidden_size, self.all_head_size, bias=False)
232
+ self.key = nn.Linear(config.hidden_size, self.all_head_size, bias=False)
233
+ self.value = nn.Linear(config.hidden_size, self.all_head_size, bias=False)
234
+
235
+ if config.qkv_bias:
236
+ self.q_bias = nn.Parameter(torch.zeros(self.all_head_size))
237
+ self.v_bias = nn.Parameter(torch.zeros(self.all_head_size))
238
+ else:
239
+ self.q_bias = None
240
+ self.v_bias = None
241
+
242
+ def forward(
243
+ self, hidden_states, head_mask: Optional[torch.Tensor] = None, output_attentions: bool = False
244
+ ) -> Union[tuple[torch.Tensor, torch.Tensor], tuple[torch.Tensor]]:
245
+ batch_size, seq_length, _ = hidden_states.shape
246
+ k_bias = torch.zeros_like(self.v_bias, requires_grad=False) if self.q_bias is not None else None
247
+ keys = nn.functional.linear(input=hidden_states, weight=self.key.weight, bias=k_bias)
248
+ values = nn.functional.linear(input=hidden_states, weight=self.value.weight, bias=self.v_bias)
249
+ queries = nn.functional.linear(input=hidden_states, weight=self.query.weight, bias=self.q_bias)
250
+
251
+ key_layer = keys.view(batch_size, -1, self.num_attention_heads, self.attention_head_size).transpose(1, 2)
252
+ value_layer = values.view(batch_size, -1, self.num_attention_heads, self.attention_head_size).transpose(1, 2)
253
+ query_layer = queries.view(batch_size, -1, self.num_attention_heads, self.attention_head_size).transpose(1, 2)
254
+
255
+ attention_interface: Callable = eager_attention_forward
256
+ if self.config._attn_implementation != "eager":
257
+ if self.config._attn_implementation == "sdpa" and output_attentions:
258
+ logger.warning_once(
259
+ "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
260
+ 'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
261
+ )
262
+ else:
263
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
264
+
265
+ context_layer, attention_probs = attention_interface(
266
+ self,
267
+ query_layer,
268
+ key_layer,
269
+ value_layer,
270
+ head_mask,
271
+ is_causal=self.is_causal,
272
+ scaling=self.scaling,
273
+ dropout=0.0 if not self.training else self.dropout_prob,
274
+ )
275
+
276
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
277
+ context_layer = context_layer.reshape(new_context_layer_shape)
278
+
279
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
280
+
281
+ return outputs
282
+
283
+
284
+ # Copied from transformers.models.vit.modeling_vit.ViTSelfOutput with ViT->VideoMAE
285
+ class VideoMAESelfOutput(nn.Module):
286
+ """
287
+ The residual connection is defined in VideoMAELayer instead of here (as is the case with other models), due to the
288
+ layernorm applied before each block.
289
+ """
290
+
291
+ def __init__(self, config: VideoMAEConfig) -> None:
292
+ super().__init__()
293
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
294
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
295
+
296
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
297
+ hidden_states = self.dense(hidden_states)
298
+ hidden_states = self.dropout(hidden_states)
299
+
300
+ return hidden_states
301
+
302
+
303
+ # Copied from transformers.models.vit.modeling_vit.ViTAttention with ViT->VideoMAE
304
+ class VideoMAEAttention(nn.Module):
305
+ def __init__(self, config: VideoMAEConfig) -> None:
306
+ super().__init__()
307
+ self.attention = VideoMAESelfAttention(config)
308
+ self.output = VideoMAESelfOutput(config)
309
+ self.pruned_heads = set()
310
+
311
+ def prune_heads(self, heads: set[int]) -> None:
312
+ if len(heads) == 0:
313
+ return
314
+ heads, index = find_pruneable_heads_and_indices(
315
+ heads, self.attention.num_attention_heads, self.attention.attention_head_size, self.pruned_heads
316
+ )
317
+
318
+ # Prune linear layers
319
+ self.attention.query = prune_linear_layer(self.attention.query, index)
320
+ self.attention.key = prune_linear_layer(self.attention.key, index)
321
+ self.attention.value = prune_linear_layer(self.attention.value, index)
322
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
323
+
324
+ # Update hyper params and store pruned heads
325
+ self.attention.num_attention_heads = self.attention.num_attention_heads - len(heads)
326
+ self.attention.all_head_size = self.attention.attention_head_size * self.attention.num_attention_heads
327
+ self.pruned_heads = self.pruned_heads.union(heads)
328
+
329
+ def forward(
330
+ self,
331
+ hidden_states: torch.Tensor,
332
+ head_mask: Optional[torch.Tensor] = None,
333
+ output_attentions: bool = False,
334
+ ) -> Union[tuple[torch.Tensor, torch.Tensor], tuple[torch.Tensor]]:
335
+ self_outputs = self.attention(hidden_states, head_mask, output_attentions)
336
+
337
+ attention_output = self.output(self_outputs[0], hidden_states)
338
+
339
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
340
+ return outputs
341
+
342
+
343
+ # Copied from transformers.models.vit.modeling_vit.ViTIntermediate ViT->VideoMAE
344
+ class VideoMAEIntermediate(nn.Module):
345
+ def __init__(self, config: VideoMAEConfig) -> None:
346
+ super().__init__()
347
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
348
+ if isinstance(config.hidden_act, str):
349
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
350
+ else:
351
+ self.intermediate_act_fn = config.hidden_act
352
+
353
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
354
+ hidden_states = self.dense(hidden_states)
355
+ hidden_states = self.intermediate_act_fn(hidden_states)
356
+
357
+ return hidden_states
358
+
359
+
360
+ # Copied from transformers.models.vit.modeling_vit.ViTOutput ViT->VideoMAE
361
+ class VideoMAEOutput(nn.Module):
362
+ def __init__(self, config: VideoMAEConfig) -> None:
363
+ super().__init__()
364
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
365
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
366
+
367
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
368
+ hidden_states = self.dense(hidden_states)
369
+ hidden_states = self.dropout(hidden_states)
370
+
371
+ hidden_states = hidden_states + input_tensor
372
+
373
+ return hidden_states
374
+
375
+
376
+ # Copied from transformers.models.vit.modeling_vit.ViTLayer with ViT->VideoMAE,VIT->VIDEOMAE
377
+ class VideoMAELayer(GradientCheckpointingLayer):
378
+ """This corresponds to the Block class in the timm implementation."""
379
+
380
+ def __init__(self, config: VideoMAEConfig) -> None:
381
+ super().__init__()
382
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
383
+ self.seq_len_dim = 1
384
+ self.attention = VideoMAEAttention(config)
385
+ self.intermediate = VideoMAEIntermediate(config)
386
+ self.output = VideoMAEOutput(config)
387
+ self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
388
+ self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
389
+
390
+ def forward(
391
+ self,
392
+ hidden_states: torch.Tensor,
393
+ head_mask: Optional[torch.Tensor] = None,
394
+ output_attentions: bool = False,
395
+ ) -> Union[tuple[torch.Tensor, torch.Tensor], tuple[torch.Tensor]]:
396
+ self_attention_outputs = self.attention(
397
+ self.layernorm_before(hidden_states), # in VideoMAE, layernorm is applied before self-attention
398
+ head_mask,
399
+ output_attentions=output_attentions,
400
+ )
401
+ attention_output = self_attention_outputs[0]
402
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
403
+
404
+ # first residual connection
405
+ hidden_states = attention_output + hidden_states
406
+
407
+ # in VideoMAE, layernorm is also applied after self-attention
408
+ layer_output = self.layernorm_after(hidden_states)
409
+ layer_output = self.intermediate(layer_output)
410
+
411
+ # second residual connection is done here
412
+ layer_output = self.output(layer_output, hidden_states)
413
+
414
+ outputs = (layer_output,) + outputs
415
+
416
+ return outputs
417
+
418
+
419
+ # Copied from transformers.models.vit.modeling_vit.ViTEncoder with ViT->VideoMAE
420
+ class VideoMAEEncoder(nn.Module):
421
+ def __init__(self, config: VideoMAEConfig) -> None:
422
+ super().__init__()
423
+ self.config = config
424
+ self.layer = nn.ModuleList([VideoMAELayer(config) for _ in range(config.num_hidden_layers)])
425
+ self.gradient_checkpointing = False
426
+
427
+ def forward(
428
+ self,
429
+ hidden_states: torch.Tensor,
430
+ head_mask: Optional[torch.Tensor] = None,
431
+ output_attentions: bool = False,
432
+ output_hidden_states: bool = False,
433
+ return_dict: bool = True,
434
+ ) -> Union[tuple, BaseModelOutput]:
435
+ all_hidden_states = () if output_hidden_states else None
436
+ all_self_attentions = () if output_attentions else None
437
+
438
+ for i, layer_module in enumerate(self.layer):
439
+ if output_hidden_states:
440
+ all_hidden_states = all_hidden_states + (hidden_states,)
441
+
442
+ layer_head_mask = head_mask[i] if head_mask is not None else None
443
+
444
+ layer_outputs = layer_module(hidden_states, layer_head_mask, output_attentions)
445
+
446
+ hidden_states = layer_outputs[0]
447
+
448
+ if output_attentions:
449
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
450
+
451
+ if output_hidden_states:
452
+ all_hidden_states = all_hidden_states + (hidden_states,)
453
+
454
+ if not return_dict:
455
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
456
+ return BaseModelOutput(
457
+ last_hidden_state=hidden_states,
458
+ hidden_states=all_hidden_states,
459
+ attentions=all_self_attentions,
460
+ )
461
+
462
+
463
+ @auto_docstring
464
+ class VideoMAEPreTrainedModel(PreTrainedModel):
465
+ config: VideoMAEConfig
466
+ base_model_prefix = "videomae"
467
+ main_input_name = "pixel_values"
468
+ supports_gradient_checkpointing = True
469
+ _supports_sdpa = True
470
+ _supports_flash_attn = True
471
+ _supports_flex_attn = True
472
+ _supports_attention_backend = True
473
+
474
+ def _init_weights(self, module):
475
+ """Initialize the weights"""
476
+ if isinstance(module, (nn.Linear, nn.Conv3d)):
477
+ # Slightly different from the TF version which uses truncated_normal for initialization
478
+ # cf https://github.com/pytorch/pytorch/pull/5617
479
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
480
+ if module.bias is not None:
481
+ module.bias.data.zero_()
482
+ elif isinstance(module, nn.LayerNorm):
483
+ module.bias.data.zero_()
484
+ module.weight.data.fill_(1.0)
485
+
486
+
487
+ @auto_docstring
488
+ class VideoMAEModel(VideoMAEPreTrainedModel):
489
+ def __init__(self, config):
490
+ super().__init__(config)
491
+ self.config = config
492
+
493
+ self.embeddings = VideoMAEEmbeddings(config)
494
+ self.encoder = VideoMAEEncoder(config)
495
+
496
+ if config.use_mean_pooling:
497
+ self.layernorm = None
498
+ else:
499
+ self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
500
+
501
+ # Initialize weights and apply final processing
502
+ self.post_init()
503
+
504
+ def get_input_embeddings(self):
505
+ return self.embeddings.patch_embeddings
506
+
507
+ def _prune_heads(self, heads_to_prune):
508
+ """
509
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
510
+ class PreTrainedModel
511
+ """
512
+ for layer, heads in heads_to_prune.items():
513
+ self.encoder.layer[layer].attention.prune_heads(heads)
514
+
515
+ @auto_docstring
516
+ def forward(
517
+ self,
518
+ pixel_values: torch.FloatTensor,
519
+ bool_masked_pos: Optional[torch.BoolTensor] = None,
520
+ head_mask: Optional[torch.Tensor] = None,
521
+ output_attentions: Optional[bool] = None,
522
+ output_hidden_states: Optional[bool] = None,
523
+ return_dict: Optional[bool] = None,
524
+ ) -> Union[tuple, BaseModelOutput]:
525
+ r"""
526
+ bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, sequence_length)`, *optional*):
527
+ Boolean masked positions. Indicates which patches are masked (1) and which aren't (0). Each video in the
528
+ batch must have the same number of masked patches. If `None`, then all patches are considered. Sequence
529
+ length is `(num_frames // tubelet_size) * (image_size // patch_size) ** 2`.
530
+
531
+ Examples:
532
+
533
+ ```python
534
+ >>> import av
535
+ >>> import numpy as np
536
+
537
+ >>> from transformers import AutoImageProcessor, VideoMAEModel
538
+ >>> from huggingface_hub import hf_hub_download
539
+
540
+ >>> np.random.seed(0)
541
+
542
+
543
+ >>> def read_video_pyav(container, indices):
544
+ ... '''
545
+ ... Decode the video with PyAV decoder.
546
+ ... Args:
547
+ ... container (`av.container.input.InputContainer`): PyAV container.
548
+ ... indices (`list[int]`): List of frame indices to decode.
549
+ ... Returns:
550
+ ... result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).
551
+ ... '''
552
+ ... frames = []
553
+ ... container.seek(0)
554
+ ... start_index = indices[0]
555
+ ... end_index = indices[-1]
556
+ ... for i, frame in enumerate(container.decode(video=0)):
557
+ ... if i > end_index:
558
+ ... break
559
+ ... if i >= start_index and i in indices:
560
+ ... frames.append(frame)
561
+ ... return np.stack([x.to_ndarray(format="rgb24") for x in frames])
562
+
563
+
564
+ >>> def sample_frame_indices(clip_len, frame_sample_rate, seg_len):
565
+ ... '''
566
+ ... Sample a given number of frame indices from the video.
567
+ ... Args:
568
+ ... clip_len (`int`): Total number of frames to sample.
569
+ ... frame_sample_rate (`int`): Sample every n-th frame.
570
+ ... seg_len (`int`): Maximum allowed index of sample's last frame.
571
+ ... Returns:
572
+ ... indices (`list[int]`): List of sampled frame indices
573
+ ... '''
574
+ ... converted_len = int(clip_len * frame_sample_rate)
575
+ ... end_idx = np.random.randint(converted_len, seg_len)
576
+ ... start_idx = end_idx - converted_len
577
+ ... indices = np.linspace(start_idx, end_idx, num=clip_len)
578
+ ... indices = np.clip(indices, start_idx, end_idx - 1).astype(np.int64)
579
+ ... return indices
580
+
581
+
582
+ >>> # video clip consists of 300 frames (10 seconds at 30 FPS)
583
+ >>> file_path = hf_hub_download(
584
+ ... repo_id="nielsr/video-demo", filename="eating_spaghetti.mp4", repo_type="dataset"
585
+ ... )
586
+ >>> container = av.open(file_path)
587
+
588
+ >>> # sample 16 frames
589
+ >>> indices = sample_frame_indices(clip_len=16, frame_sample_rate=1, seg_len=container.streams.video[0].frames)
590
+ >>> video = read_video_pyav(container, indices)
591
+
592
+ >>> image_processor = AutoImageProcessor.from_pretrained("MCG-NJU/videomae-base")
593
+ >>> model = VideoMAEModel.from_pretrained("MCG-NJU/videomae-base")
594
+
595
+ >>> # prepare video for the model
596
+ >>> inputs = image_processor(list(video), return_tensors="pt")
597
+
598
+ >>> # forward pass
599
+ >>> outputs = model(**inputs)
600
+ >>> last_hidden_states = outputs.last_hidden_state
601
+ >>> list(last_hidden_states.shape)
602
+ [1, 1568, 768]
603
+ ```"""
604
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
605
+ output_hidden_states = (
606
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
607
+ )
608
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
609
+
610
+ # Prepare head mask if needed
611
+ # 1.0 in head_mask indicate we keep the head
612
+ # attention_probs has shape bsz x n_heads x N x N
613
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
614
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
615
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
616
+
617
+ embedding_output = self.embeddings(pixel_values, bool_masked_pos)
618
+
619
+ encoder_outputs = self.encoder(
620
+ embedding_output,
621
+ head_mask=head_mask,
622
+ output_attentions=output_attentions,
623
+ output_hidden_states=output_hidden_states,
624
+ return_dict=return_dict,
625
+ )
626
+ sequence_output = encoder_outputs[0]
627
+ if self.layernorm is not None:
628
+ sequence_output = self.layernorm(sequence_output)
629
+
630
+ if not return_dict:
631
+ return (sequence_output,) + encoder_outputs[1:]
632
+
633
+ return BaseModelOutput(
634
+ last_hidden_state=sequence_output,
635
+ hidden_states=encoder_outputs.hidden_states,
636
+ attentions=encoder_outputs.attentions,
637
+ )
638
+
639
+
640
+ class VideoMAEDecoder(nn.Module):
641
+ def __init__(self, config, num_patches):
642
+ super().__init__()
643
+
644
+ decoder_num_labels = config.num_channels * config.tubelet_size * config.patch_size**2
645
+
646
+ decoder_config = deepcopy(config)
647
+ decoder_config.hidden_size = config.decoder_hidden_size
648
+ decoder_config.num_hidden_layers = config.decoder_num_hidden_layers
649
+ decoder_config.num_attention_heads = config.decoder_num_attention_heads
650
+ decoder_config.intermediate_size = config.decoder_intermediate_size
651
+ self.decoder_layers = nn.ModuleList(
652
+ [VideoMAELayer(decoder_config) for _ in range(config.decoder_num_hidden_layers)]
653
+ )
654
+
655
+ self.norm = nn.LayerNorm(config.decoder_hidden_size)
656
+ self.head = (
657
+ nn.Linear(config.decoder_hidden_size, decoder_num_labels) if decoder_num_labels > 0 else nn.Identity()
658
+ )
659
+
660
+ self.gradient_checkpointing = False
661
+ self.config = config
662
+
663
+ def forward(
664
+ self,
665
+ hidden_states,
666
+ return_token_num,
667
+ output_attentions=False,
668
+ output_hidden_states=False,
669
+ return_dict=True,
670
+ ):
671
+ # apply Transformer layers (blocks)
672
+ all_hidden_states = () if output_hidden_states else None
673
+ all_self_attentions = () if output_attentions else None
674
+ for i, layer_module in enumerate(self.decoder_layers):
675
+ if output_hidden_states:
676
+ all_hidden_states = all_hidden_states + (hidden_states,)
677
+
678
+ layer_outputs = layer_module(hidden_states, head_mask=None, output_attentions=output_attentions)
679
+
680
+ hidden_states = layer_outputs[0]
681
+
682
+ if output_attentions:
683
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
684
+
685
+ if output_hidden_states:
686
+ all_hidden_states = all_hidden_states + (hidden_states,)
687
+
688
+ if return_token_num > 0:
689
+ hidden_states = hidden_states[:, -return_token_num:]
690
+
691
+ # predictor projection
692
+ hidden_states = self.norm(hidden_states)
693
+ logits = self.head(hidden_states)
694
+
695
+ if not return_dict:
696
+ return tuple(v for v in [logits, all_hidden_states, all_self_attentions] if v is not None)
697
+ return VideoMAEDecoderOutput(logits=logits, hidden_states=all_hidden_states, attentions=all_self_attentions)
698
+
699
+
700
+ @auto_docstring(
701
+ custom_intro="""
702
+ The VideoMAE Model transformer with the decoder on top for self-supervised pre-training.
703
+ """
704
+ )
705
+ class VideoMAEForPreTraining(VideoMAEPreTrainedModel):
706
+ def __init__(self, config):
707
+ super().__init__(config)
708
+ self.config = config
709
+
710
+ self.videomae = VideoMAEModel(config)
711
+
712
+ self.encoder_to_decoder = nn.Linear(config.hidden_size, config.decoder_hidden_size, bias=False)
713
+ self.mask_token = nn.Parameter(torch.zeros(1, 1, config.decoder_hidden_size))
714
+ self.position_embeddings = get_sinusoid_encoding_table(
715
+ self.videomae.embeddings.num_patches, config.decoder_hidden_size
716
+ )
717
+
718
+ self.decoder = VideoMAEDecoder(config, num_patches=self.videomae.embeddings.num_patches)
719
+
720
+ # Initialize weights and apply final processing
721
+ self.post_init()
722
+
723
+ @auto_docstring
724
+ def forward(
725
+ self,
726
+ pixel_values: torch.FloatTensor,
727
+ bool_masked_pos: torch.BoolTensor,
728
+ head_mask: Optional[torch.Tensor] = None,
729
+ output_attentions: Optional[bool] = None,
730
+ output_hidden_states: Optional[bool] = None,
731
+ return_dict: Optional[bool] = None,
732
+ ) -> Union[tuple, VideoMAEForPreTrainingOutput]:
733
+ r"""
734
+ bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, sequence_length)`):
735
+ Boolean masked positions. Indicates which patches are masked (1) and which aren't (0). Each video in the
736
+ batch must have the same number of masked patches. Sequence length is `(num_frames // tubelet_size) *
737
+ (image_size // patch_size) ** 2`.
738
+
739
+ Examples:
740
+ ```python
741
+ >>> from transformers import AutoImageProcessor, VideoMAEForPreTraining
742
+ >>> import numpy as np
743
+ >>> import torch
744
+
745
+ >>> num_frames = 16
746
+ >>> video = list(np.random.randint(0, 256, (num_frames, 3, 224, 224)))
747
+
748
+ >>> image_processor = AutoImageProcessor.from_pretrained("MCG-NJU/videomae-base")
749
+ >>> model = VideoMAEForPreTraining.from_pretrained("MCG-NJU/videomae-base")
750
+
751
+ >>> pixel_values = image_processor(video, return_tensors="pt").pixel_values
752
+
753
+ >>> num_patches_per_frame = (model.config.image_size // model.config.patch_size) ** 2
754
+ >>> seq_length = (num_frames // model.config.tubelet_size) * num_patches_per_frame
755
+ >>> bool_masked_pos = torch.randint(0, 2, (1, seq_length)).bool()
756
+
757
+ >>> outputs = model(pixel_values, bool_masked_pos=bool_masked_pos)
758
+ >>> loss = outputs.loss
759
+ ```"""
760
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
761
+
762
+ outputs = self.videomae(
763
+ pixel_values,
764
+ bool_masked_pos=bool_masked_pos,
765
+ head_mask=head_mask,
766
+ output_attentions=output_attentions,
767
+ output_hidden_states=output_hidden_states,
768
+ return_dict=return_dict,
769
+ )
770
+
771
+ sequence_output = outputs[0]
772
+ sequence_output = self.encoder_to_decoder(
773
+ sequence_output
774
+ ) # [batch_size, num_visible_patches, decoder_hidden_size]
775
+ batch_size, seq_len, num_channels = sequence_output.shape
776
+
777
+ # we don't unshuffle the correct visible token order, but shuffle the position embeddings accordingly.
778
+ if bool_masked_pos is None:
779
+ raise ValueError("One must provided a boolean mask ")
780
+ expanded_position_embeddings = self.position_embeddings.expand(batch_size, -1, -1).type_as(pixel_values)
781
+ expanded_position_embeddings = expanded_position_embeddings.detach().to(device=pixel_values.device, copy=True)
782
+ pos_emb_visible = expanded_position_embeddings[~bool_masked_pos].reshape(batch_size, -1, num_channels)
783
+ pos_emb_mask = expanded_position_embeddings[bool_masked_pos].reshape(batch_size, -1, num_channels)
784
+
785
+ # [batch_size, num_patches, decoder_hidden_size]
786
+ x_full = torch.cat([sequence_output + pos_emb_visible, self.mask_token + pos_emb_mask], dim=1)
787
+
788
+ # [batch_size, num_masked_patches, num_channels * patch_size * patch_size]
789
+ decoder_outputs = self.decoder(x_full, pos_emb_mask.shape[1])
790
+ logits = decoder_outputs.logits
791
+
792
+ loss = None
793
+ with torch.no_grad():
794
+ # calculate the labels to be predicted
795
+ if self.config.num_channels != 3:
796
+ # Can't unnormalize with default means/stds
797
+ frames = pixel_values
798
+ else:
799
+ # first, unnormalize the frames
800
+ device = pixel_values.device
801
+ dtype = pixel_values.dtype
802
+ mean = torch.as_tensor(IMAGENET_DEFAULT_MEAN).to(device=device, dtype=dtype)[None, None, :, None, None]
803
+ std = torch.as_tensor(IMAGENET_DEFAULT_STD).to(device=device, dtype=dtype)[None, None, :, None, None]
804
+ frames = pixel_values * std + mean # in [0, 1]
805
+
806
+ batch_size, time, num_channels, height, width = frames.shape
807
+ tubelet_size, patch_size = self.config.tubelet_size, self.config.patch_size
808
+ if self.config.norm_pix_loss:
809
+ # step 1: split up dimensions (time by tubelet_size, height by patch_size, width by patch_size)
810
+ frames = frames.view(
811
+ batch_size,
812
+ time // tubelet_size,
813
+ tubelet_size,
814
+ num_channels,
815
+ height // patch_size,
816
+ patch_size,
817
+ width // patch_size,
818
+ patch_size,
819
+ )
820
+ # step 2: move dimensions to concatenate:
821
+ frames = frames.permute(0, 1, 4, 6, 2, 5, 7, 3).contiguous()
822
+ # step 3: concatenate:
823
+ frames = frames.view(
824
+ batch_size,
825
+ time // tubelet_size * height // patch_size * width // patch_size,
826
+ tubelet_size * patch_size * patch_size,
827
+ num_channels,
828
+ )
829
+ # step 4: normalize. The authors find that the mean is about 0.48 and standard deviation is about 0.08.
830
+ frames_norm = (frames - frames.mean(dim=-2, keepdim=True)) / (
831
+ frames.var(dim=-2, unbiased=True, keepdim=True).sqrt() + 1e-6
832
+ )
833
+ # step 5: reshape to (batch_size, T//ts * H//ps * W//ps, ts * ps * ps * C)
834
+ videos_patch = frames_norm.view(
835
+ batch_size,
836
+ time // tubelet_size * height // patch_size * width // patch_size,
837
+ tubelet_size * patch_size * patch_size * num_channels,
838
+ )
839
+ else:
840
+ if self.config.num_channels != 3:
841
+ raise ValueError(
842
+ "Can't unnormalize non-RGB images. Consider setting config.norm_pix_loss to False."
843
+ )
844
+ # step 1: split up dimensions (time by tubelet_size, height by patch_size, width by patch_size)
845
+ frames = frames.view(
846
+ batch_size,
847
+ time // tubelet_size,
848
+ tubelet_size,
849
+ num_channels,
850
+ height // patch_size,
851
+ patch_size,
852
+ width // patch_size,
853
+ patch_size,
854
+ )
855
+ # step 2: move dimensions to concatenate: (batch_size, T//ts, H//ps, W//ps, ts, ps, ps, C)
856
+ frames = frames.permute(0, 1, 4, 6, 2, 5, 7, 3).contiguous()
857
+ # step 3: concatenate
858
+ videos_patch = frames.view(
859
+ batch_size,
860
+ time // tubelet_size * height // patch_size * width // patch_size,
861
+ tubelet_size * patch_size * patch_size * num_channels,
862
+ )
863
+
864
+ batch_size, _, num_channels = videos_patch.shape
865
+ labels = videos_patch[bool_masked_pos].reshape(batch_size, -1, num_channels)
866
+
867
+ loss_fct = MSELoss()
868
+ loss = loss_fct(logits, labels)
869
+
870
+ if not return_dict:
871
+ output = (logits,) + outputs[1:]
872
+ return ((loss,) + output) if loss is not None else output
873
+
874
+ return VideoMAEForPreTrainingOutput(
875
+ loss=loss,
876
+ logits=logits,
877
+ hidden_states=outputs.hidden_states,
878
+ attentions=outputs.attentions,
879
+ )
880
+
881
+
882
+ @auto_docstring(
883
+ custom_intro="""
884
+ VideoMAE Model transformer with a video classification head on top (a linear layer on top of the average pooled hidden
885
+ states of all tokens) e.g. for ImageNet.
886
+ """
887
+ )
888
+ class VideoMAEForVideoClassification(VideoMAEPreTrainedModel):
889
+ def __init__(self, config):
890
+ super().__init__(config)
891
+
892
+ self.num_labels = config.num_labels
893
+ self.videomae = VideoMAEModel(config)
894
+
895
+ # Classifier head
896
+ self.fc_norm = nn.LayerNorm(config.hidden_size) if config.use_mean_pooling else None
897
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()
898
+
899
+ # Initialize weights and apply final processing
900
+ self.post_init()
901
+
902
+ @auto_docstring
903
+ def forward(
904
+ self,
905
+ pixel_values: Optional[torch.Tensor] = None,
906
+ head_mask: Optional[torch.Tensor] = None,
907
+ labels: Optional[torch.Tensor] = None,
908
+ output_attentions: Optional[bool] = None,
909
+ output_hidden_states: Optional[bool] = None,
910
+ return_dict: Optional[bool] = None,
911
+ ) -> Union[tuple, ImageClassifierOutput]:
912
+ r"""
913
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
914
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
915
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
916
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
917
+
918
+ Examples:
919
+
920
+ ```python
921
+ >>> import av
922
+ >>> import torch
923
+ >>> import numpy as np
924
+
925
+ >>> from transformers import AutoImageProcessor, VideoMAEForVideoClassification
926
+ >>> from huggingface_hub import hf_hub_download
927
+
928
+ >>> np.random.seed(0)
929
+
930
+
931
+ >>> def read_video_pyav(container, indices):
932
+ ... '''
933
+ ... Decode the video with PyAV decoder.
934
+ ... Args:
935
+ ... container (`av.container.input.InputContainer`): PyAV container.
936
+ ... indices (`list[int]`): List of frame indices to decode.
937
+ ... Returns:
938
+ ... result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3).
939
+ ... '''
940
+ ... frames = []
941
+ ... container.seek(0)
942
+ ... start_index = indices[0]
943
+ ... end_index = indices[-1]
944
+ ... for i, frame in enumerate(container.decode(video=0)):
945
+ ... if i > end_index:
946
+ ... break
947
+ ... if i >= start_index and i in indices:
948
+ ... frames.append(frame)
949
+ ... return np.stack([x.to_ndarray(format="rgb24") for x in frames])
950
+
951
+
952
+ >>> def sample_frame_indices(clip_len, frame_sample_rate, seg_len):
953
+ ... '''
954
+ ... Sample a given number of frame indices from the video.
955
+ ... Args:
956
+ ... clip_len (`int`): Total number of frames to sample.
957
+ ... frame_sample_rate (`int`): Sample every n-th frame.
958
+ ... seg_len (`int`): Maximum allowed index of sample's last frame.
959
+ ... Returns:
960
+ ... indices (`list[int]`): List of sampled frame indices
961
+ ... '''
962
+ ... converted_len = int(clip_len * frame_sample_rate)
963
+ ... end_idx = np.random.randint(converted_len, seg_len)
964
+ ... start_idx = end_idx - converted_len
965
+ ... indices = np.linspace(start_idx, end_idx, num=clip_len)
966
+ ... indices = np.clip(indices, start_idx, end_idx - 1).astype(np.int64)
967
+ ... return indices
968
+
969
+
970
+ >>> # video clip consists of 300 frames (10 seconds at 30 FPS)
971
+ >>> file_path = hf_hub_download(
972
+ ... repo_id="nielsr/video-demo", filename="eating_spaghetti.mp4", repo_type="dataset"
973
+ ... )
974
+ >>> container = av.open(file_path)
975
+
976
+ >>> # sample 16 frames
977
+ >>> indices = sample_frame_indices(clip_len=16, frame_sample_rate=1, seg_len=container.streams.video[0].frames)
978
+ >>> video = read_video_pyav(container, indices)
979
+
980
+ >>> image_processor = AutoImageProcessor.from_pretrained("MCG-NJU/videomae-base-finetuned-kinetics")
981
+ >>> model = VideoMAEForVideoClassification.from_pretrained("MCG-NJU/videomae-base-finetuned-kinetics")
982
+
983
+ >>> inputs = image_processor(list(video), return_tensors="pt")
984
+
985
+ >>> with torch.no_grad():
986
+ ... outputs = model(**inputs)
987
+ ... logits = outputs.logits
988
+
989
+ >>> # model predicts one of the 400 Kinetics-400 classes
990
+ >>> predicted_label = logits.argmax(-1).item()
991
+ >>> print(model.config.id2label[predicted_label])
992
+ eating spaghetti
993
+ ```"""
994
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
995
+
996
+ outputs = self.videomae(
997
+ pixel_values,
998
+ head_mask=head_mask,
999
+ output_attentions=output_attentions,
1000
+ output_hidden_states=output_hidden_states,
1001
+ return_dict=return_dict,
1002
+ )
1003
+
1004
+ sequence_output = outputs[0]
1005
+
1006
+ if self.fc_norm is not None:
1007
+ sequence_output = self.fc_norm(sequence_output.mean(1))
1008
+ else:
1009
+ sequence_output = sequence_output[:, 0]
1010
+
1011
+ logits = self.classifier(sequence_output)
1012
+
1013
+ loss = None
1014
+ if labels is not None:
1015
+ if self.config.problem_type is None:
1016
+ if self.num_labels == 1:
1017
+ self.config.problem_type = "regression"
1018
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1019
+ self.config.problem_type = "single_label_classification"
1020
+ else:
1021
+ self.config.problem_type = "multi_label_classification"
1022
+
1023
+ if self.config.problem_type == "regression":
1024
+ loss_fct = MSELoss()
1025
+ if self.num_labels == 1:
1026
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1027
+ else:
1028
+ loss = loss_fct(logits, labels)
1029
+ elif self.config.problem_type == "single_label_classification":
1030
+ loss_fct = CrossEntropyLoss()
1031
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1032
+ elif self.config.problem_type == "multi_label_classification":
1033
+ loss_fct = BCEWithLogitsLoss()
1034
+ loss = loss_fct(logits, labels)
1035
+
1036
+ if not return_dict:
1037
+ output = (logits,) + outputs[1:]
1038
+ return ((loss,) + output) if loss is not None else output
1039
+
1040
+ return ImageClassifierOutput(
1041
+ loss=loss,
1042
+ logits=logits,
1043
+ hidden_states=outputs.hidden_states,
1044
+ attentions=outputs.attentions,
1045
+ )
1046
+
1047
+
1048
+ __all__ = ["VideoMAEForPreTraining", "VideoMAEModel", "VideoMAEPreTrainedModel", "VideoMAEForVideoClassification"]
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/vilt/__init__.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. 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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_vilt import *
22
+ from .feature_extraction_vilt import *
23
+ from .image_processing_vilt import *
24
+ from .image_processing_vilt_fast import *
25
+ from .modeling_vilt import *
26
+ from .processing_vilt import *
27
+ else:
28
+ import sys
29
+
30
+ _file = globals()["__file__"]
31
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/vilt/configuration_vilt.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team. 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
+ """VilT model configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+ from ...utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ class ViltConfig(PretrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`ViLTModel`]. It is used to instantiate an ViLT
27
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
28
+ defaults will yield a similar configuration to that of the ViLT
29
+ [dandelin/vilt-b32-mlm](https://huggingface.co/dandelin/vilt-b32-mlm) architecture.
30
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+ Args:
35
+ vocab_size (`int`, *optional*, defaults to 30522):
36
+ Vocabulary size of the text part of the model. Defines the number of different tokens that can be
37
+ represented by the `inputs_ids` passed when calling [`ViltModel`].
38
+ type_vocab_size (`int`, *optional*, defaults to 2):
39
+ The vocabulary size of the `token_type_ids` passed when calling [`ViltModel`]. This is used when encoding
40
+ text.
41
+ modality_type_vocab_size (`int`, *optional*, defaults to 2):
42
+ The vocabulary size of the modalities passed when calling [`ViltModel`]. This is used after concatenating the
43
+ embeddings of the text and image modalities.
44
+ max_position_embeddings (`int`, *optional*, defaults to 40):
45
+ The maximum sequence length that this model might ever be used with.
46
+ hidden_size (`int`, *optional*, defaults to 768):
47
+ Dimensionality of the encoder layers and the pooler layer.
48
+ num_hidden_layers (`int`, *optional*, defaults to 12):
49
+ Number of hidden layers in the Transformer encoder.
50
+ num_attention_heads (`int`, *optional*, defaults to 12):
51
+ Number of attention heads for each attention layer in the Transformer encoder.
52
+ intermediate_size (`int`, *optional*, defaults to 3072):
53
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
54
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
55
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
56
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
57
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
58
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
59
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
60
+ The dropout ratio for the attention probabilities.
61
+ initializer_range (`float`, *optional*, defaults to 0.02):
62
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
63
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
64
+ The epsilon used by the layer normalization layers.
65
+ image_size (`int`, *optional*, defaults to 384):
66
+ The size (resolution) of each image.
67
+ patch_size (`int`, *optional*, defaults to 32):
68
+ The size (resolution) of each patch.
69
+ num_channels (`int`, *optional*, defaults to 3):
70
+ The number of input channels.
71
+ qkv_bias (`bool`, *optional*, defaults to `True`):
72
+ Whether to add a bias to the queries, keys and values.
73
+ max_image_length (`int`, *optional*, defaults to -1):
74
+ The maximum number of patches to take as input for the Transformer encoder. If set to a positive integer,
75
+ the encoder will sample `max_image_length` patches at maximum. If set to -1, will not be taken into
76
+ account.
77
+ num_images (`int`, *optional*, defaults to -1):
78
+ The number of images to use for natural language visual reasoning. If set to a positive integer, will be
79
+ used by [`ViltForImagesAndTextClassification`] for defining the classifier head.
80
+
81
+ Example:
82
+
83
+ ```python
84
+ >>> from transformers import ViLTModel, ViLTConfig
85
+
86
+ >>> # Initializing a ViLT dandelin/vilt-b32-mlm style configuration
87
+ >>> configuration = ViLTConfig()
88
+
89
+ >>> # Initializing a model from the dandelin/vilt-b32-mlm style configuration
90
+ >>> model = ViLTModel(configuration)
91
+
92
+ >>> # Accessing the model configuration
93
+ >>> configuration = model.config
94
+ ```"""
95
+
96
+ model_type = "vilt"
97
+
98
+ def __init__(
99
+ self,
100
+ vocab_size=30522,
101
+ type_vocab_size=2,
102
+ modality_type_vocab_size=2,
103
+ max_position_embeddings=40,
104
+ hidden_size=768,
105
+ num_hidden_layers=12,
106
+ num_attention_heads=12,
107
+ intermediate_size=3072,
108
+ hidden_act="gelu",
109
+ hidden_dropout_prob=0.0,
110
+ attention_probs_dropout_prob=0.0,
111
+ initializer_range=0.02,
112
+ layer_norm_eps=1e-12,
113
+ image_size=384,
114
+ patch_size=32,
115
+ num_channels=3,
116
+ qkv_bias=True,
117
+ max_image_length=-1,
118
+ tie_word_embeddings=False,
119
+ num_images=-1,
120
+ **kwargs,
121
+ ):
122
+ super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
123
+
124
+ self.vocab_size = vocab_size
125
+ self.type_vocab_size = type_vocab_size
126
+ self.modality_type_vocab_size = modality_type_vocab_size
127
+ self.max_position_embeddings = max_position_embeddings
128
+
129
+ self.hidden_size = hidden_size
130
+ self.num_hidden_layers = num_hidden_layers
131
+ self.num_attention_heads = num_attention_heads
132
+ self.intermediate_size = intermediate_size
133
+ self.hidden_act = hidden_act
134
+ self.hidden_dropout_prob = hidden_dropout_prob
135
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
136
+ self.initializer_range = initializer_range
137
+ self.layer_norm_eps = layer_norm_eps
138
+
139
+ self.image_size = image_size
140
+ self.patch_size = patch_size
141
+ self.num_channels = num_channels
142
+ self.qkv_bias = qkv_bias
143
+ self.max_image_length = max_image_length
144
+ self.num_images = num_images
145
+
146
+
147
+ __all__ = ["ViltConfig"]
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/vilt/convert_vilt_original_to_pytorch.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team.
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
+ """Convert ViLT checkpoints from the original Github repository."""
16
+
17
+ import argparse
18
+ import json
19
+ from pathlib import Path
20
+
21
+ import requests
22
+ import torch
23
+ from huggingface_hub import hf_hub_download
24
+ from PIL import Image
25
+
26
+ from transformers import (
27
+ BertTokenizer,
28
+ ViltConfig,
29
+ ViltForImageAndTextRetrieval,
30
+ ViltForImagesAndTextClassification,
31
+ ViltForMaskedLM,
32
+ ViltForQuestionAnswering,
33
+ ViltImageProcessor,
34
+ ViltProcessor,
35
+ )
36
+ from transformers.utils import logging
37
+
38
+
39
+ logging.set_verbosity_info()
40
+ logger = logging.get_logger(__name__)
41
+
42
+
43
+ # here we list all keys to be renamed (original name on the left, our name on the right)
44
+ def create_rename_keys(config, vqa_model=False, nlvr_model=False, irtr_model=False):
45
+ rename_keys = []
46
+ for i in range(config.num_hidden_layers):
47
+ # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
48
+ rename_keys.append((f"transformer.blocks.{i}.norm1.weight", f"vilt.encoder.layer.{i}.layernorm_before.weight"))
49
+ rename_keys.append((f"transformer.blocks.{i}.norm1.bias", f"vilt.encoder.layer.{i}.layernorm_before.bias"))
50
+ rename_keys.append(
51
+ (f"transformer.blocks.{i}.attn.proj.weight", f"vilt.encoder.layer.{i}.attention.output.dense.weight")
52
+ )
53
+ rename_keys.append(
54
+ (f"transformer.blocks.{i}.attn.proj.bias", f"vilt.encoder.layer.{i}.attention.output.dense.bias")
55
+ )
56
+ rename_keys.append((f"transformer.blocks.{i}.norm2.weight", f"vilt.encoder.layer.{i}.layernorm_after.weight"))
57
+ rename_keys.append((f"transformer.blocks.{i}.norm2.bias", f"vilt.encoder.layer.{i}.layernorm_after.bias"))
58
+ rename_keys.append(
59
+ (f"transformer.blocks.{i}.mlp.fc1.weight", f"vilt.encoder.layer.{i}.intermediate.dense.weight")
60
+ )
61
+ rename_keys.append((f"transformer.blocks.{i}.mlp.fc1.bias", f"vilt.encoder.layer.{i}.intermediate.dense.bias"))
62
+ rename_keys.append((f"transformer.blocks.{i}.mlp.fc2.weight", f"vilt.encoder.layer.{i}.output.dense.weight"))
63
+ rename_keys.append((f"transformer.blocks.{i}.mlp.fc2.bias", f"vilt.encoder.layer.{i}.output.dense.bias"))
64
+
65
+ # embeddings
66
+ rename_keys.extend(
67
+ [
68
+ # text embeddings
69
+ ("text_embeddings.word_embeddings.weight", "vilt.embeddings.text_embeddings.word_embeddings.weight"),
70
+ (
71
+ "text_embeddings.position_embeddings.weight",
72
+ "vilt.embeddings.text_embeddings.position_embeddings.weight",
73
+ ),
74
+ ("text_embeddings.position_ids", "vilt.embeddings.text_embeddings.position_ids"),
75
+ (
76
+ "text_embeddings.token_type_embeddings.weight",
77
+ "vilt.embeddings.text_embeddings.token_type_embeddings.weight",
78
+ ),
79
+ ("text_embeddings.LayerNorm.weight", "vilt.embeddings.text_embeddings.LayerNorm.weight"),
80
+ ("text_embeddings.LayerNorm.bias", "vilt.embeddings.text_embeddings.LayerNorm.bias"),
81
+ # patch embeddings
82
+ ("transformer.cls_token", "vilt.embeddings.cls_token"),
83
+ ("transformer.patch_embed.proj.weight", "vilt.embeddings.patch_embeddings.projection.weight"),
84
+ ("transformer.patch_embed.proj.bias", "vilt.embeddings.patch_embeddings.projection.bias"),
85
+ ("transformer.pos_embed", "vilt.embeddings.position_embeddings"),
86
+ # token type embeddings
87
+ ("token_type_embeddings.weight", "vilt.embeddings.token_type_embeddings.weight"),
88
+ ]
89
+ )
90
+
91
+ # final layernorm + pooler
92
+ rename_keys.extend(
93
+ [
94
+ ("transformer.norm.weight", "vilt.layernorm.weight"),
95
+ ("transformer.norm.bias", "vilt.layernorm.bias"),
96
+ ("pooler.dense.weight", "vilt.pooler.dense.weight"),
97
+ ("pooler.dense.bias", "vilt.pooler.dense.bias"),
98
+ ]
99
+ )
100
+
101
+ # classifier head(s)
102
+ if vqa_model:
103
+ # classification head
104
+ rename_keys.extend(
105
+ [
106
+ ("vqa_classifier.0.weight", "classifier.0.weight"),
107
+ ("vqa_classifier.0.bias", "classifier.0.bias"),
108
+ ("vqa_classifier.1.weight", "classifier.1.weight"),
109
+ ("vqa_classifier.1.bias", "classifier.1.bias"),
110
+ ("vqa_classifier.3.weight", "classifier.3.weight"),
111
+ ("vqa_classifier.3.bias", "classifier.3.bias"),
112
+ ]
113
+ )
114
+ elif nlvr_model:
115
+ # classification head
116
+ rename_keys.extend(
117
+ [
118
+ ("nlvr2_classifier.0.weight", "classifier.0.weight"),
119
+ ("nlvr2_classifier.0.bias", "classifier.0.bias"),
120
+ ("nlvr2_classifier.1.weight", "classifier.1.weight"),
121
+ ("nlvr2_classifier.1.bias", "classifier.1.bias"),
122
+ ("nlvr2_classifier.3.weight", "classifier.3.weight"),
123
+ ("nlvr2_classifier.3.bias", "classifier.3.bias"),
124
+ ]
125
+ )
126
+ else:
127
+ pass
128
+
129
+ return rename_keys
130
+
131
+
132
+ # we split up the matrix of each encoder layer into queries, keys and values
133
+ def read_in_q_k_v(state_dict, config):
134
+ for i in range(config.num_hidden_layers):
135
+ prefix = "vilt."
136
+ # read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
137
+ in_proj_weight = state_dict.pop(f"transformer.blocks.{i}.attn.qkv.weight")
138
+ in_proj_bias = state_dict.pop(f"transformer.blocks.{i}.attn.qkv.bias")
139
+ # next, add query, keys and values (in that order) to the state dict
140
+ state_dict[f"{prefix}encoder.layer.{i}.attention.attention.query.weight"] = in_proj_weight[
141
+ : config.hidden_size, :
142
+ ]
143
+ state_dict[f"{prefix}encoder.layer.{i}.attention.attention.query.bias"] = in_proj_bias[: config.hidden_size]
144
+ state_dict[f"{prefix}encoder.layer.{i}.attention.attention.key.weight"] = in_proj_weight[
145
+ config.hidden_size : config.hidden_size * 2, :
146
+ ]
147
+ state_dict[f"{prefix}encoder.layer.{i}.attention.attention.key.bias"] = in_proj_bias[
148
+ config.hidden_size : config.hidden_size * 2
149
+ ]
150
+ state_dict[f"{prefix}encoder.layer.{i}.attention.attention.value.weight"] = in_proj_weight[
151
+ -config.hidden_size :, :
152
+ ]
153
+ state_dict[f"{prefix}encoder.layer.{i}.attention.attention.value.bias"] = in_proj_bias[-config.hidden_size :]
154
+
155
+
156
+ def remove_classification_head_(state_dict):
157
+ ignore_keys = ["head.weight", "head.bias"]
158
+ for k in ignore_keys:
159
+ state_dict.pop(k, None)
160
+
161
+
162
+ def rename_key(dct, old, new):
163
+ val = dct.pop(old)
164
+ dct[new] = val
165
+
166
+
167
+ @torch.no_grad()
168
+ def convert_vilt_checkpoint(checkpoint_url, pytorch_dump_folder_path):
169
+ """
170
+ Copy/paste/tweak model's weights to our ViLT structure.
171
+ """
172
+
173
+ # define configuration and initialize HuggingFace model
174
+ config = ViltConfig(image_size=384, patch_size=32, tie_word_embeddings=False)
175
+ mlm_model = False
176
+ vqa_model = False
177
+ nlvr_model = False
178
+ irtr_model = False
179
+ if "vqa" in checkpoint_url:
180
+ vqa_model = True
181
+ config.num_labels = 3129
182
+ repo_id = "huggingface/label-files"
183
+ filename = "vqa2-id2label.json"
184
+ id2label = json.load(open(hf_hub_download(repo_id, filename, repo_type="dataset"), "r"))
185
+ id2label = {int(k): v for k, v in id2label.items()}
186
+ config.id2label = id2label
187
+ config.label2id = {v: k for k, v in id2label.items()}
188
+ model = ViltForQuestionAnswering(config)
189
+ elif "nlvr" in checkpoint_url:
190
+ nlvr_model = True
191
+ config.num_labels = 2
192
+ config.id2label = {0: "False", 1: "True"}
193
+ config.label2id = {v: k for k, v in config.id2label.items()}
194
+ config.modality_type_vocab_size = 3
195
+ model = ViltForImagesAndTextClassification(config)
196
+ elif "irtr" in checkpoint_url:
197
+ irtr_model = True
198
+ model = ViltForImageAndTextRetrieval(config)
199
+ elif "mlm_itm" in checkpoint_url:
200
+ mlm_model = True
201
+ model = ViltForMaskedLM(config)
202
+ else:
203
+ raise ValueError("Unknown model type")
204
+
205
+ # load state_dict of original model, remove and rename some keys
206
+ state_dict = torch.hub.load_state_dict_from_url(checkpoint_url, map_location="cpu")["state_dict"]
207
+ rename_keys = create_rename_keys(config, vqa_model, nlvr_model, irtr_model)
208
+ for src, dest in rename_keys:
209
+ rename_key(state_dict, src, dest)
210
+ read_in_q_k_v(state_dict, config)
211
+ if mlm_model or irtr_model:
212
+ ignore_keys = ["itm_score.fc.weight", "itm_score.fc.bias"]
213
+ for k in ignore_keys:
214
+ state_dict.pop(k, None)
215
+
216
+ # load state dict into HuggingFace model
217
+ model.eval()
218
+ if mlm_model:
219
+ missing_keys, unexpected_keys = model.load_state_dict(state_dict, strict=False)
220
+ assert missing_keys == ["mlm_score.decoder.bias"]
221
+ else:
222
+ model.load_state_dict(state_dict)
223
+
224
+ # Define processor
225
+ image_processor = ViltImageProcessor(size=384)
226
+ tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-uncased")
227
+ processor = ViltProcessor(image_processor, tokenizer)
228
+
229
+ # Forward pass on example inputs (image + text)
230
+ if nlvr_model:
231
+ image1 = Image.open(requests.get("https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg", stream=True).raw)
232
+ image2 = Image.open(requests.get("https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg", stream=True).raw)
233
+ text = (
234
+ "The left image contains twice the number of dogs as the right image, and at least two dogs in total are"
235
+ " standing."
236
+ )
237
+ encoding_1 = processor(image1, text, return_tensors="pt")
238
+ encoding_2 = processor(image2, text, return_tensors="pt")
239
+ outputs = model(
240
+ input_ids=encoding_1.input_ids,
241
+ pixel_values=encoding_1.pixel_values,
242
+ pixel_values_2=encoding_2.pixel_values,
243
+ )
244
+ else:
245
+ image = Image.open(requests.get("http://images.cocodataset.org/val2017/000000039769.jpg", stream=True).raw)
246
+ if mlm_model:
247
+ text = "a bunch of [MASK] laying on a [MASK]."
248
+ else:
249
+ text = "How many cats are there?"
250
+ encoding = processor(image, text, return_tensors="pt")
251
+ outputs = model(**encoding)
252
+
253
+ # Verify outputs
254
+ if mlm_model:
255
+ expected_shape = torch.Size([1, 11, 30522])
256
+ expected_slice = torch.tensor([-12.5061, -12.5123, -12.5174])
257
+ assert outputs.logits.shape == expected_shape
258
+ assert torch.allclose(outputs.logits[0, 0, :3], expected_slice, atol=1e-4)
259
+
260
+ # verify masked token prediction equals "cats"
261
+ predicted_id = outputs.logits[0, 4, :].argmax(-1).item()
262
+ assert tokenizer.decode([predicted_id]) == "cats"
263
+ elif vqa_model:
264
+ expected_shape = torch.Size([1, 3129])
265
+ expected_slice = torch.tensor([-15.9495, -18.1472, -10.3041])
266
+ assert torch.allclose(outputs.logits[0, :3], expected_slice, atol=1e-4)
267
+ assert outputs.logits.shape == expected_shape
268
+ assert torch.allclose(outputs.logits[0, 0, :3], expected_slice, atol=1e-4)
269
+
270
+ # verify vqa prediction equals "2"
271
+ predicted_idx = outputs.logits.argmax(-1).item()
272
+ assert model.config.id2label[predicted_idx] == "2"
273
+ elif nlvr_model:
274
+ expected_shape = torch.Size([1, 2])
275
+ expected_slice = torch.tensor([-2.8721, 2.1291])
276
+ assert torch.allclose(outputs.logits[0, :3], expected_slice, atol=1e-4)
277
+ assert outputs.logits.shape == expected_shape
278
+
279
+ Path(pytorch_dump_folder_path).mkdir(exist_ok=True)
280
+ print(f"Saving model and processor to {pytorch_dump_folder_path}")
281
+ model.save_pretrained(pytorch_dump_folder_path)
282
+ processor.save_pretrained(pytorch_dump_folder_path)
283
+
284
+
285
+ if __name__ == "__main__":
286
+ parser = argparse.ArgumentParser()
287
+ # Required parameters
288
+ parser.add_argument(
289
+ "--checkpoint_url",
290
+ default="https://github.com/dandelin/ViLT/releases/download/200k/vilt_200k_mlm_itm.ckpt",
291
+ type=str,
292
+ help="URL of the checkpoint you'd like to convert.",
293
+ )
294
+ parser.add_argument(
295
+ "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory."
296
+ )
297
+
298
+ args = parser.parse_args()
299
+ convert_vilt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/vilt/feature_extraction_vilt.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team. 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
+ """Feature extractor class for ViLT."""
16
+
17
+ import warnings
18
+
19
+ from ...utils import logging
20
+ from ...utils.import_utils import requires
21
+ from .image_processing_vilt import ViltImageProcessor
22
+
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+
27
+ @requires(backends=("vision",))
28
+ class ViltFeatureExtractor(ViltImageProcessor):
29
+ def __init__(self, *args, **kwargs) -> None:
30
+ warnings.warn(
31
+ "The class ViltFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please"
32
+ " use ViltImageProcessor instead.",
33
+ FutureWarning,
34
+ )
35
+ super().__init__(*args, **kwargs)
36
+
37
+
38
+ __all__ = ["ViltFeatureExtractor"]
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/vilt/image_processing_vilt.py ADDED
@@ -0,0 +1,492 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team. 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
+ """Image processor class for Vilt."""
16
+
17
+ from collections.abc import Iterable
18
+ from typing import Any, Optional, Union
19
+
20
+ import numpy as np
21
+
22
+ from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
23
+ from ...image_transforms import PaddingMode, pad, resize, to_channel_dimension_format
24
+ from ...image_utils import (
25
+ IMAGENET_STANDARD_MEAN,
26
+ IMAGENET_STANDARD_STD,
27
+ ChannelDimension,
28
+ ImageInput,
29
+ PILImageResampling,
30
+ get_image_size,
31
+ infer_channel_dimension_format,
32
+ is_scaled_image,
33
+ make_list_of_images,
34
+ to_numpy_array,
35
+ valid_images,
36
+ validate_preprocess_arguments,
37
+ )
38
+ from ...utils import TensorType, filter_out_non_signature_kwargs, is_vision_available, logging
39
+ from ...utils.import_utils import requires
40
+
41
+
42
+ if is_vision_available():
43
+ import PIL
44
+
45
+
46
+ logger = logging.get_logger(__name__)
47
+
48
+
49
+ def max_across_indices(values: Iterable[Any]) -> list[Any]:
50
+ """
51
+ Return the maximum value across all indices of an iterable of values.
52
+ """
53
+ return [max(values_i) for values_i in zip(*values)]
54
+
55
+
56
+ def make_pixel_mask(
57
+ image: np.ndarray, output_size: tuple[int, int], input_data_format: Optional[Union[str, ChannelDimension]] = None
58
+ ) -> np.ndarray:
59
+ """
60
+ Make a pixel mask for the image, where 1 indicates a valid pixel and 0 indicates padding.
61
+
62
+ Args:
63
+ image (`np.ndarray`):
64
+ Image to make the pixel mask for.
65
+ output_size (`tuple[int, int]`):
66
+ Output size of the mask.
67
+ """
68
+ input_height, input_width = get_image_size(image, channel_dim=input_data_format)
69
+ mask = np.zeros(output_size, dtype=np.int64)
70
+ mask[:input_height, :input_width] = 1
71
+ return mask
72
+
73
+
74
+ def get_max_height_width(
75
+ images: list[np.ndarray], input_data_format: Optional[Union[str, ChannelDimension]] = None
76
+ ) -> list[int]:
77
+ """
78
+ Get the maximum height and width across all images in a batch.
79
+ """
80
+ if input_data_format is None:
81
+ input_data_format = infer_channel_dimension_format(images[0])
82
+
83
+ if input_data_format == ChannelDimension.FIRST:
84
+ _, max_height, max_width = max_across_indices([img.shape for img in images])
85
+ elif input_data_format == ChannelDimension.LAST:
86
+ max_height, max_width, _ = max_across_indices([img.shape for img in images])
87
+ else:
88
+ raise ValueError(f"Invalid channel dimension format: {input_data_format}")
89
+ return (max_height, max_width)
90
+
91
+
92
+ def get_resize_output_image_size(
93
+ input_image: np.ndarray,
94
+ shorter: int = 800,
95
+ longer: int = 1333,
96
+ size_divisor: int = 32,
97
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
98
+ ) -> tuple[int, int]:
99
+ input_height, input_width = get_image_size(input_image, input_data_format)
100
+ min_size, max_size = shorter, longer
101
+
102
+ scale = min_size / min(input_height, input_width)
103
+
104
+ if input_height < input_width:
105
+ new_height = min_size
106
+ new_width = scale * input_width
107
+ else:
108
+ new_height = scale * input_height
109
+ new_width = min_size
110
+
111
+ if max(new_height, new_width) > max_size:
112
+ scale = max_size / max(new_height, new_width)
113
+ new_height = scale * new_height
114
+ new_width = scale * new_width
115
+
116
+ new_height, new_width = int(new_height + 0.5), int(new_width + 0.5)
117
+ new_height = new_height // size_divisor * size_divisor
118
+ new_width = new_width // size_divisor * size_divisor
119
+
120
+ return new_height, new_width
121
+
122
+
123
+ @requires(backends=("vision",))
124
+ class ViltImageProcessor(BaseImageProcessor):
125
+ r"""
126
+ Constructs a ViLT image processor.
127
+
128
+ Args:
129
+ do_resize (`bool`, *optional*, defaults to `True`):
130
+ Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by the
131
+ `do_resize` parameter in the `preprocess` method.
132
+ size (`dict[str, int]` *optional*, defaults to `{"shortest_edge": 384}`):
133
+ Resize the shorter side of the input to `size["shortest_edge"]`. The longer side will be limited to under
134
+ `int((1333 / 800) * size["shortest_edge"])` while preserving the aspect ratio. Only has an effect if
135
+ `do_resize` is set to `True`. Can be overridden by the `size` parameter in the `preprocess` method.
136
+ size_divisor (`int`, *optional*, defaults to 32):
137
+ The size by which to make sure both the height and width can be divided. Only has an effect if `do_resize`
138
+ is set to `True`. Can be overridden by the `size_divisor` parameter in the `preprocess` method.
139
+ resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`):
140
+ Resampling filter to use if resizing the image. Only has an effect if `do_resize` is set to `True`. Can be
141
+ overridden by the `resample` parameter in the `preprocess` method.
142
+ do_rescale (`bool`, *optional*, defaults to `True`):
143
+ Wwhether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the
144
+ `do_rescale` parameter in the `preprocess` method.
145
+ rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
146
+ Scale factor to use if rescaling the image. Only has an effect if `do_rescale` is set to `True`. Can be
147
+ overridden by the `rescale_factor` parameter in the `preprocess` method.
148
+ do_normalize (`bool`, *optional*, defaults to `True`):
149
+ Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
150
+ method. Can be overridden by the `do_normalize` parameter in the `preprocess` method.
151
+ image_mean (`float` or `list[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
152
+ Mean to use if normalizing the image. This is a float or list of floats the length of the number of
153
+ channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method. Can be
154
+ overridden by the `image_mean` parameter in the `preprocess` method.
155
+ image_std (`float` or `list[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
156
+ Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
157
+ number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
158
+ Can be overridden by the `image_std` parameter in the `preprocess` method.
159
+ do_pad (`bool`, *optional*, defaults to `True`):
160
+ Whether to pad the image to the `(max_height, max_width)` of the images in the batch. Can be overridden by
161
+ the `do_pad` parameter in the `preprocess` method.
162
+ """
163
+
164
+ model_input_names = ["pixel_values"]
165
+
166
+ def __init__(
167
+ self,
168
+ do_resize: bool = True,
169
+ size: Optional[dict[str, int]] = None,
170
+ size_divisor: int = 32,
171
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
172
+ do_rescale: bool = True,
173
+ rescale_factor: Union[int, float] = 1 / 255,
174
+ do_normalize: bool = True,
175
+ image_mean: Optional[Union[float, list[float]]] = None,
176
+ image_std: Optional[Union[float, list[float]]] = None,
177
+ do_pad: bool = True,
178
+ **kwargs,
179
+ ) -> None:
180
+ if "pad_and_return_pixel_mask" in kwargs:
181
+ do_pad = kwargs.pop("pad_and_return_pixel_mask")
182
+
183
+ super().__init__(**kwargs)
184
+ size = size if size is not None else {"shortest_edge": 384}
185
+ size = get_size_dict(size, default_to_square=False)
186
+
187
+ self.do_resize = do_resize
188
+ self.size = size
189
+ self.size_divisor = size_divisor
190
+ self.resample = resample
191
+ self.do_rescale = do_rescale
192
+ self.rescale_factor = rescale_factor
193
+ self.do_normalize = do_normalize
194
+ self.image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
195
+ self.image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD
196
+ self.do_pad = do_pad
197
+
198
+ @classmethod
199
+ def from_dict(cls, image_processor_dict: dict[str, Any], **kwargs):
200
+ """
201
+ Overrides the `from_dict` method from the base class to make sure `pad_and_return_pixel_mask` is updated if image processor
202
+ is created using from_dict and kwargs e.g. `ViltImageProcessor.from_pretrained(checkpoint,
203
+ pad_and_return_pixel_mask=False)`
204
+ """
205
+ image_processor_dict = image_processor_dict.copy()
206
+ if "pad_and_return_pixel_mask" in kwargs:
207
+ image_processor_dict["pad_and_return_pixel_mask"] = kwargs.pop("pad_and_return_pixel_mask")
208
+ return super().from_dict(image_processor_dict, **kwargs)
209
+
210
+ def resize(
211
+ self,
212
+ image: np.ndarray,
213
+ size: dict[str, int],
214
+ size_divisor: int = 32,
215
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
216
+ data_format: Optional[Union[str, ChannelDimension]] = None,
217
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
218
+ **kwargs,
219
+ ) -> np.ndarray:
220
+ """
221
+ Resize an image.
222
+
223
+ Resizes the shorter side of the image to `size["shortest_edge"]` while preserving the aspect ratio. If the
224
+ longer side is larger than the max size `(int(`size["shortest_edge"]` * 1333 / 800))`, the longer side is then
225
+ resized to the max size while preserving the aspect ratio.
226
+
227
+ Args:
228
+ image (`np.ndarray`):
229
+ Image to resize.
230
+ size (`dict[str, int]`):
231
+ Controls the size of the output image. Should be of the form `{"shortest_edge": int}`.
232
+ size_divisor (`int`, *optional*, defaults to 32):
233
+ The image is resized to a size that is a multiple of this value.
234
+ resample (`PILImageResampling` filter, *optional*, defaults to `PILImageResampling.BICUBIC`):
235
+ Resampling filter to use when resiizing the image.
236
+ data_format (`str` or `ChannelDimension`, *optional*):
237
+ The channel dimension format of the image. If not provided, it will be the same as the input image.
238
+ input_data_format (`str` or `ChannelDimension`, *optional*):
239
+ The channel dimension format of the input image. If not provided, it will be inferred.
240
+ """
241
+ size = get_size_dict(size, default_to_square=False)
242
+ if "shortest_edge" not in size:
243
+ raise ValueError(f"The `size` dictionary must contain the key `shortest_edge`. Got {size.keys()}")
244
+ shorter = size["shortest_edge"]
245
+ longer = int(1333 / 800 * shorter)
246
+ output_size = get_resize_output_image_size(
247
+ image, shorter=shorter, longer=longer, size_divisor=size_divisor, input_data_format=input_data_format
248
+ )
249
+ return resize(
250
+ image,
251
+ size=output_size,
252
+ resample=resample,
253
+ data_format=data_format,
254
+ input_data_format=input_data_format,
255
+ **kwargs,
256
+ )
257
+
258
+ def _pad_image(
259
+ self,
260
+ image: np.ndarray,
261
+ output_size: tuple[int, int],
262
+ constant_values: Union[float, Iterable[float]] = 0,
263
+ data_format: Optional[ChannelDimension] = None,
264
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
265
+ ) -> np.ndarray:
266
+ """
267
+ Pad an image with zeros to the given size.
268
+ """
269
+ input_height, input_width = get_image_size(image, channel_dim=input_data_format)
270
+ output_height, output_width = output_size
271
+
272
+ pad_bottom = output_height - input_height
273
+ pad_right = output_width - input_width
274
+ padding = ((0, pad_bottom), (0, pad_right))
275
+ padded_image = pad(
276
+ image,
277
+ padding,
278
+ mode=PaddingMode.CONSTANT,
279
+ constant_values=constant_values,
280
+ data_format=data_format,
281
+ input_data_format=input_data_format,
282
+ )
283
+ return padded_image
284
+
285
+ def pad(
286
+ self,
287
+ images: list[np.ndarray],
288
+ constant_values: Union[float, Iterable[float]] = 0,
289
+ return_pixel_mask: bool = True,
290
+ return_tensors: Optional[Union[str, TensorType]] = None,
291
+ data_format: Optional[ChannelDimension] = None,
292
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
293
+ ) -> BatchFeature:
294
+ """
295
+ Pads a batch of images to the bottom and right of the image with zeros to the size of largest height and width
296
+ in the batch and optionally returns their corresponding pixel mask.
297
+
298
+ Args:
299
+ image (`np.ndarray`):
300
+ Image to pad.
301
+ constant_values (`float` or `Iterable[float]`, *optional*):
302
+ The value to use for the padding if `mode` is `"constant"`.
303
+ return_pixel_mask (`bool`, *optional*, defaults to `True`):
304
+ Whether to return a pixel mask.
305
+ return_tensors (`str` or `TensorType`, *optional*):
306
+ The type of tensors to return. Can be one of:
307
+ - Unset: Return a list of `np.ndarray`.
308
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
309
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
310
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
311
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
312
+ data_format (`str` or `ChannelDimension`, *optional*):
313
+ The channel dimension format of the image. If not provided, it will be the same as the input image.
314
+ input_data_format (`ChannelDimension` or `str`, *optional*):
315
+ The channel dimension format of the input image. If not provided, it will be inferred.
316
+ """
317
+ pad_size = get_max_height_width(images, input_data_format=input_data_format)
318
+
319
+ padded_images = [
320
+ self._pad_image(
321
+ image,
322
+ pad_size,
323
+ constant_values=constant_values,
324
+ data_format=data_format,
325
+ input_data_format=input_data_format,
326
+ )
327
+ for image in images
328
+ ]
329
+ data = {"pixel_values": padded_images}
330
+
331
+ if return_pixel_mask:
332
+ masks = [
333
+ make_pixel_mask(image=image, output_size=pad_size, input_data_format=input_data_format)
334
+ for image in images
335
+ ]
336
+ data["pixel_mask"] = masks
337
+
338
+ return BatchFeature(data=data, tensor_type=return_tensors)
339
+
340
+ @filter_out_non_signature_kwargs()
341
+ def preprocess(
342
+ self,
343
+ images: ImageInput,
344
+ do_resize: Optional[bool] = None,
345
+ size: Optional[dict[str, int]] = None,
346
+ size_divisor: Optional[int] = None,
347
+ resample: PILImageResampling = None,
348
+ do_rescale: Optional[bool] = None,
349
+ rescale_factor: Optional[float] = None,
350
+ do_normalize: Optional[bool] = None,
351
+ image_mean: Optional[Union[float, list[float]]] = None,
352
+ image_std: Optional[Union[float, list[float]]] = None,
353
+ do_pad: Optional[bool] = None,
354
+ return_tensors: Optional[Union[str, TensorType]] = None,
355
+ data_format: ChannelDimension = ChannelDimension.FIRST,
356
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
357
+ ) -> PIL.Image.Image:
358
+ """
359
+ Preprocess an image or batch of images.
360
+
361
+ Args:
362
+ images (`ImageInput`):
363
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
364
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
365
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
366
+ Whether to resize the image.
367
+ size (`dict[str, int]`, *optional*, defaults to `self.size`):
368
+ Controls the size of the image after `resize`. The shortest edge of the image is resized to
369
+ `size["shortest_edge"]` whilst preserving the aspect ratio. If the longest edge of this resized image
370
+ is > `int(size["shortest_edge"] * (1333 / 800))`, then the image is resized again to make the longest
371
+ edge equal to `int(size["shortest_edge"] * (1333 / 800))`.
372
+ size_divisor (`int`, *optional*, defaults to `self.size_divisor`):
373
+ The image is resized to a size that is a multiple of this value.
374
+ resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
375
+ Resampling filter to use if resizing the image. Only has an effect if `do_resize` is set to `True`.
376
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
377
+ Whether to rescale the image values between [0 - 1].
378
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
379
+ Rescale factor to rescale the image by if `do_rescale` is set to `True`.
380
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
381
+ Whether to normalize the image.
382
+ image_mean (`float` or `list[float]`, *optional*, defaults to `self.image_mean`):
383
+ Image mean to normalize the image by if `do_normalize` is set to `True`.
384
+ image_std (`float` or `list[float]`, *optional*, defaults to `self.image_std`):
385
+ Image standard deviation to normalize the image by if `do_normalize` is set to `True`.
386
+ do_pad (`bool`, *optional*, defaults to `self.do_pad`):
387
+ Whether to pad the image to the (max_height, max_width) in the batch. If `True`, a pixel mask is also
388
+ created and returned.
389
+ return_tensors (`str` or `TensorType`, *optional*):
390
+ The type of tensors to return. Can be one of:
391
+ - Unset: Return a list of `np.ndarray`.
392
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
393
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
394
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
395
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
396
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
397
+ The channel dimension format for the output image. Can be one of:
398
+ - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
399
+ - `ChannelDimension.LAST`: image in (height, width, num_channels) format.
400
+ input_data_format (`ChannelDimension` or `str`, *optional*):
401
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
402
+ from the input image. Can be one of:
403
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
404
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
405
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
406
+ """
407
+ do_resize = do_resize if do_resize is not None else self.do_resize
408
+ size_divisor = size_divisor if size_divisor is not None else self.size_divisor
409
+ resample = resample if resample is not None else self.resample
410
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
411
+ rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
412
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
413
+ image_mean = image_mean if image_mean is not None else self.image_mean
414
+ image_std = image_std if image_std is not None else self.image_std
415
+ do_pad = do_pad if do_pad is not None else self.do_pad
416
+
417
+ size = size if size is not None else self.size
418
+ size = get_size_dict(size, default_to_square=False)
419
+
420
+ images = make_list_of_images(images)
421
+
422
+ if not valid_images(images):
423
+ raise ValueError(
424
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
425
+ "torch.Tensor, tf.Tensor or jax.ndarray."
426
+ )
427
+
428
+ # Here the pad() method does not require any additional argument as it takes the maximum of (height, width).
429
+ # Hence, it does not need to be passed to a validate_preprocess_arguments() method.
430
+ validate_preprocess_arguments(
431
+ do_rescale=do_rescale,
432
+ rescale_factor=rescale_factor,
433
+ do_normalize=do_normalize,
434
+ image_mean=image_mean,
435
+ image_std=image_std,
436
+ do_resize=do_resize,
437
+ size=size,
438
+ resample=resample,
439
+ )
440
+
441
+ # All transformations expect numpy arrays.
442
+ images = [to_numpy_array(image) for image in images]
443
+
444
+ if do_rescale and is_scaled_image(images[0]):
445
+ logger.warning_once(
446
+ "It looks like you are trying to rescale already rescaled images. If the input"
447
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
448
+ )
449
+
450
+ if input_data_format is None:
451
+ # We assume that all images have the same channel dimension format.
452
+ input_data_format = infer_channel_dimension_format(images[0])
453
+
454
+ if do_resize:
455
+ images = [
456
+ self.resize(
457
+ image=image,
458
+ size=size,
459
+ size_divisor=size_divisor,
460
+ resample=resample,
461
+ input_data_format=input_data_format,
462
+ )
463
+ for image in images
464
+ ]
465
+
466
+ if do_rescale:
467
+ images = [
468
+ self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
469
+ for image in images
470
+ ]
471
+
472
+ if do_normalize:
473
+ images = [
474
+ self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
475
+ for image in images
476
+ ]
477
+
478
+ images = [
479
+ to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images
480
+ ]
481
+
482
+ if do_pad:
483
+ encoded_outputs = self.pad(
484
+ images, return_pixel_mask=True, return_tensors=return_tensors, input_data_format=data_format
485
+ )
486
+ else:
487
+ encoded_outputs = BatchFeature(data={"pixel_values": images}, tensor_type=return_tensors)
488
+
489
+ return encoded_outputs
490
+
491
+
492
+ __all__ = ["ViltImageProcessor"]
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/vilt/image_processing_vilt_fast.py ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 The HuggingFace Inc. team. 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
+ """Fast Image processor class for Vilt."""
16
+
17
+ from typing import Optional, Union
18
+
19
+ from ...image_processing_utils import BatchFeature
20
+ from ...image_processing_utils_fast import (
21
+ BaseImageProcessorFast,
22
+ DefaultFastImageProcessorKwargs,
23
+ get_max_height_width,
24
+ group_images_by_shape,
25
+ reorder_images,
26
+ )
27
+ from ...image_utils import IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, PILImageResampling, SizeDict
28
+ from ...utils import (
29
+ TensorType,
30
+ auto_docstring,
31
+ is_torch_available,
32
+ is_torchvision_available,
33
+ is_torchvision_v2_available,
34
+ )
35
+
36
+
37
+ if is_torch_available():
38
+ import torch
39
+
40
+ if is_torchvision_available():
41
+ if is_torchvision_v2_available():
42
+ from torchvision.transforms.v2 import functional as F
43
+ else:
44
+ from torchvision.transforms import functional as F
45
+
46
+ # Set maximum size based on the typical aspect ratio of the COCO dataset
47
+ MAX_LONGER_EDGE = 1333
48
+ MAX_SHORTER_EDGE = 800
49
+
50
+
51
+ class ViltFastImageProcessorKwargs(DefaultFastImageProcessorKwargs):
52
+ """
53
+ Args:
54
+ do_pad (`bool`, *optional*, defaults to `True`):
55
+ Whether to pad the image. If `True`, will pad the images in the batch to the largest height and width
56
+ in the batch. Padding will be applied to the bottom and right with zeros.
57
+ size_divisor (`int`, *optional*, defaults to 32):
58
+ The size to make the height and width divisible by.
59
+ rescale_factor (`float`, *optional*, defaults to 1/255):
60
+ The factor to rescale the image by.
61
+ """
62
+
63
+ do_pad: Optional[bool]
64
+ size_divisor: Optional[int]
65
+ rescale_factor: Optional[float]
66
+
67
+
68
+ @auto_docstring
69
+ class ViltImageProcessorFast(BaseImageProcessorFast):
70
+ resample = PILImageResampling.BICUBIC
71
+ image_mean = IMAGENET_STANDARD_MEAN
72
+ image_std = IMAGENET_STANDARD_STD
73
+ size = {"shortest_edge": 384}
74
+ do_resize = True
75
+ do_rescale = True
76
+ do_normalize = True
77
+ size_divisor = 32
78
+ do_pad = True
79
+ default_to_square = False
80
+ model_input_names = ["pixel_values", "pixel_mask"]
81
+ valid_kwargs = ViltFastImageProcessorKwargs
82
+
83
+ def _preprocess(
84
+ self,
85
+ images: list["torch.Tensor"],
86
+ do_resize: bool,
87
+ size: SizeDict,
88
+ interpolation: Optional["F.InterpolationMode"],
89
+ size_divisor: Optional[int],
90
+ do_pad: bool,
91
+ do_rescale: bool,
92
+ rescale_factor: float,
93
+ do_normalize: bool,
94
+ image_mean: Optional[Union[float, list[float]]],
95
+ image_std: Optional[Union[float, list[float]]],
96
+ disable_grouping: Optional[bool],
97
+ return_tensors: Optional[Union[str, TensorType]],
98
+ **kwargs,
99
+ ) -> BatchFeature:
100
+ """
101
+ Preprocess an image or batch of images.
102
+
103
+ This method overrides the base class method to include padding and pixel mask generation.
104
+ """
105
+ # Group images by size for batched resizing
106
+ grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
107
+ resized_images_grouped = {}
108
+
109
+ for shape, stacked_images in grouped_images.items():
110
+ if do_resize:
111
+ stacked_images = self.resize(stacked_images, size, interpolation, size_divisor)
112
+ resized_images_grouped[shape] = stacked_images
113
+ resized_images = reorder_images(resized_images_grouped, grouped_images_index)
114
+
115
+ # Group images by size for further processing
116
+ grouped_images, grouped_images_index = group_images_by_shape(resized_images, disable_grouping=disable_grouping)
117
+ processed_images_grouped = {}
118
+
119
+ for shape, stacked_images in grouped_images.items():
120
+ # Fused rescale and normalize
121
+ stacked_images = self.rescale_and_normalize(
122
+ stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std
123
+ )
124
+ processed_images_grouped[shape] = stacked_images
125
+
126
+ processed_images = reorder_images(processed_images_grouped, grouped_images_index)
127
+
128
+ # Handle padding if required
129
+ data = {}
130
+ if do_pad:
131
+ pixel_values, pixel_mask = self._pad_batch(
132
+ processed_images, return_tensors, disable_grouping=disable_grouping
133
+ )
134
+ data = {"pixel_values": pixel_values, "pixel_mask": pixel_mask}
135
+ else:
136
+ # If no padding, just return the processed images
137
+ if return_tensors == "pt":
138
+ processed_images = torch.stack(processed_images)
139
+ data = {"pixel_values": processed_images}
140
+
141
+ return BatchFeature(data=data, tensor_type=return_tensors)
142
+
143
+ def resize(
144
+ self,
145
+ images: "torch.Tensor",
146
+ size: SizeDict,
147
+ interpolation: Optional["F.InterpolationMode"] = None,
148
+ size_divisor: Optional[int] = None,
149
+ ) -> "torch.Tensor":
150
+ """
151
+ Resize an image or batch of images to specified size.
152
+
153
+ Args:
154
+ images (`torch.Tensor`): Image or batch of images to resize.
155
+ size (`dict[str, int]`): Size dictionary with shortest_edge key.
156
+ interpolation (`F.InterpolationMode`, *optional*): Interpolation method to use.
157
+ size_divisor (`int`, *optional*): Value to ensure height/width are divisible by.
158
+
159
+ Returns:
160
+ `torch.Tensor`: Resized image or batch of images.
161
+ """
162
+ if interpolation is None:
163
+ interpolation = self.resample
164
+
165
+ # Resize with aspect ratio preservation
166
+ shorter = size.shortest_edge
167
+ longer = int(MAX_LONGER_EDGE / MAX_SHORTER_EDGE * shorter)
168
+
169
+ heights = images.shape[-2]
170
+ widths = images.shape[-1]
171
+
172
+ # Determine the new dimensions
173
+ if heights < widths:
174
+ new_heights = shorter
175
+ new_widths = widths * (shorter / heights)
176
+ else:
177
+ new_heights = heights * (shorter / widths)
178
+ new_widths = shorter
179
+
180
+ # Check if the longer side exceeds max size
181
+ if max(new_heights, new_widths) > longer:
182
+ scale = longer / max(new_heights, new_widths)
183
+ new_heights = new_heights * scale
184
+ new_widths = new_widths * scale
185
+
186
+ new_heights = int(new_heights + 0.5)
187
+ new_widths = int(new_widths + 0.5)
188
+
189
+ # Make dimensions divisible by size_divisor
190
+ if size_divisor is not None:
191
+ new_heights = new_heights // size_divisor * size_divisor
192
+ new_widths = new_widths // size_divisor * size_divisor
193
+
194
+ # Resize the image
195
+ return F.resize(images, [new_heights, new_widths], interpolation=interpolation)
196
+
197
+ def _pad_batch(
198
+ self,
199
+ images: list["torch.Tensor"],
200
+ return_tensors: Optional[Union[str, TensorType]],
201
+ disable_grouping: Optional[bool],
202
+ ) -> tuple:
203
+ """
204
+ Pad a batch of images to the same size based on the maximum dimensions.
205
+
206
+ Args:
207
+ images (`list[torch.Tensor]`): List of images to pad.
208
+ return_tensors (`str` or `TensorType`, *optional*): The type of tensors to return.
209
+
210
+ Returns:
211
+ `tuple`: Tuple containing padded images and pixel masks.
212
+ """
213
+ # Calculate global maximum dimensions across all images
214
+ max_size = get_max_height_width(images)
215
+
216
+ # Group images by shape before padding
217
+ grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
218
+ processed_images = {}
219
+ processed_masks = {}
220
+
221
+ for shape, stacked_images in grouped_images.items():
222
+ # Create mask template for efficient masking
223
+ if return_tensors == "pt" and len(stacked_images) > 0:
224
+ device = stacked_images.device
225
+ mask_template = torch.zeros(max_size, dtype=torch.int64, device=device)
226
+
227
+ original_size = stacked_images.shape[-2:]
228
+ needs_padding = original_size[0] != max_size[0] or original_size[1] != max_size[1]
229
+
230
+ if needs_padding:
231
+ padding_bottom = max_size[0] - original_size[0]
232
+ padding_right = max_size[1] - original_size[1]
233
+ padding = [0, 0, padding_right, padding_bottom]
234
+
235
+ padded_images = F.pad(stacked_images, padding, fill=0)
236
+ pixel_mask = mask_template.clone()
237
+ pixel_mask[: original_size[0], : original_size[1]].fill_(1)
238
+ pixel_masks = pixel_mask.unsqueeze(0).repeat(stacked_images.shape[0], 1, 1)
239
+ else:
240
+ padded_images = stacked_images
241
+ pixel_masks = torch.ones(
242
+ (stacked_images.shape[0], max_size[0], max_size[1]),
243
+ dtype=torch.int64,
244
+ device=stacked_images.device,
245
+ )
246
+
247
+ # Store processed group
248
+ processed_images[shape] = padded_images
249
+ processed_masks[shape] = pixel_masks
250
+
251
+ # Reorder images back to original order
252
+ padded_images = reorder_images(processed_images, grouped_images_index)
253
+ pixel_masks = reorder_images(processed_masks, grouped_images_index)
254
+
255
+ # Stack if tensors are requested for final result
256
+ if return_tensors == "pt" and padded_images:
257
+ padded_images = torch.stack(padded_images)
258
+ pixel_masks = torch.stack(pixel_masks)
259
+
260
+ return padded_images, pixel_masks
261
+
262
+
263
+ __all__ = ["ViltImageProcessorFast"]
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/vilt/modeling_vilt.py ADDED
@@ -0,0 +1,1356 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 NAVER AI Labs and The HuggingFace Inc. team. 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
+ """PyTorch ViLT model."""
16
+
17
+ import collections.abc
18
+ import math
19
+ from dataclasses import dataclass
20
+ from typing import Optional, Union
21
+
22
+ import torch
23
+ import torch.utils.checkpoint
24
+ from torch import nn
25
+ from torch.nn import CrossEntropyLoss
26
+
27
+ from ...activations import ACT2FN
28
+ from ...modeling_layers import GradientCheckpointingLayer
29
+ from ...modeling_outputs import (
30
+ BaseModelOutput,
31
+ BaseModelOutputWithPooling,
32
+ MaskedLMOutput,
33
+ ModelOutput,
34
+ SequenceClassifierOutput,
35
+ TokenClassifierOutput,
36
+ )
37
+ from ...modeling_utils import PreTrainedModel
38
+ from ...pytorch_utils import find_pruneable_heads_and_indices, meshgrid, prune_linear_layer
39
+ from ...utils import auto_docstring, logging
40
+ from .configuration_vilt import ViltConfig
41
+
42
+
43
+ logger = logging.get_logger(__name__)
44
+
45
+
46
+ @dataclass
47
+ @auto_docstring(
48
+ custom_intro="""
49
+ Class for outputs of [`ViltForImagesAndTextClassification`].
50
+ """
51
+ )
52
+ class ViltForImagesAndTextClassificationOutput(ModelOutput):
53
+ r"""
54
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
55
+ Classification (or regression if config.num_labels==1) loss.
56
+ logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
57
+ Classification (or regression if config.num_labels==1) scores (before SoftMax).
58
+ hidden_states (`list[tuple(torch.FloatTensor)]`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
59
+ List of tuples of `torch.FloatTensor` (one for each image-text pair, each tuple containing the output of
60
+ the embeddings + one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
61
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
62
+ """
63
+
64
+ loss: Optional[torch.FloatTensor] = None
65
+ logits: Optional[torch.FloatTensor] = None
66
+ hidden_states: Optional[list[tuple[torch.FloatTensor]]] = None
67
+ attentions: Optional[list[tuple[torch.FloatTensor]]] = None
68
+
69
+
70
+ class ViltEmbeddings(nn.Module):
71
+ """
72
+ Construct the text and patch embeddings.
73
+
74
+ Text embeddings are equivalent to BERT embeddings.
75
+
76
+ Patch embeddings are equivalent to ViT embeddings.
77
+ """
78
+
79
+ def __init__(self, config):
80
+ super().__init__()
81
+
82
+ # text embeddings
83
+ self.text_embeddings = TextEmbeddings(config)
84
+ # patch embeddings
85
+ self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
86
+ self.patch_embeddings = ViltPatchEmbeddings(config)
87
+ num_patches = self.patch_embeddings.num_patches
88
+ self.position_embeddings = nn.Parameter(torch.zeros(1, num_patches + 1, config.hidden_size))
89
+ # modality type (text/patch) embeddings
90
+ self.token_type_embeddings = nn.Embedding(config.modality_type_vocab_size, config.hidden_size)
91
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
92
+ self.config = config
93
+
94
+ def visual_embed(self, pixel_values, pixel_mask, max_image_length=200):
95
+ _, _, ph, pw = self.patch_embeddings.projection.weight.shape
96
+
97
+ x = self.patch_embeddings(pixel_values)
98
+ x_mask = pixel_mask[:, None, :, :].float()
99
+ x_mask = nn.functional.interpolate(x_mask, size=(x.shape[2], x.shape[3])).long()
100
+ x_h = x_mask[:, 0].sum(dim=1)[:, 0]
101
+ x_w = x_mask[:, 0].sum(dim=2)[:, 0]
102
+
103
+ batch_size, num_channels, height, width = x.shape
104
+ patch_dim = self.config.image_size // self.config.patch_size
105
+ spatial_pos = self.position_embeddings[:, 1:, :].transpose(1, 2).view(1, num_channels, patch_dim, patch_dim)
106
+ pos_embed = torch.cat(
107
+ [
108
+ nn.functional.pad(
109
+ nn.functional.interpolate(
110
+ spatial_pos,
111
+ size=(h, w),
112
+ mode="bilinear",
113
+ align_corners=True,
114
+ ),
115
+ (0, width - w, 0, height - h),
116
+ )
117
+ for h, w in zip(x_h, x_w)
118
+ ],
119
+ dim=0,
120
+ )
121
+
122
+ pos_embed = pos_embed.flatten(2).transpose(1, 2)
123
+ x = x.flatten(2).transpose(1, 2)
124
+ # Set `device` here, otherwise `patch_index` will always be on `CPU` and will fail near the end for torch>=1.13
125
+ patch_index = torch.stack(
126
+ meshgrid(torch.arange(x_mask.shape[-2]), torch.arange(x_mask.shape[-1]), indexing="ij"), dim=-1
127
+ ).to(device=x_mask.device)
128
+ patch_index = patch_index[None, None, :, :, :]
129
+ patch_index = patch_index.expand(x_mask.shape[0], x_mask.shape[1], -1, -1, -1)
130
+ patch_index = patch_index.flatten(1, 3)
131
+ x_mask = x_mask.flatten(1)
132
+
133
+ if max_image_length < 0 or max_image_length is None or not isinstance(max_image_length, int):
134
+ # suppose aug is 800 x 1333, then, maximum effective res is 800 x 1333 (if one side gets bigger, the other will be constrained and be shrunk)
135
+ # (800 // self.patch_size) * (1333 // self.patch_size) is the maximum number of patches that single image can get.
136
+ # if self.patch_size = 32, 25 * 41 = 1025
137
+ # if res is 384 x 640, 12 * 20 = 240
138
+ effective_resolution = x_h * x_w
139
+ max_image_length = effective_resolution.max()
140
+ else:
141
+ effective_resolution = x_h * x_w
142
+ max_image_length = min(effective_resolution.max(), max_image_length)
143
+
144
+ valid_idx = x_mask.nonzero(as_tuple=False)
145
+ non_valid_idx = (1 - x_mask).nonzero(as_tuple=False)
146
+ unique_rows = valid_idx[:, 0].unique()
147
+ valid_row_idx = [valid_idx[valid_idx[:, 0] == u] for u in unique_rows]
148
+ non_valid_row_idx = [non_valid_idx[non_valid_idx[:, 0] == u] for u in unique_rows]
149
+
150
+ valid_nums = [v.size(0) for v in valid_row_idx]
151
+ non_valid_nums = [v.size(0) for v in non_valid_row_idx]
152
+ pad_nums = [max_image_length - v for v in valid_nums]
153
+
154
+ select = []
155
+ for i, (v, nv, p) in enumerate(zip(valid_nums, non_valid_nums, pad_nums)):
156
+ if p <= 0:
157
+ valid_choice = torch.multinomial(torch.ones(v).float(), max_image_length)
158
+ select.append(valid_row_idx[i][valid_choice])
159
+ else:
160
+ pad_choice = torch.multinomial(torch.ones(nv).float(), p, replacement=True)
161
+ select.append(torch.cat([valid_row_idx[i], non_valid_row_idx[i][pad_choice]], dim=0))
162
+
163
+ select = torch.cat(select, dim=0)
164
+ x = x[select[:, 0], select[:, 1]].view(batch_size, -1, num_channels)
165
+ x_mask = x_mask[select[:, 0], select[:, 1]].view(batch_size, -1)
166
+ # `patch_index` should be on the same device as `select`, which is ensured at definition time.
167
+ patch_index = patch_index[select[:, 0], select[:, 1]].view(batch_size, -1, 2)
168
+ pos_embed = pos_embed[select[:, 0], select[:, 1]].view(batch_size, -1, num_channels)
169
+
170
+ cls_tokens = self.cls_token.expand(batch_size, -1, -1)
171
+ x = torch.cat((cls_tokens, x), dim=1)
172
+ pos_embed = torch.cat(
173
+ (self.position_embeddings[:, 0, :][:, None, :].expand(batch_size, -1, -1), pos_embed), dim=1
174
+ )
175
+ x = x + pos_embed
176
+ x = self.dropout(x)
177
+
178
+ x_mask = torch.cat([torch.ones(x_mask.shape[0], 1).to(x_mask), x_mask], dim=1)
179
+
180
+ return x, x_mask, (patch_index, (height, width))
181
+
182
+ def forward(
183
+ self,
184
+ input_ids,
185
+ attention_mask,
186
+ token_type_ids,
187
+ pixel_values,
188
+ pixel_mask,
189
+ inputs_embeds,
190
+ image_embeds,
191
+ image_token_type_idx=1,
192
+ ):
193
+ # PART 1: text embeddings
194
+ text_embeds = self.text_embeddings(
195
+ input_ids=input_ids, token_type_ids=token_type_ids, inputs_embeds=inputs_embeds
196
+ )
197
+
198
+ # PART 2: patch embeddings (with interpolated position encodings)
199
+ if image_embeds is None:
200
+ image_embeds, image_masks, patch_index = self.visual_embed(
201
+ pixel_values, pixel_mask, max_image_length=self.config.max_image_length
202
+ )
203
+ else:
204
+ image_masks = pixel_mask.flatten(1)
205
+
206
+ # PART 3: add modality type embeddings
207
+ # 0 indicates text, 1 indicates image, 2 is optionally used when a second image is provided (NLVR2)
208
+ if image_token_type_idx is None:
209
+ image_token_type_idx = 1
210
+ text_embeds = text_embeds + self.token_type_embeddings(
211
+ torch.zeros_like(attention_mask, dtype=torch.long, device=text_embeds.device)
212
+ )
213
+ image_embeds = image_embeds + self.token_type_embeddings(
214
+ torch.full_like(image_masks, image_token_type_idx, dtype=torch.long, device=text_embeds.device)
215
+ )
216
+
217
+ # PART 4: concatenate
218
+ embeddings = torch.cat([text_embeds, image_embeds], dim=1)
219
+ masks = torch.cat([attention_mask, image_masks], dim=1)
220
+
221
+ return embeddings, masks
222
+
223
+
224
+ class TextEmbeddings(nn.Module):
225
+ """Construct the embeddings from word, position and token_type embeddings."""
226
+
227
+ def __init__(self, config):
228
+ super().__init__()
229
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
230
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
231
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
232
+
233
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
234
+ # any TensorFlow checkpoint file
235
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
236
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
237
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
238
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
239
+ self.register_buffer(
240
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
241
+ )
242
+ self.register_buffer(
243
+ "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
244
+ )
245
+
246
+ def forward(self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None):
247
+ if input_ids is not None:
248
+ input_shape = input_ids.size()
249
+ else:
250
+ input_shape = inputs_embeds.size()[:-1]
251
+
252
+ seq_length = input_shape[1]
253
+
254
+ if position_ids is None:
255
+ position_ids = self.position_ids[:, :seq_length]
256
+
257
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
258
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
259
+ # issue #5664
260
+ if token_type_ids is None:
261
+ if hasattr(self, "token_type_ids"):
262
+ buffered_token_type_ids = self.token_type_ids[:, :seq_length]
263
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
264
+ token_type_ids = buffered_token_type_ids_expanded
265
+ else:
266
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
267
+
268
+ if inputs_embeds is None:
269
+ inputs_embeds = self.word_embeddings(input_ids)
270
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
271
+
272
+ embeddings = inputs_embeds + token_type_embeddings
273
+ if self.position_embedding_type == "absolute":
274
+ position_embeddings = self.position_embeddings(position_ids)
275
+ embeddings += position_embeddings
276
+ embeddings = self.LayerNorm(embeddings)
277
+ embeddings = self.dropout(embeddings)
278
+ return embeddings
279
+
280
+
281
+ class ViltPatchEmbeddings(nn.Module):
282
+ """
283
+ Image to Patch Embedding.
284
+ """
285
+
286
+ def __init__(self, config):
287
+ super().__init__()
288
+ image_size, patch_size = config.image_size, config.patch_size
289
+ num_channels, hidden_size = config.num_channels, config.hidden_size
290
+
291
+ image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
292
+ patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
293
+ num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
294
+ self.image_size = image_size
295
+ self.patch_size = patch_size
296
+ self.num_channels = num_channels
297
+ self.num_patches = num_patches
298
+
299
+ self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
300
+
301
+ def forward(self, pixel_values):
302
+ batch_size, num_channels, height, width = pixel_values.shape
303
+ if num_channels != self.num_channels:
304
+ raise ValueError(
305
+ "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
306
+ )
307
+ target_dtype = self.projection.weight.dtype
308
+ x = self.projection(pixel_values.to(dtype=target_dtype))
309
+ return x
310
+
311
+
312
+ class ViltSelfAttention(nn.Module):
313
+ def __init__(self, config):
314
+ super().__init__()
315
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
316
+ raise ValueError(
317
+ f"The hidden size {config.hidden_size} is not a multiple of the number of attention "
318
+ f"heads {config.num_attention_heads}."
319
+ )
320
+
321
+ self.num_attention_heads = config.num_attention_heads
322
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
323
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
324
+
325
+ self.query = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
326
+ self.key = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
327
+ self.value = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
328
+
329
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
330
+
331
+ def forward(self, hidden_states, attention_mask=None, head_mask=None, output_attentions=False):
332
+ batch_size, seq_length, _ = hidden_states.shape
333
+ query_layer = (
334
+ self.query(hidden_states)
335
+ .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
336
+ .transpose(1, 2)
337
+ )
338
+ key_layer = (
339
+ self.key(hidden_states)
340
+ .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
341
+ .transpose(1, 2)
342
+ )
343
+ value_layer = (
344
+ self.value(hidden_states)
345
+ .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
346
+ .transpose(1, 2)
347
+ )
348
+
349
+ # Take the dot product between "query" and "key" to get the raw attention scores.
350
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
351
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
352
+ if attention_mask is not None:
353
+ # Apply the attention mask is (precomputed for all layers in BertModel forward() function)
354
+ attention_scores = attention_scores + attention_mask
355
+
356
+ # Normalize the attention scores to probabilities.
357
+ attention_probs = nn.Softmax(dim=-1)(attention_scores)
358
+
359
+ # This is actually dropping out entire tokens to attend to, which might
360
+ # seem a bit unusual, but is taken from the original Transformer paper.
361
+ attention_probs = self.dropout(attention_probs)
362
+
363
+ # Mask heads if we want to
364
+ if head_mask is not None:
365
+ attention_probs = attention_probs * head_mask
366
+
367
+ context_layer = torch.matmul(attention_probs, value_layer)
368
+
369
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
370
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
371
+ context_layer = context_layer.view(*new_context_layer_shape)
372
+
373
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
374
+
375
+ return outputs
376
+
377
+
378
+ # Copied from transformers.models.vit.modeling_vit.ViTSelfOutput with ViT->Vilt
379
+ class ViltSelfOutput(nn.Module):
380
+ """
381
+ The residual connection is defined in ViltLayer instead of here (as is the case with other models), due to the
382
+ layernorm applied before each block.
383
+ """
384
+
385
+ def __init__(self, config: ViltConfig) -> None:
386
+ super().__init__()
387
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
388
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
389
+
390
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
391
+ hidden_states = self.dense(hidden_states)
392
+ hidden_states = self.dropout(hidden_states)
393
+
394
+ return hidden_states
395
+
396
+
397
+ class ViltAttention(nn.Module):
398
+ def __init__(self, config):
399
+ super().__init__()
400
+ self.attention = ViltSelfAttention(config)
401
+ self.output = ViltSelfOutput(config)
402
+ self.pruned_heads = set()
403
+
404
+ def prune_heads(self, heads):
405
+ if len(heads) == 0:
406
+ return
407
+ heads, index = find_pruneable_heads_and_indices(
408
+ heads, self.attention.num_attention_heads, self.attention.attention_head_size, self.pruned_heads
409
+ )
410
+
411
+ # Prune linear layers
412
+ self.attention.query = prune_linear_layer(self.attention.query, index)
413
+ self.attention.key = prune_linear_layer(self.attention.key, index)
414
+ self.attention.value = prune_linear_layer(self.attention.value, index)
415
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
416
+
417
+ # Update hyper params and store pruned heads
418
+ self.attention.num_attention_heads = self.attention.num_attention_heads - len(heads)
419
+ self.attention.all_head_size = self.attention.attention_head_size * self.attention.num_attention_heads
420
+ self.pruned_heads = self.pruned_heads.union(heads)
421
+
422
+ def forward(self, hidden_states, attention_mask=None, head_mask=None, output_attentions=False):
423
+ self_outputs = self.attention(hidden_states, attention_mask, head_mask, output_attentions)
424
+
425
+ attention_output = self.output(self_outputs[0], hidden_states)
426
+
427
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
428
+ return outputs
429
+
430
+
431
+ # Copied from transformers.models.vit.modeling_vit.ViTIntermediate with ViT->Vilt
432
+ class ViltIntermediate(nn.Module):
433
+ def __init__(self, config: ViltConfig) -> None:
434
+ super().__init__()
435
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
436
+ if isinstance(config.hidden_act, str):
437
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
438
+ else:
439
+ self.intermediate_act_fn = config.hidden_act
440
+
441
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
442
+ hidden_states = self.dense(hidden_states)
443
+ hidden_states = self.intermediate_act_fn(hidden_states)
444
+
445
+ return hidden_states
446
+
447
+
448
+ # Copied from transformers.models.vit.modeling_vit.ViTOutput with ViT->Vilt
449
+ class ViltOutput(nn.Module):
450
+ def __init__(self, config: ViltConfig) -> None:
451
+ super().__init__()
452
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
453
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
454
+
455
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
456
+ hidden_states = self.dense(hidden_states)
457
+ hidden_states = self.dropout(hidden_states)
458
+
459
+ hidden_states = hidden_states + input_tensor
460
+
461
+ return hidden_states
462
+
463
+
464
+ class ViltLayer(GradientCheckpointingLayer):
465
+ """This corresponds to the Block class in the timm implementation."""
466
+
467
+ def __init__(self, config):
468
+ super().__init__()
469
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
470
+ self.seq_len_dim = 1
471
+ self.attention = ViltAttention(config)
472
+ self.intermediate = ViltIntermediate(config)
473
+ self.output = ViltOutput(config)
474
+ self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
475
+ self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
476
+
477
+ def forward(self, hidden_states, attention_mask=None, head_mask=None, output_attentions=False):
478
+ self_attention_outputs = self.attention(
479
+ self.layernorm_before(hidden_states), # in ViLT, layernorm is applied before self-attention
480
+ attention_mask,
481
+ head_mask,
482
+ output_attentions=output_attentions,
483
+ )
484
+ attention_output = self_attention_outputs[0]
485
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
486
+
487
+ # first residual connection
488
+ hidden_states = attention_output + hidden_states.to(attention_output.device)
489
+
490
+ # in ViLT, layernorm is also applied after self-attention
491
+ layer_output = self.layernorm_after(hidden_states)
492
+ layer_output = self.intermediate(layer_output)
493
+
494
+ # second residual connection is done here
495
+ layer_output = self.output(layer_output, hidden_states)
496
+
497
+ outputs = (layer_output,) + outputs
498
+
499
+ return outputs
500
+
501
+
502
+ class ViltEncoder(nn.Module):
503
+ def __init__(self, config):
504
+ super().__init__()
505
+ self.config = config
506
+ self.layer = nn.ModuleList([ViltLayer(config) for _ in range(config.num_hidden_layers)])
507
+ self.gradient_checkpointing = False
508
+
509
+ def forward(
510
+ self,
511
+ hidden_states,
512
+ attention_mask=None,
513
+ head_mask=None,
514
+ output_attentions=False,
515
+ output_hidden_states=False,
516
+ return_dict=True,
517
+ ):
518
+ all_hidden_states = () if output_hidden_states else None
519
+ all_self_attentions = () if output_attentions else None
520
+
521
+ for i, layer_module in enumerate(self.layer):
522
+ if output_hidden_states:
523
+ all_hidden_states = all_hidden_states + (hidden_states,)
524
+
525
+ layer_head_mask = head_mask[i] if head_mask is not None else None
526
+
527
+ layer_outputs = layer_module(hidden_states, attention_mask, layer_head_mask, output_attentions)
528
+
529
+ hidden_states = layer_outputs[0]
530
+
531
+ if output_attentions:
532
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
533
+
534
+ if output_hidden_states:
535
+ all_hidden_states = all_hidden_states + (hidden_states,)
536
+
537
+ if not return_dict:
538
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
539
+ return BaseModelOutput(
540
+ last_hidden_state=hidden_states,
541
+ hidden_states=all_hidden_states,
542
+ attentions=all_self_attentions,
543
+ )
544
+
545
+
546
+ @auto_docstring
547
+ class ViltPreTrainedModel(PreTrainedModel):
548
+ config: ViltConfig
549
+ base_model_prefix = "vilt"
550
+ supports_gradient_checkpointing = True
551
+ _no_split_modules = ["ViltEmbeddings", "ViltSelfAttention"]
552
+
553
+ def _init_weights(self, module):
554
+ """Initialize the weights"""
555
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
556
+ # Slightly different from the TF version which uses truncated_normal for initialization
557
+ # cf https://github.com/pytorch/pytorch/pull/5617
558
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
559
+ if module.bias is not None:
560
+ module.bias.data.zero_()
561
+ elif isinstance(module, nn.Embedding):
562
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
563
+ if module.padding_idx is not None:
564
+ module.weight.data[module.padding_idx].zero_()
565
+ elif isinstance(module, nn.LayerNorm):
566
+ module.bias.data.zero_()
567
+ module.weight.data.fill_(1.0)
568
+
569
+
570
+ @auto_docstring
571
+ class ViltModel(ViltPreTrainedModel):
572
+ def __init__(self, config, add_pooling_layer=True):
573
+ r"""
574
+ add_pooling_layer (bool, *optional*, defaults to `True`):
575
+ Whether to add a pooling layer
576
+ """
577
+ super().__init__(config)
578
+ self.config = config
579
+
580
+ self.embeddings = ViltEmbeddings(config)
581
+ self.encoder = ViltEncoder(config)
582
+
583
+ self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
584
+ self.pooler = ViltPooler(config) if add_pooling_layer else None
585
+
586
+ # Initialize weights and apply final processing
587
+ self.post_init()
588
+
589
+ def get_input_embeddings(self):
590
+ return self.embeddings.text_embeddings.word_embeddings
591
+
592
+ def set_input_embeddings(self, value):
593
+ self.embeddings.text_embeddings.word_embeddings = value
594
+
595
+ def _prune_heads(self, heads_to_prune):
596
+ """
597
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
598
+ class PreTrainedModel
599
+ """
600
+ for layer, heads in heads_to_prune.items():
601
+ self.encoder.layer[layer].attention.prune_heads(heads)
602
+
603
+ @auto_docstring
604
+ def forward(
605
+ self,
606
+ input_ids: Optional[torch.LongTensor] = None,
607
+ attention_mask: Optional[torch.FloatTensor] = None,
608
+ token_type_ids: Optional[torch.LongTensor] = None,
609
+ pixel_values: Optional[torch.FloatTensor] = None,
610
+ pixel_mask: Optional[torch.LongTensor] = None,
611
+ head_mask: Optional[torch.FloatTensor] = None,
612
+ inputs_embeds: Optional[torch.FloatTensor] = None,
613
+ image_embeds: Optional[torch.FloatTensor] = None,
614
+ image_token_type_idx: Optional[int] = None,
615
+ output_attentions: Optional[bool] = None,
616
+ output_hidden_states: Optional[bool] = None,
617
+ return_dict: Optional[bool] = None,
618
+ ) -> Union[BaseModelOutputWithPooling, tuple[torch.FloatTensor]]:
619
+ r"""
620
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, num_patches, hidden_size)`, *optional*):
621
+ Optionally, instead of passing `pixel_values`, you can choose to directly pass an embedded representation.
622
+ This is useful if you want more control over how to convert `pixel_values` into patch embeddings.
623
+ image_token_type_idx (`int`, *optional*):
624
+ - The token type ids for images.
625
+
626
+ Examples:
627
+
628
+ ```python
629
+ >>> from transformers import ViltProcessor, ViltModel
630
+ >>> from PIL import Image
631
+ >>> import requests
632
+
633
+ >>> # prepare image and text
634
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
635
+ >>> image = Image.open(requests.get(url, stream=True).raw)
636
+ >>> text = "hello world"
637
+
638
+ >>> processor = ViltProcessor.from_pretrained("dandelin/vilt-b32-mlm")
639
+ >>> model = ViltModel.from_pretrained("dandelin/vilt-b32-mlm")
640
+
641
+ >>> inputs = processor(image, text, return_tensors="pt")
642
+ >>> outputs = model(**inputs)
643
+ >>> last_hidden_states = outputs.last_hidden_state
644
+ ```"""
645
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
646
+ output_hidden_states = (
647
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
648
+ )
649
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
650
+
651
+ if input_ids is not None and inputs_embeds is not None:
652
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
653
+ elif input_ids is not None:
654
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
655
+ input_shape = input_ids.size()
656
+ elif inputs_embeds is not None:
657
+ input_shape = inputs_embeds.size()[:-1]
658
+ else:
659
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
660
+
661
+ text_batch_size, seq_length = input_shape
662
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
663
+
664
+ if attention_mask is None:
665
+ attention_mask = torch.ones(((text_batch_size, seq_length)), device=device)
666
+
667
+ if pixel_values is not None and image_embeds is not None:
668
+ raise ValueError("You cannot specify both pixel_values and image_embeds at the same time")
669
+ elif pixel_values is None and image_embeds is None:
670
+ raise ValueError("You have to specify either pixel_values or image_embeds")
671
+
672
+ image_batch_size = pixel_values.shape[0] if pixel_values is not None else image_embeds.shape[0]
673
+ if image_batch_size != text_batch_size:
674
+ raise ValueError("The text inputs and image inputs need to have the same batch size")
675
+ if pixel_mask is None:
676
+ pixel_mask = torch.ones((image_batch_size, self.config.image_size, self.config.image_size), device=device)
677
+
678
+ # Prepare head mask if needed
679
+ # 1.0 in head_mask indicate we keep the head
680
+ # attention_probs has shape bsz x n_heads x N x N
681
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
682
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
683
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
684
+
685
+ embedding_output, attention_mask = self.embeddings(
686
+ input_ids,
687
+ attention_mask,
688
+ token_type_ids,
689
+ pixel_values,
690
+ pixel_mask,
691
+ inputs_embeds,
692
+ image_embeds,
693
+ image_token_type_idx=image_token_type_idx,
694
+ )
695
+
696
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
697
+ # ourselves in which case we just need to make it broadcastable to all heads.
698
+ extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
699
+
700
+ encoder_outputs = self.encoder(
701
+ embedding_output,
702
+ attention_mask=extended_attention_mask,
703
+ head_mask=head_mask,
704
+ output_attentions=output_attentions,
705
+ output_hidden_states=output_hidden_states,
706
+ return_dict=return_dict,
707
+ )
708
+ sequence_output = encoder_outputs[0]
709
+ sequence_output = self.layernorm(sequence_output)
710
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
711
+
712
+ if not return_dict:
713
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
714
+
715
+ return BaseModelOutputWithPooling(
716
+ last_hidden_state=sequence_output,
717
+ pooler_output=pooled_output,
718
+ hidden_states=encoder_outputs.hidden_states,
719
+ attentions=encoder_outputs.attentions,
720
+ )
721
+
722
+
723
+ class ViltPooler(nn.Module):
724
+ def __init__(self, config):
725
+ super().__init__()
726
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
727
+ self.activation = nn.Tanh()
728
+
729
+ def forward(self, hidden_states):
730
+ # We "pool" the model by simply taking the hidden state corresponding
731
+ # to the first token.
732
+ first_token_tensor = hidden_states[:, 0]
733
+ pooled_output = self.dense(first_token_tensor)
734
+ pooled_output = self.activation(pooled_output)
735
+ return pooled_output
736
+
737
+
738
+ @auto_docstring(
739
+ custom_intro="""
740
+ ViLT Model with a language modeling head on top as done during pretraining.
741
+ """
742
+ )
743
+ class ViltForMaskedLM(ViltPreTrainedModel):
744
+ _tied_weights_keys = ["mlm_score.decoder.weight", "mlm_score.decoder.bias"]
745
+
746
+ def __init__(self, config):
747
+ super().__init__(config)
748
+
749
+ self.vilt = ViltModel(config)
750
+ self.mlm_score = ViltMLMHead(config)
751
+
752
+ # Initialize weights and apply final processing
753
+ self.post_init()
754
+
755
+ def get_output_embeddings(self):
756
+ return self.mlm_score.decoder
757
+
758
+ def set_output_embeddings(self, new_embeddings):
759
+ self.mlm_score.decoder = new_embeddings
760
+ self.mlm_score.bias = new_embeddings.bias
761
+
762
+ @auto_docstring
763
+ def forward(
764
+ self,
765
+ input_ids: Optional[torch.LongTensor] = None,
766
+ attention_mask: Optional[torch.FloatTensor] = None,
767
+ token_type_ids: Optional[torch.LongTensor] = None,
768
+ pixel_values: Optional[torch.FloatTensor] = None,
769
+ pixel_mask: Optional[torch.LongTensor] = None,
770
+ head_mask: Optional[torch.FloatTensor] = None,
771
+ inputs_embeds: Optional[torch.FloatTensor] = None,
772
+ image_embeds: Optional[torch.FloatTensor] = None,
773
+ labels: Optional[torch.LongTensor] = None,
774
+ output_attentions: Optional[bool] = None,
775
+ output_hidden_states: Optional[bool] = None,
776
+ return_dict: Optional[bool] = None,
777
+ ) -> Union[MaskedLMOutput, tuple[torch.FloatTensor]]:
778
+ r"""
779
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, num_patches, hidden_size)`, *optional*):
780
+ Optionally, instead of passing `pixel_values`, you can choose to directly pass an embedded representation.
781
+ This is useful if you want more control over how to convert `pixel_values` into patch embeddings.
782
+ labels (*torch.LongTensor* of shape *(batch_size, sequence_length)*, *optional*):
783
+ Labels for computing the masked language modeling loss. Indices should be in *[-100, 0, ...,
784
+ config.vocab_size]* (see *input_ids* docstring) Tokens with indices set to *-100* are ignored (masked), the
785
+ loss is only computed for the tokens with labels in *[0, ..., config.vocab_size]*
786
+
787
+ Examples:
788
+
789
+ ```python
790
+ >>> from transformers import ViltProcessor, ViltForMaskedLM
791
+ >>> import requests
792
+ >>> from PIL import Image
793
+ >>> import re
794
+ >>> import torch
795
+
796
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
797
+ >>> image = Image.open(requests.get(url, stream=True).raw)
798
+ >>> text = "a bunch of [MASK] laying on a [MASK]."
799
+
800
+ >>> processor = ViltProcessor.from_pretrained("dandelin/vilt-b32-mlm")
801
+ >>> model = ViltForMaskedLM.from_pretrained("dandelin/vilt-b32-mlm")
802
+
803
+ >>> # prepare inputs
804
+ >>> encoding = processor(image, text, return_tensors="pt")
805
+
806
+ >>> # forward pass
807
+ >>> outputs = model(**encoding)
808
+
809
+ >>> tl = len(re.findall("\[MASK\]", text))
810
+ >>> inferred_token = [text]
811
+
812
+ >>> # gradually fill in the MASK tokens, one by one
813
+ >>> with torch.no_grad():
814
+ ... for i in range(tl):
815
+ ... encoded = processor.tokenizer(inferred_token)
816
+ ... input_ids = torch.tensor(encoded.input_ids)
817
+ ... encoded = encoded["input_ids"][0][1:-1]
818
+ ... outputs = model(input_ids=input_ids, pixel_values=encoding.pixel_values)
819
+ ... mlm_logits = outputs.logits[0] # shape (seq_len, vocab_size)
820
+ ... # only take into account text features (minus CLS and SEP token)
821
+ ... mlm_logits = mlm_logits[1 : input_ids.shape[1] - 1, :]
822
+ ... mlm_values, mlm_ids = mlm_logits.softmax(dim=-1).max(dim=-1)
823
+ ... # only take into account text
824
+ ... mlm_values[torch.tensor(encoded) != 103] = 0
825
+ ... select = mlm_values.argmax().item()
826
+ ... encoded[select] = mlm_ids[select].item()
827
+ ... inferred_token = [processor.decode(encoded)]
828
+
829
+ >>> selected_token = ""
830
+ >>> encoded = processor.tokenizer(inferred_token)
831
+ >>> output = processor.decode(encoded.input_ids[0], skip_special_tokens=True)
832
+ >>> print(output)
833
+ a bunch of cats laying on a couch.
834
+ ```"""
835
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
836
+
837
+ outputs = self.vilt(
838
+ input_ids,
839
+ attention_mask=attention_mask,
840
+ token_type_ids=token_type_ids,
841
+ pixel_values=pixel_values,
842
+ pixel_mask=pixel_mask,
843
+ head_mask=head_mask,
844
+ inputs_embeds=inputs_embeds,
845
+ image_embeds=image_embeds,
846
+ output_attentions=output_attentions,
847
+ output_hidden_states=output_hidden_states,
848
+ return_dict=return_dict,
849
+ )
850
+
851
+ sequence_output, pooled_output = outputs[:2]
852
+ # split up final hidden states into text and image features
853
+ text_seq_len = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
854
+ text_features, _ = (sequence_output[:, :text_seq_len], sequence_output[:, text_seq_len:])
855
+
856
+ mlm_logits = self.mlm_score(text_features)
857
+
858
+ masked_lm_loss = None
859
+ if labels is not None:
860
+ loss_fct = CrossEntropyLoss() # -100 index = padding token
861
+ # move labels to correct device to enable PP
862
+ labels = labels.to(mlm_logits.device)
863
+ masked_lm_loss = loss_fct(mlm_logits.view(-1, self.config.vocab_size), labels.view(-1))
864
+
865
+ if not return_dict:
866
+ output = (mlm_logits,) + outputs[2:]
867
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
868
+
869
+ return MaskedLMOutput(
870
+ loss=masked_lm_loss,
871
+ logits=mlm_logits,
872
+ hidden_states=outputs.hidden_states,
873
+ attentions=outputs.attentions,
874
+ )
875
+
876
+
877
+ class ViltPredictionHeadTransform(nn.Module):
878
+ def __init__(self, config):
879
+ super().__init__()
880
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
881
+ if isinstance(config.hidden_act, str):
882
+ self.transform_act_fn = ACT2FN[config.hidden_act]
883
+ else:
884
+ self.transform_act_fn = config.hidden_act
885
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
886
+
887
+ def forward(self, hidden_states):
888
+ hidden_states = self.dense(hidden_states)
889
+ hidden_states = self.transform_act_fn(hidden_states)
890
+ hidden_states = self.LayerNorm(hidden_states)
891
+ return hidden_states
892
+
893
+
894
+ class ViltMLMHead(nn.Module):
895
+ def __init__(self, config, weight=None):
896
+ super().__init__()
897
+ self.config = config
898
+ self.transform = ViltPredictionHeadTransform(config)
899
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
900
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
901
+ if weight is not None:
902
+ self.decoder.weight = weight
903
+
904
+ # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
905
+ self.decoder.bias = self.bias
906
+
907
+ def _tie_weights(self):
908
+ self.decoder.bias = self.bias
909
+
910
+ def forward(self, x):
911
+ x = self.transform(x)
912
+ x = self.decoder(x)
913
+ return x
914
+
915
+
916
+ @auto_docstring(
917
+ custom_intro="""
918
+ Vilt Model transformer with a classifier head on top (a linear layer on top of the final hidden state of the [CLS]
919
+ token) for visual question answering, e.g. for VQAv2.
920
+ """
921
+ )
922
+ class ViltForQuestionAnswering(ViltPreTrainedModel):
923
+ def __init__(self, config):
924
+ super().__init__(config)
925
+
926
+ self.num_labels = config.num_labels
927
+ self.vilt = ViltModel(config)
928
+
929
+ # Classifier head
930
+ self.classifier = nn.Sequential(
931
+ nn.Linear(config.hidden_size, config.hidden_size * 2),
932
+ nn.LayerNorm(config.hidden_size * 2),
933
+ nn.GELU(),
934
+ nn.Linear(config.hidden_size * 2, config.num_labels),
935
+ )
936
+
937
+ # Initialize weights and apply final processing
938
+ self.post_init()
939
+
940
+ @auto_docstring
941
+ def forward(
942
+ self,
943
+ input_ids: Optional[torch.LongTensor] = None,
944
+ attention_mask: Optional[torch.FloatTensor] = None,
945
+ token_type_ids: Optional[torch.LongTensor] = None,
946
+ pixel_values: Optional[torch.FloatTensor] = None,
947
+ pixel_mask: Optional[torch.LongTensor] = None,
948
+ head_mask: Optional[torch.FloatTensor] = None,
949
+ inputs_embeds: Optional[torch.FloatTensor] = None,
950
+ image_embeds: Optional[torch.FloatTensor] = None,
951
+ labels: Optional[torch.LongTensor] = None,
952
+ output_attentions: Optional[bool] = None,
953
+ output_hidden_states: Optional[bool] = None,
954
+ return_dict: Optional[bool] = None,
955
+ ) -> Union[SequenceClassifierOutput, tuple[torch.FloatTensor]]:
956
+ r"""
957
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, num_patches, hidden_size)`, *optional*):
958
+ Optionally, instead of passing `pixel_values`, you can choose to directly pass an embedded representation.
959
+ This is useful if you want more control over how to convert `pixel_values` into patch embeddings.
960
+ labels (`torch.FloatTensor` of shape `(batch_size, num_labels)`, *optional*):
961
+ Labels for computing the visual question answering loss. This tensor must be either a one-hot encoding of
962
+ all answers that are applicable for a given example in the batch, or a soft encoding indicating which
963
+ answers are applicable, where 1.0 is the highest score.
964
+
965
+ Examples:
966
+
967
+ ```python
968
+ >>> from transformers import ViltProcessor, ViltForQuestionAnswering
969
+ >>> import requests
970
+ >>> from PIL import Image
971
+
972
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
973
+ >>> image = Image.open(requests.get(url, stream=True).raw)
974
+ >>> text = "How many cats are there?"
975
+
976
+ >>> processor = ViltProcessor.from_pretrained("dandelin/vilt-b32-finetuned-vqa")
977
+ >>> model = ViltForQuestionAnswering.from_pretrained("dandelin/vilt-b32-finetuned-vqa")
978
+
979
+ >>> # prepare inputs
980
+ >>> encoding = processor(image, text, return_tensors="pt")
981
+
982
+ >>> # forward pass
983
+ >>> outputs = model(**encoding)
984
+ >>> logits = outputs.logits
985
+ >>> idx = logits.argmax(-1).item()
986
+ >>> print("Predicted answer:", model.config.id2label[idx])
987
+ Predicted answer: 2
988
+ ```"""
989
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
990
+
991
+ outputs = self.vilt(
992
+ input_ids,
993
+ attention_mask=attention_mask,
994
+ token_type_ids=token_type_ids,
995
+ pixel_values=pixel_values,
996
+ pixel_mask=pixel_mask,
997
+ head_mask=head_mask,
998
+ inputs_embeds=inputs_embeds,
999
+ image_embeds=image_embeds,
1000
+ output_attentions=output_attentions,
1001
+ output_hidden_states=output_hidden_states,
1002
+ return_dict=return_dict,
1003
+ )
1004
+
1005
+ pooler_output = outputs.pooler_output if return_dict else outputs[1]
1006
+
1007
+ logits = self.classifier(pooler_output)
1008
+
1009
+ loss = None
1010
+ if labels is not None:
1011
+ # move labels to correct device to enable PP
1012
+ labels = labels.to(logits.device)
1013
+ loss = nn.functional.binary_cross_entropy_with_logits(logits, labels) * labels.shape[1]
1014
+ # see https://github.com/jnhwkim/ban-vqa/blob/master/train.py#L19
1015
+
1016
+ if not return_dict:
1017
+ output = (logits,) + outputs[2:]
1018
+ return ((loss,) + output) if loss is not None else output
1019
+
1020
+ return SequenceClassifierOutput(
1021
+ loss=loss,
1022
+ logits=logits,
1023
+ hidden_states=outputs.hidden_states,
1024
+ attentions=outputs.attentions,
1025
+ )
1026
+
1027
+
1028
+ @auto_docstring(
1029
+ custom_intro="""
1030
+ Vilt Model transformer with a classifier head on top (a linear layer on top of the final hidden state of the [CLS]
1031
+ token) for image-to-text or text-to-image retrieval, e.g. MSCOCO and F30K.
1032
+ """
1033
+ )
1034
+ class ViltForImageAndTextRetrieval(ViltPreTrainedModel):
1035
+ def __init__(self, config):
1036
+ super().__init__(config)
1037
+
1038
+ self.vilt = ViltModel(config)
1039
+
1040
+ # Classifier head
1041
+ self.rank_output = nn.Linear(config.hidden_size, 1)
1042
+
1043
+ # Initialize weights and apply final processing
1044
+ self.post_init()
1045
+
1046
+ @auto_docstring
1047
+ def forward(
1048
+ self,
1049
+ input_ids: Optional[torch.LongTensor] = None,
1050
+ attention_mask: Optional[torch.FloatTensor] = None,
1051
+ token_type_ids: Optional[torch.LongTensor] = None,
1052
+ pixel_values: Optional[torch.FloatTensor] = None,
1053
+ pixel_mask: Optional[torch.LongTensor] = None,
1054
+ head_mask: Optional[torch.FloatTensor] = None,
1055
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1056
+ image_embeds: Optional[torch.FloatTensor] = None,
1057
+ labels: Optional[torch.LongTensor] = None,
1058
+ output_attentions: Optional[bool] = None,
1059
+ output_hidden_states: Optional[bool] = None,
1060
+ return_dict: Optional[bool] = None,
1061
+ ) -> Union[SequenceClassifierOutput, tuple[torch.FloatTensor]]:
1062
+ r"""
1063
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, num_patches, hidden_size)`, *optional*):
1064
+ Optionally, instead of passing `pixel_values`, you can choose to directly pass an embedded representation.
1065
+ This is useful if you want more control over how to convert `pixel_values` into patch embeddings.
1066
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1067
+ Labels are currently not supported.
1068
+
1069
+ Examples:
1070
+
1071
+ ```python
1072
+ >>> from transformers import ViltProcessor, ViltForImageAndTextRetrieval
1073
+ >>> import requests
1074
+ >>> from PIL import Image
1075
+
1076
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1077
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1078
+ >>> texts = ["An image of two cats chilling on a couch", "A football player scoring a goal"]
1079
+
1080
+ >>> processor = ViltProcessor.from_pretrained("dandelin/vilt-b32-finetuned-coco")
1081
+ >>> model = ViltForImageAndTextRetrieval.from_pretrained("dandelin/vilt-b32-finetuned-coco")
1082
+
1083
+ >>> # forward pass
1084
+ >>> scores = dict()
1085
+ >>> for text in texts:
1086
+ ... # prepare inputs
1087
+ ... encoding = processor(image, text, return_tensors="pt")
1088
+ ... outputs = model(**encoding)
1089
+ ... scores[text] = outputs.logits[0, :].item()
1090
+ ```"""
1091
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1092
+
1093
+ loss = None
1094
+ if labels is not None:
1095
+ raise NotImplementedError("Training is not yet supported.")
1096
+
1097
+ outputs = self.vilt(
1098
+ input_ids,
1099
+ attention_mask=attention_mask,
1100
+ token_type_ids=token_type_ids,
1101
+ pixel_values=pixel_values,
1102
+ pixel_mask=pixel_mask,
1103
+ head_mask=head_mask,
1104
+ inputs_embeds=inputs_embeds,
1105
+ image_embeds=image_embeds,
1106
+ output_attentions=output_attentions,
1107
+ output_hidden_states=output_hidden_states,
1108
+ return_dict=return_dict,
1109
+ )
1110
+
1111
+ pooler_output = outputs.pooler_output if return_dict else outputs[1]
1112
+
1113
+ logits = self.rank_output(pooler_output)
1114
+
1115
+ if not return_dict:
1116
+ output = (logits,) + outputs[2:]
1117
+ return ((loss,) + output) if loss is not None else output
1118
+
1119
+ return SequenceClassifierOutput(
1120
+ loss=loss,
1121
+ logits=logits,
1122
+ hidden_states=outputs.hidden_states,
1123
+ attentions=outputs.attentions,
1124
+ )
1125
+
1126
+
1127
+ @auto_docstring(
1128
+ custom_intro="""
1129
+ Vilt Model transformer with a classifier head on top for natural language visual reasoning, e.g. NLVR2.
1130
+ """
1131
+ )
1132
+ class ViltForImagesAndTextClassification(ViltPreTrainedModel):
1133
+ def __init__(self, config):
1134
+ super().__init__(config)
1135
+
1136
+ self.num_labels = config.num_labels
1137
+ self.vilt = ViltModel(config)
1138
+
1139
+ # Classifier head
1140
+ num_images = config.num_images
1141
+ self.classifier = nn.Sequential(
1142
+ nn.Linear(config.hidden_size * num_images, config.hidden_size * num_images),
1143
+ nn.LayerNorm(config.hidden_size * num_images),
1144
+ nn.GELU(),
1145
+ nn.Linear(config.hidden_size * num_images, config.num_labels),
1146
+ )
1147
+
1148
+ # Initialize weights and apply final processing
1149
+ self.post_init()
1150
+
1151
+ @auto_docstring
1152
+ def forward(
1153
+ self,
1154
+ input_ids: Optional[torch.LongTensor] = None,
1155
+ attention_mask: Optional[torch.FloatTensor] = None,
1156
+ token_type_ids: Optional[torch.LongTensor] = None,
1157
+ pixel_values: Optional[torch.FloatTensor] = None,
1158
+ pixel_mask: Optional[torch.LongTensor] = None,
1159
+ head_mask: Optional[torch.FloatTensor] = None,
1160
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1161
+ image_embeds: Optional[torch.FloatTensor] = None,
1162
+ labels: Optional[torch.LongTensor] = None,
1163
+ output_attentions: Optional[bool] = None,
1164
+ output_hidden_states: Optional[bool] = None,
1165
+ return_dict: Optional[bool] = None,
1166
+ ) -> Union[ViltForImagesAndTextClassificationOutput, tuple[torch.FloatTensor]]:
1167
+ r"""
1168
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, num_patches, hidden_size)`, *optional*):
1169
+ Optionally, instead of passing `pixel_values`, you can choose to directly pass an embedded representation.
1170
+ This is useful if you want more control over how to convert `pixel_values` into patch embeddings.
1171
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1172
+ Binary classification labels.
1173
+
1174
+ Examples:
1175
+
1176
+ ```python
1177
+ >>> from transformers import ViltProcessor, ViltForImagesAndTextClassification
1178
+ >>> import requests
1179
+ >>> from PIL import Image
1180
+
1181
+ >>> image1 = Image.open(requests.get("https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg", stream=True).raw)
1182
+ >>> image2 = Image.open(requests.get("https://lil.nlp.cornell.edu/nlvr/exs/ex0_1.jpg", stream=True).raw)
1183
+ >>> text = "The left image contains twice the number of dogs as the right image."
1184
+
1185
+ >>> processor = ViltProcessor.from_pretrained("dandelin/vilt-b32-finetuned-nlvr2")
1186
+ >>> model = ViltForImagesAndTextClassification.from_pretrained("dandelin/vilt-b32-finetuned-nlvr2")
1187
+
1188
+ >>> # prepare inputs
1189
+ >>> encoding = processor([image1, image2], text, return_tensors="pt")
1190
+
1191
+ >>> # forward pass
1192
+ >>> outputs = model(input_ids=encoding.input_ids, pixel_values=encoding.pixel_values.unsqueeze(0))
1193
+ >>> logits = outputs.logits
1194
+ >>> idx = logits.argmax(-1).item()
1195
+ >>> print("Predicted answer:", model.config.id2label[idx])
1196
+ Predicted answer: True
1197
+ ```"""
1198
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1199
+ output_hidden_states = (
1200
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1201
+ )
1202
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1203
+
1204
+ if pixel_values is not None and pixel_values.ndim == 4:
1205
+ # add dummy num_images dimension
1206
+ pixel_values = pixel_values.unsqueeze(1)
1207
+
1208
+ if image_embeds is not None and image_embeds.ndim == 3:
1209
+ # add dummy num_images dimension
1210
+ image_embeds = image_embeds.unsqueeze(1)
1211
+
1212
+ num_images = pixel_values.shape[1] if pixel_values is not None else None
1213
+ if num_images is None:
1214
+ num_images = image_embeds.shape[1] if image_embeds is not None else None
1215
+ if num_images != self.config.num_images:
1216
+ raise ValueError(
1217
+ "Make sure to match the number of images in the model with the number of images in the input."
1218
+ )
1219
+ pooler_outputs = []
1220
+ hidden_states = [] if output_hidden_states else None
1221
+ attentions = [] if output_attentions else None
1222
+ for i in range(num_images):
1223
+ # forward every image through the model
1224
+ outputs = self.vilt(
1225
+ input_ids,
1226
+ attention_mask=attention_mask,
1227
+ token_type_ids=token_type_ids,
1228
+ pixel_values=pixel_values[:, i, :, :, :] if pixel_values is not None else None,
1229
+ pixel_mask=pixel_mask[:, i, :, :] if pixel_mask is not None else None,
1230
+ head_mask=head_mask,
1231
+ inputs_embeds=inputs_embeds,
1232
+ image_embeds=image_embeds[:, i, :, :] if image_embeds is not None else None,
1233
+ image_token_type_idx=i + 1,
1234
+ output_attentions=output_attentions,
1235
+ output_hidden_states=output_hidden_states,
1236
+ return_dict=return_dict,
1237
+ )
1238
+ pooler_output = outputs.pooler_output if return_dict else outputs[1]
1239
+ pooler_outputs.append(pooler_output)
1240
+ if output_hidden_states:
1241
+ hidden_states.append(outputs.hidden_states)
1242
+ if output_attentions:
1243
+ attentions.append(outputs.attentions)
1244
+
1245
+ pooled_output = torch.cat(pooler_outputs, dim=-1)
1246
+ logits = self.classifier(pooled_output)
1247
+
1248
+ loss = None
1249
+ if labels is not None:
1250
+ loss_fct = CrossEntropyLoss()
1251
+ # move labels to correct device to enable PP
1252
+ labels = labels.to(logits.device)
1253
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1254
+
1255
+ if not return_dict:
1256
+ output = (logits, hidden_states, attentions)
1257
+ return ((loss,) + output) if loss is not None else output
1258
+
1259
+ return ViltForImagesAndTextClassificationOutput(
1260
+ loss=loss,
1261
+ logits=logits,
1262
+ hidden_states=hidden_states,
1263
+ attentions=attentions,
1264
+ )
1265
+
1266
+
1267
+ @auto_docstring
1268
+ class ViltForTokenClassification(ViltPreTrainedModel):
1269
+ def __init__(self, config):
1270
+ super().__init__(config)
1271
+
1272
+ self.num_labels = config.num_labels
1273
+ self.vilt = ViltModel(config, add_pooling_layer=False)
1274
+
1275
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
1276
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1277
+
1278
+ # Initialize weights and apply final processing
1279
+ self.post_init()
1280
+
1281
+ @auto_docstring
1282
+ def forward(
1283
+ self,
1284
+ input_ids: Optional[torch.LongTensor] = None,
1285
+ attention_mask: Optional[torch.FloatTensor] = None,
1286
+ token_type_ids: Optional[torch.LongTensor] = None,
1287
+ pixel_values: Optional[torch.FloatTensor] = None,
1288
+ pixel_mask: Optional[torch.LongTensor] = None,
1289
+ head_mask: Optional[torch.FloatTensor] = None,
1290
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1291
+ image_embeds: Optional[torch.FloatTensor] = None,
1292
+ labels: Optional[torch.LongTensor] = None,
1293
+ output_attentions: Optional[bool] = None,
1294
+ output_hidden_states: Optional[bool] = None,
1295
+ return_dict: Optional[bool] = None,
1296
+ ) -> Union[TokenClassifierOutput, tuple[torch.FloatTensor]]:
1297
+ r"""
1298
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, num_patches, hidden_size)`, *optional*):
1299
+ Optionally, instead of passing `pixel_values`, you can choose to directly pass an embedded representation.
1300
+ This is useful if you want more control over how to convert `pixel_values` into patch embeddings.
1301
+ labels (`torch.LongTensor` of shape `(batch_size, text_sequence_length)`, *optional*):
1302
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1303
+ """
1304
+
1305
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1306
+
1307
+ outputs = self.vilt(
1308
+ input_ids,
1309
+ attention_mask=attention_mask,
1310
+ token_type_ids=token_type_ids,
1311
+ pixel_values=pixel_values,
1312
+ pixel_mask=pixel_mask,
1313
+ head_mask=head_mask,
1314
+ inputs_embeds=inputs_embeds,
1315
+ image_embeds=image_embeds,
1316
+ output_attentions=output_attentions,
1317
+ output_hidden_states=output_hidden_states,
1318
+ return_dict=return_dict,
1319
+ )
1320
+
1321
+ sequence_output = outputs[0]
1322
+
1323
+ text_input_size = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
1324
+
1325
+ sequence_output = self.dropout(sequence_output)
1326
+ logits = self.classifier(sequence_output[:, :text_input_size])
1327
+
1328
+ loss = None
1329
+ if labels is not None:
1330
+ loss_fct = CrossEntropyLoss()
1331
+ # move labels to correct device to enable PP
1332
+ labels = labels.to(logits.device)
1333
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1334
+
1335
+ if not return_dict:
1336
+ output = (logits,) + outputs[2:]
1337
+ return ((loss,) + output) if loss is not None else output
1338
+
1339
+ return TokenClassifierOutput(
1340
+ loss=loss,
1341
+ logits=logits,
1342
+ hidden_states=outputs.hidden_states,
1343
+ attentions=outputs.attentions,
1344
+ )
1345
+
1346
+
1347
+ __all__ = [
1348
+ "ViltForImageAndTextRetrieval",
1349
+ "ViltForImagesAndTextClassification",
1350
+ "ViltForTokenClassification",
1351
+ "ViltForMaskedLM",
1352
+ "ViltForQuestionAnswering",
1353
+ "ViltLayer",
1354
+ "ViltModel",
1355
+ "ViltPreTrainedModel",
1356
+ ]
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/vilt/processing_vilt.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team.
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
+ Processor class for ViLT.
17
+ """
18
+
19
+ import warnings
20
+ from typing import Optional, Union
21
+
22
+ from ...processing_utils import ProcessorMixin
23
+ from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
24
+ from ...utils import TensorType
25
+
26
+
27
+ class ViltProcessor(ProcessorMixin):
28
+ r"""
29
+ Constructs a ViLT processor which wraps a BERT tokenizer and ViLT image processor into a single processor.
30
+
31
+ [`ViltProcessor`] offers all the functionalities of [`ViltImageProcessor`] and [`BertTokenizerFast`]. See the
32
+ docstring of [`~ViltProcessor.__call__`] and [`~ViltProcessor.decode`] for more information.
33
+
34
+ Args:
35
+ image_processor (`ViltImageProcessor`, *optional*):
36
+ An instance of [`ViltImageProcessor`]. The image processor is a required input.
37
+ tokenizer (`BertTokenizerFast`, *optional*):
38
+ An instance of ['BertTokenizerFast`]. The tokenizer is a required input.
39
+ """
40
+
41
+ attributes = ["image_processor", "tokenizer"]
42
+ image_processor_class = "ViltImageProcessor"
43
+ tokenizer_class = ("BertTokenizer", "BertTokenizerFast")
44
+
45
+ def __init__(self, image_processor=None, tokenizer=None, **kwargs):
46
+ feature_extractor = None
47
+ if "feature_extractor" in kwargs:
48
+ warnings.warn(
49
+ "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
50
+ " instead.",
51
+ FutureWarning,
52
+ )
53
+ feature_extractor = kwargs.pop("feature_extractor")
54
+
55
+ image_processor = image_processor if image_processor is not None else feature_extractor
56
+ if image_processor is None:
57
+ raise ValueError("You need to specify an `image_processor`.")
58
+ if tokenizer is None:
59
+ raise ValueError("You need to specify a `tokenizer`.")
60
+
61
+ super().__init__(image_processor, tokenizer)
62
+ self.current_processor = self.image_processor
63
+
64
+ def __call__(
65
+ self,
66
+ images,
67
+ text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None,
68
+ add_special_tokens: bool = True,
69
+ padding: Union[bool, str, PaddingStrategy] = False,
70
+ truncation: Union[bool, str, TruncationStrategy] = None,
71
+ max_length: Optional[int] = None,
72
+ stride: int = 0,
73
+ pad_to_multiple_of: Optional[int] = None,
74
+ return_token_type_ids: Optional[bool] = None,
75
+ return_attention_mask: Optional[bool] = None,
76
+ return_overflowing_tokens: bool = False,
77
+ return_special_tokens_mask: bool = False,
78
+ return_offsets_mapping: bool = False,
79
+ return_length: bool = False,
80
+ verbose: bool = True,
81
+ return_tensors: Optional[Union[str, TensorType]] = None,
82
+ **kwargs,
83
+ ) -> BatchEncoding:
84
+ """
85
+ This method uses [`ViltImageProcessor.__call__`] method to prepare image(s) for the model, and
86
+ [`BertTokenizerFast.__call__`] to prepare text for the model.
87
+
88
+ Please refer to the docstring of the above two methods for more information.
89
+ """
90
+ encoding = self.tokenizer(
91
+ text=text,
92
+ add_special_tokens=add_special_tokens,
93
+ padding=padding,
94
+ truncation=truncation,
95
+ max_length=max_length,
96
+ stride=stride,
97
+ pad_to_multiple_of=pad_to_multiple_of,
98
+ return_token_type_ids=return_token_type_ids,
99
+ return_attention_mask=return_attention_mask,
100
+ return_overflowing_tokens=return_overflowing_tokens,
101
+ return_special_tokens_mask=return_special_tokens_mask,
102
+ return_offsets_mapping=return_offsets_mapping,
103
+ return_length=return_length,
104
+ verbose=verbose,
105
+ return_tensors=return_tensors,
106
+ **kwargs,
107
+ )
108
+ # add pixel_values + pixel_mask
109
+ encoding_image_processor = self.image_processor(images, return_tensors=return_tensors)
110
+ encoding.update(encoding_image_processor)
111
+
112
+ return encoding
113
+
114
+ def batch_decode(self, *args, **kwargs):
115
+ """
116
+ This method forwards all its arguments to BertTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
117
+ refer to the docstring of this method for more information.
118
+ """
119
+ return self.tokenizer.batch_decode(*args, **kwargs)
120
+
121
+ def decode(self, *args, **kwargs):
122
+ """
123
+ This method forwards all its arguments to BertTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
124
+ the docstring of this method for more information.
125
+ """
126
+ return self.tokenizer.decode(*args, **kwargs)
127
+
128
+ @property
129
+ def model_input_names(self):
130
+ tokenizer_input_names = self.tokenizer.model_input_names
131
+ image_processor_input_names = self.image_processor.model_input_names
132
+ return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
133
+
134
+ @property
135
+ def feature_extractor_class(self):
136
+ warnings.warn(
137
+ "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.",
138
+ FutureWarning,
139
+ )
140
+ return self.image_processor_class
141
+
142
+ @property
143
+ def feature_extractor(self):
144
+ warnings.warn(
145
+ "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.",
146
+ FutureWarning,
147
+ )
148
+ return self.image_processor
149
+
150
+
151
+ __all__ = ["ViltProcessor"]
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/vipllava/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. 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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_vipllava import *
22
+ from .modeling_vipllava import *
23
+ else:
24
+ import sys
25
+
26
+ _file = globals()["__file__"]
27
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/vipllava/configuration_vipllava.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Microsoft Research & University of Wisconsin-Madison and the HuggingFace Inc. team. All rights reserved.
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
+ """VipLlava model configuration"""
15
+
16
+ from ...configuration_utils import PretrainedConfig
17
+ from ...utils import logging
18
+ from ..auto import CONFIG_MAPPING, AutoConfig
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ class VipLlavaConfig(PretrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`VipLlavaForConditionalGeneration`]. It is used to instantiate an
27
+ VipLlava model according to the specified arguments, defining the model architecture. Instantiating a configuration
28
+ with the defaults will yield a similar configuration to that of the VipLlava-9B.
29
+
30
+ e.g. [ybelkada/vip-llava-7b-hf](https://huggingface.co/ybelkada/vip-llava-7b-hf)
31
+
32
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
33
+ documentation from [`PretrainedConfig`] for more information.
34
+
35
+ Args:
36
+ vision_config (`VipLlavaVisionConfig`, *optional*):
37
+ Custom vision config or dict
38
+ text_config (`Union[AutoConfig, dict]`, *optional*):
39
+ The config object of the text backbone. Can be any of `LlamaConfig` or `MistralConfig`.
40
+ image_token_index (`int`, *optional*, defaults to 32000):
41
+ The image token index to encode the image prompt.
42
+ projector_hidden_act (`str`, *optional*, defaults to `"gelu"`):
43
+ The activation function used by the multimodal projector.
44
+ projector_layernorm_eps (`float`, *optional*, defaults to 1e-05):
45
+ The layer norm epsilon of the projector layernorm
46
+ vision_feature_layers (`Union[int, list[int]]`, *optional*, defaults to `[-2, -5, -8, -11, 6]`):
47
+ The vision feature layer, or list of layers to select the vision features from.
48
+ image_seq_length (`int`, *optional*, defaults to 576):
49
+ Sequence length of one image embedding.
50
+
51
+ Example:
52
+
53
+ ```python
54
+ >>> from transformers import VipLlavaForConditionalGeneration, VipLlavaConfig, CLIPVisionConfig, LlamaConfig
55
+
56
+ >>> # Initializing a CLIP-vision config
57
+ >>> vision_config = CLIPVisionConfig()
58
+
59
+ >>> # Initializing a Llama config
60
+ >>> text_config = LlamaConfig()
61
+
62
+ >>> # Initializing a VipLlava vipllava-7b style configuration
63
+ >>> configuration = VipLlavaConfig(vision_config, text_config)
64
+
65
+ >>> # Initializing a model from the vipllava-7b style configuration
66
+ >>> model = VipLlavaForConditionalGeneration(configuration)
67
+
68
+ >>> # Accessing the model configuration
69
+ >>> configuration = model.config
70
+ ```"""
71
+
72
+ model_type = "vipllava"
73
+ attribute_map = {
74
+ "image_token_id": "image_token_index",
75
+ }
76
+ sub_configs = {"text_config": AutoConfig, "vision_config": AutoConfig}
77
+
78
+ def __init__(
79
+ self,
80
+ vision_config=None,
81
+ text_config=None,
82
+ image_token_index=32000,
83
+ projector_hidden_act="gelu",
84
+ projector_layernorm_eps=1e-5,
85
+ vision_feature_layers=[-2, -5, -8, -11, 6],
86
+ image_seq_length=576,
87
+ **kwargs,
88
+ ):
89
+ self.image_token_index = image_token_index
90
+ self.projector_hidden_act = projector_hidden_act
91
+ self.projector_layernorm_eps = projector_layernorm_eps
92
+ self.vision_feature_layers = vision_feature_layers
93
+ self.image_seq_length = image_seq_length
94
+ self.vision_config = vision_config
95
+
96
+ if isinstance(self.vision_config, dict):
97
+ vision_config["model_type"] = vision_config.get("model_type", "clip_vision_model")
98
+ self.vision_config = CONFIG_MAPPING[vision_config["model_type"]](**vision_config)
99
+ elif vision_config is None:
100
+ self.vision_config = CONFIG_MAPPING["clip_vision_model"](
101
+ intermediate_size=4096,
102
+ hidden_size=1024,
103
+ patch_size=14,
104
+ image_size=336,
105
+ num_hidden_layers=24,
106
+ num_attention_heads=16,
107
+ vocab_size=32000,
108
+ projection_dim=768,
109
+ )
110
+
111
+ if isinstance(text_config, dict):
112
+ text_config["model_type"] = text_config.get("model_type", "llama")
113
+ text_config = CONFIG_MAPPING[text_config["model_type"]](**text_config)
114
+ elif text_config is None:
115
+ text_config = CONFIG_MAPPING["llama"]()
116
+
117
+ self.text_config = text_config
118
+
119
+ super().__init__(**kwargs)
120
+
121
+
122
+ __all__ = ["VipLlavaConfig"]
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/vipllava/convert_vipllava_weights_to_hf.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Inc. team. 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
+ import argparse
15
+
16
+ import torch
17
+ from huggingface_hub import hf_hub_download
18
+
19
+ from transformers import (
20
+ AddedToken,
21
+ AutoConfig,
22
+ AutoTokenizer,
23
+ CLIPImageProcessor,
24
+ LlavaProcessor,
25
+ VipLlavaConfig,
26
+ VipLlavaForConditionalGeneration,
27
+ )
28
+
29
+
30
+ KEYS_TO_MODIFY_MAPPING = {
31
+ "model.vision_tower.": "",
32
+ "model.mm_projector": "multi_modal_projector",
33
+ "model": "model.model",
34
+ "vision_model.model": "vision_model",
35
+ "lm_head": "language_model.lm_head",
36
+ "model.model": "language_model.model",
37
+ "multi_modal_projector.0": "multi_modal_projector.linear_1",
38
+ "multi_modal_projector.2": "multi_modal_projector.linear_2",
39
+ "final_linear.0": "linear_1",
40
+ "final_linear.2": "linear_2",
41
+ "multi_modal_projector.clip_layernorm": "multi_modal_projector.projector_layernorm",
42
+ }
43
+
44
+
45
+ # Copied from transformers.models.llava.convert_llava_weights_to_hf.convert_state_dict_to_hf
46
+ def convert_state_dict_to_hf(state_dict):
47
+ new_state_dict = {}
48
+ for key, value in state_dict.items():
49
+ if key.endswith(".inv_freq"):
50
+ continue
51
+ for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items():
52
+ if key_to_modify in key:
53
+ key = key.replace(key_to_modify, new_key)
54
+ new_state_dict[key] = value
55
+ return new_state_dict
56
+
57
+
58
+ def convert_vipllava_llama_to_hf(text_model_id, vision_model_id, output_hub_path, old_state_dict_id):
59
+ torch.set_default_dtype(torch.float16)
60
+ text_config = AutoConfig.from_pretrained(text_model_id)
61
+
62
+ tokenizer = AutoTokenizer.from_pretrained(text_model_id)
63
+ tokenizer.add_tokens(AddedToken("<image>", special=True, normalized=False), special_tokens=True)
64
+ tokenizer.add_special_tokens({"pad_token": "<pad>"})
65
+
66
+ image_processor = CLIPImageProcessor.from_pretrained(vision_model_id)
67
+
68
+ processor = LlavaProcessor(tokenizer=tokenizer, image_processor=image_processor)
69
+
70
+ config = VipLlavaConfig(text_config=text_config)
71
+ config.pad_token_id = 32001
72
+
73
+ with torch.device("meta"):
74
+ model = VipLlavaForConditionalGeneration(config)
75
+
76
+ # Pad to 64 for performance reasons
77
+ pad_shape = 64
78
+
79
+ state_dict_path = hf_hub_download(old_state_dict_id, "model_state_dict_7b.bin")
80
+
81
+ state_dict = torch.load(state_dict_path, map_location="cpu", weights_only=True)
82
+ state_dict = convert_state_dict_to_hf(state_dict)
83
+
84
+ model.load_state_dict(state_dict, strict=True, assign=True)
85
+
86
+ pre_expansion_embeddings = model.language_model.model.embed_tokens.weight.data
87
+ mu = torch.mean(pre_expansion_embeddings, dim=0).float()
88
+ n = pre_expansion_embeddings.size()[0]
89
+ sigma = ((pre_expansion_embeddings - mu).T @ (pre_expansion_embeddings - mu)) / n
90
+ dist = torch.distributions.multivariate_normal.MultivariateNormal(mu, covariance_matrix=1e-5 * sigma)
91
+
92
+ # We add an image token so we resize the model
93
+ model.resize_token_embeddings(config.text_config.vocab_size + 2, pad_shape)
94
+ model.language_model.model.embed_tokens.weight.data[32000:] = torch.stack(
95
+ tuple(dist.sample() for _ in range(model.language_model.model.embed_tokens.weight.data[32000:].shape[0])),
96
+ dim=0,
97
+ )
98
+ model.language_model.lm_head.weight.data[32000:] = torch.stack(
99
+ tuple(dist.sample() for _ in range(model.language_model.lm_head.weight.data[32000:].shape[0])),
100
+ dim=0,
101
+ )
102
+
103
+ model.push_to_hub(output_hub_path)
104
+ processor.push_to_hub(output_hub_path)
105
+
106
+
107
+ def main():
108
+ parser = argparse.ArgumentParser()
109
+ parser.add_argument(
110
+ "--text_model_id",
111
+ help="Hub location of the text model",
112
+ )
113
+ parser.add_argument(
114
+ "--vision_model_id",
115
+ help="Hub location of the vision model",
116
+ )
117
+ parser.add_argument(
118
+ "--output_hub_path",
119
+ help="Location on the hub of the converted model",
120
+ )
121
+ parser.add_argument(
122
+ "--old_state_dict_id",
123
+ help="Location on the hub of the raw state dict of the original model. The filename needs to be `model_state_dict.bin`",
124
+ )
125
+ args = parser.parse_args()
126
+ convert_vipllava_llama_to_hf(
127
+ args.text_model_id, args.vision_model_id, args.output_hub_path, args.old_state_dict_id
128
+ )
129
+
130
+
131
+ if __name__ == "__main__":
132
+ main()
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/vipllava/modeling_vipllava.py ADDED
@@ -0,0 +1,464 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/vipllava/modular_vipllava.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_vipllava.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2023 the HuggingFace Inc. team. All rights reserved.
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License");
11
+ # you may not use this file except in compliance with the License.
12
+ # You may obtain a copy of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS,
18
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ # See the License for the specific language governing permissions and
20
+ # limitations under the License.
21
+
22
+ from dataclasses import dataclass
23
+ from typing import Optional, Union
24
+
25
+ import torch
26
+ from torch import nn
27
+
28
+ from ...activations import ACT2FN
29
+ from ...cache_utils import Cache
30
+ from ...generation import GenerationMixin
31
+ from ...modeling_outputs import BaseModelOutputWithPast, ModelOutput
32
+ from ...modeling_utils import PreTrainedModel
33
+ from ...utils import auto_docstring, can_return_tuple
34
+ from ..auto import AutoModel
35
+ from .configuration_vipllava import VipLlavaConfig
36
+
37
+
38
+ @dataclass
39
+ @auto_docstring(
40
+ custom_intro="""
41
+ Base class for VipLlava outputs, with hidden states and attentions.
42
+ """
43
+ )
44
+ class VipLlavaModelOutputWithPast(BaseModelOutputWithPast):
45
+ r"""
46
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
47
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
48
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`)
49
+
50
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
51
+ `past_key_values` input) to speed up sequential decoding.
52
+ image_hidden_states (`torch.FloatTensor`, *optional*):
53
+ A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
54
+ image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
55
+ """
56
+
57
+ image_hidden_states: Optional[torch.FloatTensor] = None
58
+
59
+
60
+ @dataclass
61
+ @auto_docstring(
62
+ custom_intro="""
63
+ Base class for VipLlava causal language model (or autoregressive) outputs.
64
+ """
65
+ )
66
+ class VipLlavaCausalLMOutputWithPast(ModelOutput):
67
+ r"""
68
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
69
+ Language modeling loss (for next-token prediction).
70
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
71
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
72
+ past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
73
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
74
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`)
75
+
76
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
77
+ `past_key_values` input) to speed up sequential decoding.
78
+ image_hidden_states (`torch.FloatTensor`, *optional*):
79
+ A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
80
+ image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
81
+ """
82
+
83
+ loss: Optional[torch.FloatTensor] = None
84
+ logits: Optional[torch.FloatTensor] = None
85
+ past_key_values: Optional[list[torch.FloatTensor]] = None
86
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
87
+ attentions: Optional[tuple[torch.FloatTensor]] = None
88
+ image_hidden_states: Optional[torch.FloatTensor] = None
89
+
90
+
91
+ class VipLlavaMultiModalProjector(nn.Module):
92
+ def __init__(self, config: VipLlavaConfig):
93
+ super().__init__()
94
+ num_feature_layers = 1 if isinstance(config.vision_feature_layers, int) else len(config.vision_feature_layers)
95
+ self.projector_layernorm = nn.LayerNorm(
96
+ num_feature_layers * config.vision_config.hidden_size, eps=config.projector_layernorm_eps
97
+ )
98
+
99
+ self.linear_1 = nn.Linear(
100
+ num_feature_layers * config.vision_config.hidden_size,
101
+ config.text_config.hidden_size,
102
+ bias=True,
103
+ )
104
+ self.act = ACT2FN[config.projector_hidden_act]
105
+ self.linear_2 = nn.Linear(config.text_config.hidden_size, config.text_config.hidden_size, bias=True)
106
+
107
+ def forward(self, hidden_states):
108
+ hidden_states = self.projector_layernorm(hidden_states)
109
+ hidden_states = self.linear_1(hidden_states)
110
+ hidden_states = self.act(hidden_states)
111
+ hidden_states = self.linear_2(hidden_states)
112
+ return hidden_states
113
+
114
+
115
+ @auto_docstring
116
+ class VipLlavaPreTrainedModel(PreTrainedModel):
117
+ config: VipLlavaConfig
118
+ base_model_prefix = ""
119
+ supports_gradient_checkpointing = True
120
+ _skip_keys_device_placement = "past_key_values"
121
+
122
+ _supports_flash_attn = True
123
+ _supports_sdpa = True
124
+
125
+ _can_compile_fullgraph = True
126
+ _supports_flex_attn = True
127
+ _supports_attention_backend = True
128
+
129
+
130
+ @auto_docstring(
131
+ custom_intro="""
132
+ The VipLlava model which consists of a vision backbone and a language model, without a language modeling head.
133
+ """
134
+ )
135
+ class VipLlavaModel(VipLlavaPreTrainedModel):
136
+ _checkpoint_conversion_mapping = {"language_model.model": "language_model"}
137
+
138
+ def __init__(self, config: VipLlavaConfig):
139
+ super().__init__(config)
140
+ self.vision_tower = AutoModel.from_config(config.vision_config)
141
+
142
+ self.multi_modal_projector = VipLlavaMultiModalProjector(config)
143
+ self.language_model = AutoModel.from_config(config.text_config)
144
+ self.post_init()
145
+
146
+ def get_input_embeddings(self):
147
+ return self.language_model.get_input_embeddings()
148
+
149
+ def set_input_embeddings(self, value):
150
+ self.language_model.set_input_embeddings(value)
151
+
152
+ def set_decoder(self, decoder):
153
+ self.language_model = decoder
154
+
155
+ def get_decoder(self):
156
+ return self.language_model
157
+
158
+ def get_image_features(
159
+ self, pixel_values: torch.FloatTensor, vision_feature_layers: Optional[Union[int, list[int]]] = None
160
+ ):
161
+ """
162
+ Obtains image last hidden states from the vision tower and apply multimodal projection.
163
+
164
+ Args:
165
+ pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`)
166
+ The tensors corresponding to the input images.
167
+ vision_feature_layers (`Union[int, list[int]]`):
168
+ The vision feature layer, or the list of indexes of the layers to select
169
+ the vision feature.
170
+ Returns:
171
+ image_features (`torch.Tensor`): Image feature tensor of shape `(num_images, image_length, embed_dim)`).
172
+ """
173
+ vision_feature_layers = (
174
+ vision_feature_layers if vision_feature_layers is not None else self.config.vision_feature_layers
175
+ )
176
+ image_outputs = self.vision_tower(pixel_values, output_hidden_states=True)
177
+
178
+ # If multiple feature layers are provided (which is usually the case)
179
+ # then the image features are concatenated after the CLS is removed.
180
+ if isinstance(vision_feature_layers, int):
181
+ image_features = image_outputs.hidden_states[vision_feature_layers][:, 1:]
182
+ else:
183
+ # Usually, we select the features from index 1: the layers -2, -5, -8, -11 and 6
184
+ image_features = [image_outputs.hidden_states[index][:, 1:] for index in vision_feature_layers]
185
+ image_features = torch.cat(image_features, dim=-1)
186
+ image_features = self.multi_modal_projector(image_features)
187
+ return image_features
188
+
189
+ def get_placeholder_mask(
190
+ self, input_ids: torch.LongTensor, inputs_embeds: torch.FloatTensor, image_features: torch.FloatTensor
191
+ ):
192
+ """
193
+ Obtains multimodal placeholdr mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
194
+ equal to the length of multimodal features. If the lengths are different, an error is raised.
195
+ """
196
+ if input_ids is None:
197
+ special_image_mask = inputs_embeds == self.get_input_embeddings()(
198
+ torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
199
+ )
200
+ special_image_mask = special_image_mask.all(-1)
201
+ else:
202
+ special_image_mask = input_ids == self.config.image_token_id
203
+
204
+ n_image_tokens = special_image_mask.sum()
205
+ special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
206
+ n_image_features = image_features.shape[0] * image_features.shape[1]
207
+ if inputs_embeds[special_image_mask].numel() != image_features.numel():
208
+ raise ValueError(
209
+ f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}"
210
+ )
211
+ return special_image_mask
212
+
213
+ @auto_docstring
214
+ def forward(
215
+ self,
216
+ input_ids: torch.LongTensor = None,
217
+ pixel_values: torch.FloatTensor = None,
218
+ attention_mask: Optional[torch.Tensor] = None,
219
+ position_ids: Optional[torch.LongTensor] = None,
220
+ past_key_values: Optional[Cache] = None,
221
+ inputs_embeds: Optional[torch.FloatTensor] = None,
222
+ vision_feature_layers: Optional[Union[int, list[int]]] = None,
223
+ use_cache: Optional[bool] = None,
224
+ output_attentions: Optional[bool] = None,
225
+ output_hidden_states: Optional[bool] = None,
226
+ return_dict: Optional[bool] = None,
227
+ cache_position: Optional[torch.LongTensor] = None,
228
+ **lm_kwargs,
229
+ ) -> Union[tuple, VipLlavaModelOutputWithPast]:
230
+ r"""
231
+ vision_feature_layers (`Union[int, list[int]]`, *optional*):
232
+ The vision feature layer, or the list of indexes of the layers to select
233
+ the vision feature.
234
+ """
235
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
236
+ output_hidden_states = (
237
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
238
+ )
239
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
240
+ vision_feature_layers = (
241
+ vision_feature_layers if vision_feature_layers is not None else self.config.vision_feature_layers
242
+ )
243
+
244
+ if (input_ids is None) ^ (inputs_embeds is not None):
245
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
246
+
247
+ if inputs_embeds is None:
248
+ inputs_embeds = self.get_input_embeddings()(input_ids)
249
+
250
+ if pixel_values is not None:
251
+ image_features = self.get_image_features(
252
+ pixel_values=pixel_values, vision_feature_layers=vision_feature_layers
253
+ )
254
+ image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
255
+ special_image_mask = self.get_placeholder_mask(
256
+ input_ids, inputs_embeds=inputs_embeds, image_features=image_features
257
+ )
258
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
259
+
260
+ outputs = self.language_model(
261
+ attention_mask=attention_mask,
262
+ position_ids=position_ids,
263
+ past_key_values=past_key_values,
264
+ inputs_embeds=inputs_embeds,
265
+ use_cache=use_cache,
266
+ output_attentions=output_attentions,
267
+ output_hidden_states=output_hidden_states,
268
+ return_dict=True,
269
+ cache_position=cache_position,
270
+ **lm_kwargs,
271
+ )
272
+
273
+ output = VipLlavaModelOutputWithPast(
274
+ last_hidden_state=outputs.last_hidden_state,
275
+ past_key_values=outputs.past_key_values,
276
+ hidden_states=outputs.hidden_states,
277
+ attentions=outputs.attentions,
278
+ image_hidden_states=image_features if pixel_values is not None else None,
279
+ )
280
+ return output if return_dict else output.to_tuple()
281
+
282
+
283
+ @auto_docstring(
284
+ custom_intro="""
285
+ The VIPLLAVA model which consists of a vision backbone and a language model.
286
+ """
287
+ )
288
+ class VipLlavaForConditionalGeneration(VipLlavaPreTrainedModel, GenerationMixin):
289
+ _checkpoint_conversion_mapping = {
290
+ "^language_model.model": "model.language_model",
291
+ "^vision_tower": "model.vision_tower",
292
+ "^multi_modal_projector": "model.multi_modal_projector",
293
+ "^language_model.lm_head": "lm_head",
294
+ }
295
+ _tied_weights_keys = ["lm_head.weight"]
296
+
297
+ def __init__(self, config: VipLlavaConfig):
298
+ super().__init__(config)
299
+ self.model = VipLlavaModel(config)
300
+ self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
301
+ self.post_init()
302
+
303
+ def get_input_embeddings(self):
304
+ return self.model.get_input_embeddings()
305
+
306
+ def set_input_embeddings(self, value):
307
+ self.model.set_input_embeddings(value)
308
+
309
+ def get_output_embeddings(self) -> nn.Module:
310
+ return self.lm_head
311
+
312
+ def set_decoder(self, decoder):
313
+ self.model.set_decoder(decoder)
314
+
315
+ def get_decoder(self):
316
+ return self.model.get_decoder()
317
+
318
+ def get_image_features(
319
+ self, pixel_values: torch.FloatTensor, vision_feature_layers: Optional[Union[int, list[int]]] = None
320
+ ):
321
+ return self.model.get_image_features(pixel_values=pixel_values, vision_feature_layers=vision_feature_layers)
322
+
323
+ # Make modules available through conditional class for BC
324
+ @property
325
+ def language_model(self):
326
+ return self.model.language_model
327
+
328
+ @property
329
+ def vision_tower(self):
330
+ return self.model.vision_tower
331
+
332
+ @property
333
+ def multi_modal_projector(self):
334
+ return self.model.multi_modal_projector
335
+
336
+ @can_return_tuple
337
+ @auto_docstring
338
+ def forward(
339
+ self,
340
+ input_ids: torch.LongTensor = None,
341
+ pixel_values: torch.FloatTensor = None,
342
+ attention_mask: Optional[torch.Tensor] = None,
343
+ position_ids: Optional[torch.LongTensor] = None,
344
+ past_key_values: Optional[Cache] = None,
345
+ inputs_embeds: Optional[torch.FloatTensor] = None,
346
+ vision_feature_layers: Optional[Union[int, list[int]]] = None,
347
+ labels: Optional[torch.LongTensor] = None,
348
+ use_cache: Optional[bool] = None,
349
+ output_attentions: Optional[bool] = None,
350
+ output_hidden_states: Optional[bool] = None,
351
+ return_dict: Optional[bool] = None,
352
+ cache_position: Optional[torch.LongTensor] = None,
353
+ logits_to_keep: Union[int, torch.Tensor] = 0,
354
+ **lm_kwargs,
355
+ ) -> Union[tuple, VipLlavaCausalLMOutputWithPast]:
356
+ r"""
357
+ vision_feature_layers (`Union[int, list[int]]`, *optional*):
358
+ The vision feature layer, or the list of indexes of the layers to select
359
+ the vision feature.
360
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
361
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
362
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
363
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
364
+
365
+ Example:
366
+
367
+ ```python
368
+ >>> import torch
369
+ >>> from PIL import Image
370
+ >>> import requests
371
+ >>> from transformers import AutoProcessor, VipLlavaForConditionalGeneration
372
+
373
+ >>> model = VipLlavaForConditionalGeneration.from_pretrained("llava-hf/vip-llava-7b-hf", device_map="auto", torch_dtype=torch.float16)
374
+ >>> processor = AutoProcessor.from_pretrained("llava-hf/vip-llava-7b-hf")
375
+
376
+ >>> prompt = "A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions.###Human: <image>\n{}###Assistant:"
377
+ >>> question = "Can you please describe this image?"
378
+ >>> prompt = prompt.format(question)
379
+ >>> url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/compel-neg.png"
380
+ >>> image = Image.open(requests.get(url, stream=True).raw)
381
+
382
+ >>> inputs = processor(text=text, images=image, return_tensors="pt").to(0, torch.float16)
383
+
384
+ >>> # Generate
385
+ >>> generate_ids = model.generate(**inputs, max_new_tokens=20)
386
+ >>> processor.decode(generate_ids[0][len(inputs["input_ids"][0]):], skip_special_tokens=True)
387
+ The image features a brown and white cat sitting on a green surface, with a red ball in its
388
+ ```"""
389
+
390
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
391
+ output_hidden_states = (
392
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
393
+ )
394
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
395
+ vision_feature_layers = (
396
+ vision_feature_layers if vision_feature_layers is not None else self.config.vision_feature_layers
397
+ )
398
+
399
+ outputs = self.model(
400
+ input_ids=input_ids,
401
+ pixel_values=pixel_values,
402
+ attention_mask=attention_mask,
403
+ position_ids=position_ids,
404
+ past_key_values=past_key_values,
405
+ inputs_embeds=inputs_embeds,
406
+ use_cache=use_cache,
407
+ vision_feature_layers=vision_feature_layers,
408
+ output_attentions=output_attentions,
409
+ output_hidden_states=output_hidden_states,
410
+ return_dict=True,
411
+ cache_position=cache_position,
412
+ **lm_kwargs,
413
+ )
414
+
415
+ hidden_states = outputs[0]
416
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
417
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
418
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
419
+
420
+ loss = None
421
+ if labels is not None:
422
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size)
423
+
424
+ return VipLlavaCausalLMOutputWithPast(
425
+ loss=loss,
426
+ logits=logits,
427
+ past_key_values=outputs.past_key_values,
428
+ hidden_states=outputs.hidden_states,
429
+ attentions=outputs.attentions,
430
+ image_hidden_states=outputs.image_hidden_states,
431
+ )
432
+
433
+ def prepare_inputs_for_generation(
434
+ self,
435
+ input_ids,
436
+ past_key_values=None,
437
+ inputs_embeds=None,
438
+ pixel_values=None,
439
+ attention_mask=None,
440
+ cache_position=None,
441
+ logits_to_keep=None,
442
+ **kwargs,
443
+ ):
444
+ # Overwritten -- in specific circumstances we don't want to forward image inputs to the model
445
+
446
+ model_inputs = super().prepare_inputs_for_generation(
447
+ input_ids,
448
+ past_key_values=past_key_values,
449
+ inputs_embeds=inputs_embeds,
450
+ attention_mask=attention_mask,
451
+ cache_position=cache_position,
452
+ logits_to_keep=logits_to_keep,
453
+ **kwargs,
454
+ )
455
+
456
+ if cache_position[0] == 0:
457
+ # If we're in cached decoding stage, pixel values should be None because input ids do not contain special image token anymore
458
+ # Otherwise we need pixel values to be passed to model
459
+ model_inputs["pixel_values"] = pixel_values
460
+
461
+ return model_inputs
462
+
463
+
464
+ __all__ = ["VipLlavaModel", "VipLlavaForConditionalGeneration", "VipLlavaPreTrainedModel"]
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/vipllava/modular_vipllava.py ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 the HuggingFace Inc. team. 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
+ from typing import Optional, Union
17
+
18
+ import torch
19
+ from torch import nn
20
+
21
+ from transformers.models.llava.modeling_llava import (
22
+ LlavaCausalLMOutputWithPast,
23
+ LlavaForConditionalGeneration,
24
+ LlavaModel,
25
+ LlavaModelOutputWithPast,
26
+ LlavaPreTrainedModel,
27
+ )
28
+
29
+ from ...activations import ACT2FN
30
+ from ...cache_utils import Cache
31
+ from ...utils import auto_docstring, logging
32
+ from .configuration_vipllava import VipLlavaConfig
33
+
34
+
35
+ logger = logging.get_logger(__name__)
36
+
37
+
38
+ class VipLlavaModelOutputWithPast(LlavaModelOutputWithPast):
39
+ pass
40
+
41
+
42
+ class VipLlavaCausalLMOutputWithPast(LlavaCausalLMOutputWithPast):
43
+ pass
44
+
45
+
46
+ class VipLlavaMultiModalProjector(nn.Module):
47
+ def __init__(self, config: VipLlavaConfig):
48
+ super().__init__()
49
+ num_feature_layers = 1 if isinstance(config.vision_feature_layers, int) else len(config.vision_feature_layers)
50
+ self.projector_layernorm = nn.LayerNorm(
51
+ num_feature_layers * config.vision_config.hidden_size, eps=config.projector_layernorm_eps
52
+ )
53
+
54
+ self.linear_1 = nn.Linear(
55
+ num_feature_layers * config.vision_config.hidden_size,
56
+ config.text_config.hidden_size,
57
+ bias=True,
58
+ )
59
+ self.act = ACT2FN[config.projector_hidden_act]
60
+ self.linear_2 = nn.Linear(config.text_config.hidden_size, config.text_config.hidden_size, bias=True)
61
+
62
+ def forward(self, hidden_states):
63
+ hidden_states = self.projector_layernorm(hidden_states)
64
+ hidden_states = self.linear_1(hidden_states)
65
+ hidden_states = self.act(hidden_states)
66
+ hidden_states = self.linear_2(hidden_states)
67
+ return hidden_states
68
+
69
+
70
+ class VipLlavaPreTrainedModel(LlavaPreTrainedModel):
71
+ pass
72
+
73
+
74
+ class VipLlavaModel(LlavaModel):
75
+ def get_image_features(
76
+ self, pixel_values: torch.FloatTensor, vision_feature_layers: Optional[Union[int, list[int]]] = None
77
+ ):
78
+ """
79
+ Obtains image last hidden states from the vision tower and apply multimodal projection.
80
+
81
+ Args:
82
+ pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`)
83
+ The tensors corresponding to the input images.
84
+ vision_feature_layers (`Union[int, list[int]]`):
85
+ The vision feature layer, or the list of indexes of the layers to select
86
+ the vision feature.
87
+ Returns:
88
+ image_features (`torch.Tensor`): Image feature tensor of shape `(num_images, image_length, embed_dim)`).
89
+ """
90
+ vision_feature_layers = (
91
+ vision_feature_layers if vision_feature_layers is not None else self.config.vision_feature_layers
92
+ )
93
+ image_outputs = self.vision_tower(pixel_values, output_hidden_states=True)
94
+
95
+ # If multiple feature layers are provided (which is usually the case)
96
+ # then the image features are concatenated after the CLS is removed.
97
+ if isinstance(vision_feature_layers, int):
98
+ image_features = image_outputs.hidden_states[vision_feature_layers][:, 1:]
99
+ else:
100
+ # Usually, we select the features from index 1: the layers -2, -5, -8, -11 and 6
101
+ image_features = [image_outputs.hidden_states[index][:, 1:] for index in vision_feature_layers]
102
+ image_features = torch.cat(image_features, dim=-1)
103
+ image_features = self.multi_modal_projector(image_features)
104
+ return image_features
105
+
106
+ @auto_docstring
107
+ def forward(
108
+ self,
109
+ input_ids: torch.LongTensor = None,
110
+ pixel_values: torch.FloatTensor = None,
111
+ attention_mask: Optional[torch.Tensor] = None,
112
+ position_ids: Optional[torch.LongTensor] = None,
113
+ past_key_values: Optional[Cache] = None,
114
+ inputs_embeds: Optional[torch.FloatTensor] = None,
115
+ vision_feature_layers: Optional[Union[int, list[int]]] = None,
116
+ use_cache: Optional[bool] = None,
117
+ output_attentions: Optional[bool] = None,
118
+ output_hidden_states: Optional[bool] = None,
119
+ return_dict: Optional[bool] = None,
120
+ cache_position: Optional[torch.LongTensor] = None,
121
+ **lm_kwargs,
122
+ ) -> Union[tuple, VipLlavaModelOutputWithPast]:
123
+ r"""
124
+ vision_feature_layers (`Union[int, list[int]]`, *optional*):
125
+ The vision feature layer, or the list of indexes of the layers to select
126
+ the vision feature.
127
+ """
128
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
129
+ output_hidden_states = (
130
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
131
+ )
132
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
133
+ vision_feature_layers = (
134
+ vision_feature_layers if vision_feature_layers is not None else self.config.vision_feature_layers
135
+ )
136
+
137
+ if (input_ids is None) ^ (inputs_embeds is not None):
138
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
139
+
140
+ if inputs_embeds is None:
141
+ inputs_embeds = self.get_input_embeddings()(input_ids)
142
+
143
+ if pixel_values is not None:
144
+ image_features = self.get_image_features(
145
+ pixel_values=pixel_values, vision_feature_layers=vision_feature_layers
146
+ )
147
+ image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
148
+ special_image_mask = self.get_placeholder_mask(
149
+ input_ids, inputs_embeds=inputs_embeds, image_features=image_features
150
+ )
151
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
152
+
153
+ outputs = self.language_model(
154
+ attention_mask=attention_mask,
155
+ position_ids=position_ids,
156
+ past_key_values=past_key_values,
157
+ inputs_embeds=inputs_embeds,
158
+ use_cache=use_cache,
159
+ output_attentions=output_attentions,
160
+ output_hidden_states=output_hidden_states,
161
+ return_dict=True,
162
+ cache_position=cache_position,
163
+ **lm_kwargs,
164
+ )
165
+
166
+ output = VipLlavaModelOutputWithPast(
167
+ last_hidden_state=outputs.last_hidden_state,
168
+ past_key_values=outputs.past_key_values,
169
+ hidden_states=outputs.hidden_states,
170
+ attentions=outputs.attentions,
171
+ image_hidden_states=image_features if pixel_values is not None else None,
172
+ )
173
+ return output if return_dict else output.to_tuple()
174
+
175
+
176
+ class VipLlavaForConditionalGeneration(LlavaForConditionalGeneration):
177
+ def get_image_features(
178
+ self, pixel_values: torch.FloatTensor, vision_feature_layers: Optional[Union[int, list[int]]] = None
179
+ ):
180
+ return self.model.get_image_features(pixel_values=pixel_values, vision_feature_layers=vision_feature_layers)
181
+
182
+ def forward(
183
+ self,
184
+ input_ids: torch.LongTensor = None,
185
+ pixel_values: torch.FloatTensor = None,
186
+ attention_mask: Optional[torch.Tensor] = None,
187
+ position_ids: Optional[torch.LongTensor] = None,
188
+ past_key_values: Optional[Cache] = None,
189
+ inputs_embeds: Optional[torch.FloatTensor] = None,
190
+ vision_feature_layers: Optional[Union[int, list[int]]] = None,
191
+ labels: Optional[torch.LongTensor] = None,
192
+ use_cache: Optional[bool] = None,
193
+ output_attentions: Optional[bool] = None,
194
+ output_hidden_states: Optional[bool] = None,
195
+ return_dict: Optional[bool] = None,
196
+ cache_position: Optional[torch.LongTensor] = None,
197
+ logits_to_keep: Union[int, torch.Tensor] = 0,
198
+ **lm_kwargs,
199
+ ) -> Union[tuple, VipLlavaCausalLMOutputWithPast]:
200
+ r"""
201
+ vision_feature_layers (`Union[int, list[int]]`, *optional*):
202
+ The vision feature layer, or the list of indexes of the layers to select
203
+ the vision feature.
204
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
205
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
206
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
207
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
208
+
209
+ Example:
210
+
211
+ ```python
212
+ >>> import torch
213
+ >>> from PIL import Image
214
+ >>> import requests
215
+ >>> from transformers import AutoProcessor, VipLlavaForConditionalGeneration
216
+
217
+ >>> model = VipLlavaForConditionalGeneration.from_pretrained("llava-hf/vip-llava-7b-hf", device_map="auto", torch_dtype=torch.float16)
218
+ >>> processor = AutoProcessor.from_pretrained("llava-hf/vip-llava-7b-hf")
219
+
220
+ >>> prompt = "A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions.###Human: <image>\n{}###Assistant:"
221
+ >>> question = "Can you please describe this image?"
222
+ >>> prompt = prompt.format(question)
223
+ >>> url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/compel-neg.png"
224
+ >>> image = Image.open(requests.get(url, stream=True).raw)
225
+
226
+ >>> inputs = processor(text=text, images=image, return_tensors="pt").to(0, torch.float16)
227
+
228
+ >>> # Generate
229
+ >>> generate_ids = model.generate(**inputs, max_new_tokens=20)
230
+ >>> processor.decode(generate_ids[0][len(inputs["input_ids"][0]):], skip_special_tokens=True)
231
+ The image features a brown and white cat sitting on a green surface, with a red ball in its
232
+ ```"""
233
+
234
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
235
+ output_hidden_states = (
236
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
237
+ )
238
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
239
+ vision_feature_layers = (
240
+ vision_feature_layers if vision_feature_layers is not None else self.config.vision_feature_layers
241
+ )
242
+
243
+ outputs = self.model(
244
+ input_ids=input_ids,
245
+ pixel_values=pixel_values,
246
+ attention_mask=attention_mask,
247
+ position_ids=position_ids,
248
+ past_key_values=past_key_values,
249
+ inputs_embeds=inputs_embeds,
250
+ use_cache=use_cache,
251
+ vision_feature_layers=vision_feature_layers,
252
+ output_attentions=output_attentions,
253
+ output_hidden_states=output_hidden_states,
254
+ return_dict=True,
255
+ cache_position=cache_position,
256
+ **lm_kwargs,
257
+ )
258
+
259
+ hidden_states = outputs[0]
260
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
261
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
262
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
263
+
264
+ loss = None
265
+ if labels is not None:
266
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size)
267
+
268
+ return VipLlavaCausalLMOutputWithPast(
269
+ loss=loss,
270
+ logits=logits,
271
+ past_key_values=outputs.past_key_values,
272
+ hidden_states=outputs.hidden_states,
273
+ attentions=outputs.attentions,
274
+ image_hidden_states=outputs.image_hidden_states,
275
+ )
276
+
277
+
278
+ __all__ = ["VipLlavaModel", "VipLlavaForConditionalGeneration", "VipLlavaPreTrainedModel"]
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/vision_encoder_decoder/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. 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
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_vision_encoder_decoder import *
22
+ from .modeling_flax_vision_encoder_decoder import *
23
+ from .modeling_tf_vision_encoder_decoder import *
24
+ from .modeling_vision_encoder_decoder import *
25
+ else:
26
+ import sys
27
+
28
+ _file = globals()["__file__"]
29
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
tasks/tasksmith-5cbfd9f64dbc/tests/source/src/transformers/models/vision_encoder_decoder/configuration_vision_encoder_decoder.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The HuggingFace Inc. team.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
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
+ from collections import OrderedDict
18
+ from collections.abc import Mapping
19
+ from typing import TYPE_CHECKING, Any, Optional
20
+
21
+ from packaging import version
22
+
23
+ from ...configuration_utils import PretrainedConfig
24
+ from ...onnx import OnnxConfig
25
+ from ...utils import logging
26
+ from ..auto.configuration_auto import AutoConfig
27
+
28
+
29
+ if TYPE_CHECKING:
30
+ from ... import PreTrainedTokenizerBase, TensorType
31
+
32
+ logger = logging.get_logger(__name__)
33
+
34
+
35
+ class VisionEncoderDecoderConfig(PretrainedConfig):
36
+ r"""
37
+ [`VisionEncoderDecoderConfig`] is the configuration class to store the configuration of a
38
+ [`VisionEncoderDecoderModel`]. It is used to instantiate a Vision-Encoder-Text-Decoder model according to the
39
+ specified arguments, defining the encoder and decoder configs.
40
+
41
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
42
+ documentation from [`PretrainedConfig`] for more information.
43
+
44
+ Args:
45
+ kwargs (*optional*):
46
+ Dictionary of keyword arguments. Notably:
47
+
48
+ - **encoder** ([`PretrainedConfig`], *optional*) -- An instance of a configuration object that defines
49
+ the encoder config.
50
+ - **decoder** ([`PretrainedConfig`], *optional*) -- An instance of a configuration object that defines
51
+ the decoder config.
52
+
53
+ Examples:
54
+
55
+ ```python
56
+ >>> from transformers import BertConfig, ViTConfig, VisionEncoderDecoderConfig, VisionEncoderDecoderModel
57
+
58
+ >>> # Initializing a ViT & BERT style configuration
59
+ >>> config_encoder = ViTConfig()
60
+ >>> config_decoder = BertConfig()
61
+
62
+ >>> config = VisionEncoderDecoderConfig.from_encoder_decoder_configs(config_encoder, config_decoder)
63
+
64
+ >>> # Initializing a ViTBert model (with random weights) from a ViT & google-bert/bert-base-uncased style configurations
65
+ >>> model = VisionEncoderDecoderModel(config=config)
66
+
67
+ >>> # Accessing the model configuration
68
+ >>> config_encoder = model.config.encoder
69
+ >>> config_decoder = model.config.decoder
70
+ >>> # set decoder config to causal lm
71
+ >>> config_decoder.is_decoder = True
72
+ >>> config_decoder.add_cross_attention = True
73
+
74
+ >>> # Saving the model, including its configuration
75
+ >>> model.save_pretrained("my-model")
76
+
77
+ >>> # loading model and config from pretrained folder
78
+ >>> encoder_decoder_config = VisionEncoderDecoderConfig.from_pretrained("my-model")
79
+ >>> model = VisionEncoderDecoderModel.from_pretrained("my-model", config=encoder_decoder_config)
80
+ ```"""
81
+
82
+ model_type = "vision-encoder-decoder"
83
+ sub_configs = {"encoder": AutoConfig, "decoder": AutoConfig}
84
+ has_no_defaults_at_init = True
85
+
86
+ def __init__(self, **kwargs):
87
+ super().__init__(**kwargs)
88
+ if "encoder" not in kwargs or "decoder" not in kwargs:
89
+ raise ValueError(
90
+ f"A configuration of type {self.model_type} cannot be instantiated because "
91
+ f"not both `encoder` and `decoder` sub-configurations are passed, but only {kwargs}"
92
+ )
93
+
94
+ encoder_config = kwargs.pop("encoder")
95
+ encoder_model_type = encoder_config.pop("model_type")
96
+ decoder_config = kwargs.pop("decoder")
97
+ decoder_model_type = decoder_config.pop("model_type")
98
+
99
+ self.encoder = AutoConfig.for_model(encoder_model_type, **encoder_config)
100
+ self.decoder = AutoConfig.for_model(decoder_model_type, **decoder_config)
101
+ self.is_encoder_decoder = True
102
+
103
+ @classmethod
104
+ def from_encoder_decoder_configs(
105
+ cls, encoder_config: PretrainedConfig, decoder_config: PretrainedConfig, **kwargs
106
+ ) -> PretrainedConfig:
107
+ r"""
108
+ Instantiate a [`VisionEncoderDecoderConfig`] (or a derived class) from a pre-trained encoder model
109
+ configuration and decoder model configuration.
110
+
111
+ Returns:
112
+ [`VisionEncoderDecoderConfig`]: An instance of a configuration object
113
+ """
114
+ logger.info("Setting `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config")
115
+ decoder_config.is_decoder = True
116
+ decoder_config.add_cross_attention = True
117
+
118
+ return cls(encoder=encoder_config.to_dict(), decoder=decoder_config.to_dict(), **kwargs)
119
+
120
+
121
+ class VisionEncoderDecoderEncoderOnnxConfig(OnnxConfig):
122
+ torch_onnx_minimum_version = version.parse("1.11")
123
+
124
+ @property
125
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
126
+ return OrderedDict(
127
+ [
128
+ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
129
+ ]
130
+ )
131
+
132
+ @property
133
+ def atol_for_validation(self) -> float:
134
+ return 1e-4
135
+
136
+ @property
137
+ def outputs(self) -> Mapping[str, Mapping[int, str]]:
138
+ return OrderedDict({"last_hidden_state": {0: "batch", 1: "encoder_sequence"}})
139
+
140
+
141
+ class VisionEncoderDecoderDecoderOnnxConfig(OnnxConfig):
142
+ @property
143
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
144
+ common_inputs = OrderedDict()
145
+ common_inputs["input_ids"] = {0: "batch", 1: "past_decoder_sequence + sequence"}
146
+ common_inputs["attention_mask"] = {0: "batch", 1: "past_decoder_sequence + sequence"}
147
+ common_inputs["encoder_hidden_states"] = {0: "batch", 1: "encoder_sequence"}
148
+
149
+ return common_inputs
150
+
151
+ def generate_dummy_inputs(
152
+ self,
153
+ tokenizer: "PreTrainedTokenizerBase",
154
+ batch_size: int = -1,
155
+ seq_length: int = -1,
156
+ is_pair: bool = False,
157
+ framework: Optional["TensorType"] = None,
158
+ ) -> Mapping[str, Any]:
159
+ import torch
160
+
161
+ common_inputs = OrderedDict()
162
+
163
+ dummy_input = super().generate_dummy_inputs(
164
+ tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
165
+ )
166
+
167
+ batch, encoder_sequence = dummy_input["input_ids"].shape
168
+ encoder_hidden_states_shape = (batch, encoder_sequence, self._config.encoder_hidden_size)
169
+ common_inputs["input_ids"] = dummy_input.pop("input_ids")
170
+ common_inputs["attention_mask"] = dummy_input.pop("attention_mask")
171
+ common_inputs["encoder_hidden_states"] = torch.zeros(encoder_hidden_states_shape)
172
+
173
+ return common_inputs
174
+
175
+
176
+ class VisionEncoderDecoderOnnxConfig(OnnxConfig):
177
+ @property
178
+ def inputs(self) -> None:
179
+ pass
180
+
181
+ def get_encoder_config(self, encoder_config: PretrainedConfig) -> OnnxConfig:
182
+ r"""
183
+ Returns ONNX encoder config for `VisionEncoderDecoder` model.
184
+
185
+ Args:
186
+ encoder_config (`PretrainedConfig`):
187
+ The encoder model's configuration to use when exporting to ONNX.
188
+
189
+ Returns:
190
+ [`VisionEncoderDecoderEncoderOnnxConfig`]: An instance of the ONNX configuration object
191
+ """
192
+ return VisionEncoderDecoderEncoderOnnxConfig(encoder_config)
193
+
194
+ def get_decoder_config(
195
+ self, encoder_config: PretrainedConfig, decoder_config: PretrainedConfig, feature: str = "default"
196
+ ) -> OnnxConfig:
197
+ r"""
198
+ Returns ONNX decoder config for `VisionEncoderDecoder` model.
199
+
200
+ Args:
201
+ encoder_config (`PretrainedConfig`):
202
+ The encoder model's configuration to use when exporting to ONNX.
203
+ decoder_config (`PretrainedConfig`):
204
+ The decoder model's configuration to use when exporting to ONNX
205
+ feature (`str`, *optional*):
206
+ The type of feature to export the model with.
207
+
208
+ Returns:
209
+ [`VisionEncoderDecoderDecoderOnnxConfig`]: An instance of the ONNX configuration object.
210
+ """
211
+ decoder_config.encoder_hidden_size = encoder_config.hidden_size
212
+ return VisionEncoderDecoderDecoderOnnxConfig(decoder_config, feature)
213
+
214
+
215
+ __all__ = ["VisionEncoderDecoderConfig", "VisionEncoderDecoderOnnxConfig"]