File size: 10,609 Bytes
6a109bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================

"""Text encoder implementation in PyTorch."""

import typing as t

import numpy as np
import sentencepiece as spm
import torch
from torch import nn
import torch.nn.functional as F


class Tokenizer(object):
  """A simple tokenizer using SentencePiece."""

  def __init__(self, tokenizer_path: str):
    self.sp = spm.SentencePieceProcessor(model_file=tokenizer_path)
    # Match tensorflow_text.SentencepieceTokenizer(add_bos=False, add_eos=False)
    self.sp.SetEncodeExtraOptions("")
    # Explicitly disable BOS/EOS to match the reference Colab implementation.
    self._add_bos = False
    self._add_eos = False

  def tokenize(self, input_texts, max_len=64):
    if isinstance(input_texts, str):
      input_texts = [input_texts]
    batch_ids = [
        self.sp.encode(t.lower(), add_bos=self._add_bos, add_eos=self._add_eos)
        for t in input_texts
    ]
    tokens = np.zeros((len(batch_ids), max_len), dtype=np.int64)
    for i, ids in enumerate(batch_ids):
      length = min(len(ids), max_len)
      tokens[i, :length] = ids[:length]
    is_padding = (tokens == 0).astype(np.int32)
    return tokens, is_padding


class PositionalEmbedding(nn.Module):
  """Generates position embedding for a given 1-d sequence.

  Attributes:
    min_timescale: Start of the geometric index. Determines the periodicity of
      the added signal.
    max_timescale: End of the geometric index. Determines the frequency of the
      added signal.
    embedding_dim: Dimension of the embedding to be generated.
  """

  min_timescale: int = 1
  max_timescale: int = 10_000
  embedding_dim: int = 0

  def __init__(self, embedding_dim: int):
    super().__init__()
    self.embedding_dim = embedding_dim

  def __call__(self, seq_length: int = None, position: torch.tensor = None):
    """Generates a torch.tensor of sinusoids with different frequencies.

    Args:
      seq_length: an optional Python int defining the output sequence length.
        if the `position` argument is specified.
      position:   [B, seq_length], optional position for each token in the
        sequence, only required when the sequence is packed.

    Returns:
      [B, seqlen, D] if `position` is specified, else [1, seqlen, D]
    """
    if position is None:
      assert seq_length is not None
      # [1, seqlen]
      position = torch.arange(seq_length, dtype=torch.float32)[None, :]
    else:
      assert position.ndim == 2, position.shape

    num_timescales = self.embedding_dim // 2
    log_timescale_increment = torch.log(
        torch.tensor(float(self.max_timescale) / float(self.min_timescale))
    ) / torch.maximum(
        torch.tensor(num_timescales, dtype=torch.float32) - 1, torch.tensor(1)
    )
    inv_timescales = self.min_timescale * torch.exp(
        torch.arange(num_timescales, dtype=torch.float32)
        * -log_timescale_increment
    )
    scaled_time = position[:, :, None] * inv_timescales[None, None, :]
    signal = torch.cat((torch.sin(scaled_time), torch.cos(scaled_time)), dim=2)
    # Force usage of `np` rather than `jnp` to compute static values at trace
    # time.
    signal = F.pad(signal, (0, self.embedding_dim % 2, 0, 0, 0, 0))
    return signal


class MlpBlockWithMask(nn.Module):
  """Transformer MLP / feed-forward block that supports masking."""

  def __init__(
      self,
      mlp_dim: int,
      d_model: int,
      use_bias: bool = True,
      dtype: torch.dtype = torch.float32,
      activation_fn: nn.Module = nn.GELU,
  ):
    super().__init__()

    self.mlp_dim = mlp_dim
    self.d_model = d_model
    self.use_bias = use_bias
    self.dtype = dtype
    self.activation_fn = activation_fn

    self.c_fc = nn.Linear(
        in_features=self.d_model,
        out_features=self.mlp_dim,
        dtype=self.dtype,
        bias=self.use_bias,
    )
    self.c_proj = nn.Linear(
        in_features=self.mlp_dim,
        out_features=self.d_model,
        dtype=self.dtype,
        bias=self.use_bias,
    )

  def __call__(
      self, inputs: torch.Tensor, mlp_mask: torch.Tensor
  ) -> torch.Tensor:
    """Applies Transformer MlpBlock with mask module."""
    x = self.c_fc(inputs)
    x = self.activation_fn()(x)
    x = x * mlp_mask[..., None]  # First masking.
    x = self.c_proj(x)
    x = x * mlp_mask[..., None]  # Second masking.
    return x


class ResidualAttentionBlock(nn.Module):
  """Transformer residual attention block."""

  def __init__(
      self,
      d_model: int,
      n_head: int,
      mlp_dim: int,
      dtype: torch.dtype = torch.float32,
  ):
    super().__init__()
    self.d_model = d_model
    self.n_head = n_head
    self.mlp_dim = mlp_dim
    self.dtype = dtype

    self.attn = nn.MultiheadAttention(d_model, n_head, dtype=self.dtype)
    self.ln_1 = nn.LayerNorm(d_model, dtype=self.dtype)
    self.mlp = MlpBlockWithMask(
        self.mlp_dim,
        d_model,
        use_bias=True,
        dtype=self.dtype,
        activation_fn=nn.ReLU,
    )
    self.ln_2 = nn.LayerNorm(d_model, dtype=self.dtype)

  def attention(self, x: torch.Tensor, mask: torch.Tensor):
    attn_mask = (
        mask[:, None, None, :]
        .repeat(1, self.n_head, x.shape[0], 1)
        .flatten(0, 1)
    )
    attn_mask[attn_mask == 0] = float('-inf')
    attn_mask[attn_mask == 1] = 0
    return self.attn(x, x, x, need_weights=False, attn_mask=attn_mask)[0]

  def forward(self, x: torch.Tensor, mask: torch.Tensor):
    x = x + self.attention(self.ln_1(x), mask.permute(1, 0))
    x = x + self.mlp(self.ln_2(x), mask)
    return x, mask


class SequentialMultiInput(nn.Sequential):
  """Sequential module that can take multiple inputs."""

  def forward(self, *inputs):
    for module in self._modules.values():
      if isinstance(inputs, tuple):
        inputs = module(*inputs)
      else:
        inputs = module(inputs)
    return inputs


class Transformer(nn.Module):
  """Transformer implementation."""

  def __init__(
      self,
      width: int,
      layers: int,
      heads: int,
      mlp_dim: int,
      dtype: torch.dtype = torch.float32,
  ):
    super().__init__()
    self.width = width
    self.layers = layers
    self.heads = heads
    self.mlp_dim = mlp_dim
    self.dtype = dtype

    self.resblocks = SequentialMultiInput(*[
        ResidualAttentionBlock(self.width, self.heads, self.mlp_dim, self.dtype)
        for _ in range(self.layers)
    ])

  def forward(self, x: torch.Tensor, mask: torch.Tensor):
    return self.resblocks(x, mask)[0]


class GlobalAvgPooling(nn.Module):
  """Performs a simple global pooling over the input with optional paddings.

  Attributes:
    pooling_dims: A list of dims to perform pooling over.
    keepdims: If True, keep dimension of inputs after pooling.
  """

  pooling_dims: t.Sequence[int]
  epsilon: float = 1e-8

  def __init__(
      self, pooling_dims: t.Sequence[int], epsilon: float = 1e-8
  ):
    super().__init__()
    self.pooling_dims = pooling_dims
    self.epsilon = epsilon

    if not all([p_dims >= 0 for p_dims in self.pooling_dims]):
      raise ValueError('pooling_dims must be non-negative integers.')

  def __call__(
      self,
      inputs: torch.tensor,
      compatible_paddings: torch.tensor,
  ):
    """Applies global average spatial pooling to inputs.

    Args:
      inputs: An input tensor.
      compatible_paddings: paddings of inputs with shapes compatible with
        inputs, e.g. compatible_paddings with shape [B, 1] for inputs with shape
        [B, D].

    Returns:
      Output tensor with global pooling applied.
    """
    padded_value = torch.zeros_like(inputs)
    padded_value = torch.ones_like(inputs) * padded_value
    inputs = torch.where(compatible_paddings > 0, padded_value, inputs)
    valid_inputs = (
        torch.sum(
            1.0 - compatible_paddings,
            self.pooling_dims,
            keepdims=True,
            dtype=inputs.dtype,
        )
        + self.epsilon
    )
    inputs_sum = torch.sum(inputs, self.pooling_dims, keepdims=True)
    outputs = torch.divide(inputs_sum, valid_inputs).type(inputs.dtype)
    outputs = torch.squeeze(outputs, axis=self.pooling_dims)
    return outputs


class TextEncoder(nn.Module):
  """Text encoder implementation."""

  def __init__(
      self,
      config: t.Dict[str, int],
      vocab_size: int,
      dtype: torch.dtype = torch.float32,
      scale_sqrt_depth: bool = True,
  ):
    super().__init__()
    self.vocab_size = vocab_size
    self.dtype = dtype
    self.scale_sqrt_depth = scale_sqrt_depth

    # The text tower layers are fixed independent of vision tower size.
    self.transformer_layers = config['num_layers']
    self.embedding_dim = config['hidden_size']
    self.transformer_width = config['hidden_size']
    self.mlp_dim = config['mlp_dim']
    self.transformer_heads = config['num_heads']

    self.token_embedding = nn.Embedding(
        self.vocab_size, self.embedding_dim, dtype=self.dtype
    )
    self.pos_embedder = PositionalEmbedding(embedding_dim=self.embedding_dim)
    self.transformer = Transformer(
        width=self.transformer_width,
        layers=self.transformer_layers,
        heads=self.transformer_heads,
        mlp_dim=self.mlp_dim,
        dtype=self.dtype,
    )
    self.pooling = GlobalAvgPooling(pooling_dims=[1])
    self.ln_final = nn.LayerNorm(self.transformer_width, dtype=self.dtype)

  def __call__(
      self,
      ids: torch.tensor,
      paddings: torch.tensor,
  ):
    """Applies TextEncoder module."""
    _, seq_length = ids.shape
    mask = (paddings == 0).type(torch.float32)
    mask = mask.permute(1, 0)  # NL -> LN
    x = self.token_embedding(ids)
    if self.scale_sqrt_depth:
      x = x * (self.embedding_dim**0.5)
    x = x + self.pos_embedder(seq_length=seq_length).to(x.device)
    x = x.permute(1, 0, 2)  # NLD -> LND
    x = self.transformer(x, mask)
    x = x.permute(1, 0, 2)  # LND -> NLD
    x = self.ln_final(x)
    x = self.pooling(x, compatible_paddings=paddings[:, :, None])
    return x