Commit
·
e872961
1
Parent(s):
e04128b
Upload NGMEForCausalLM
Browse files- config.json +35 -0
- configuration_ngme.py +177 -0
- generation_config.json +7 -0
- modeling_ngme.py +1114 -0
- pytorch_model.bin +3 -0
- sampling.py +205 -0
- tokenization_ngme.py +1250 -0
config.json
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_name_or_path": "/scratch/phmaker/ngme/tiny-stories/checkpoint-80000",
|
| 3 |
+
"architectures": [
|
| 4 |
+
"NGMEForCausalLM"
|
| 5 |
+
],
|
| 6 |
+
"auto_map": {
|
| 7 |
+
"AutoConfig": "configuration_ngme.NGMEConfig",
|
| 8 |
+
"AutoModelForCausalLM": "modeling_ngme.NGMEForCausalLM"
|
| 9 |
+
},
|
| 10 |
+
"bos_token_id": 1,
|
| 11 |
+
"eos_token_id": 0,
|
| 12 |
+
"ffn_dim": 512,
|
| 13 |
+
"hidden_act": "silu",
|
| 14 |
+
"hidden_size": 1024,
|
| 15 |
+
"initializer_range": 0.02,
|
| 16 |
+
"intermediate_size": 11008,
|
| 17 |
+
"max_position_embeddings": 2048,
|
| 18 |
+
"model_type": "ngme",
|
| 19 |
+
"num_attention_heads": 4,
|
| 20 |
+
"num_hidden_layers": 4,
|
| 21 |
+
"num_key_value_heads": 4,
|
| 22 |
+
"pad_token_id": 0,
|
| 23 |
+
"pretraining_tp": 1,
|
| 24 |
+
"rms_norm_eps": 1e-06,
|
| 25 |
+
"rope_scaling": null,
|
| 26 |
+
"tie_word_embeddings": false,
|
| 27 |
+
"torch_dtype": "float32",
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
| 5 |
+
# and OPT implementations in this library. It has been modified from its
|
| 6 |
+
# original forms to accommodate minor architectural differences compared
|
| 7 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
|
| 21 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 22 |
+
from transformers.utils import logging
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
logger = logging.get_logger(__name__)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class NGMEConfig(PretrainedConfig):
|
| 29 |
+
r"""
|
| 30 |
+
This is the configuration class to store the configuration of a [`NGMEModel`]. It is used to instantiate an LLaMA
|
| 31 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
| 32 |
+
defaults will yield a similar configuration to that of the LLaMA-7B.
|
| 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 32000):
|
| 40 |
+
Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the
|
| 41 |
+
`inputs_ids` passed when calling [`NGMEModel`]
|
| 42 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
| 43 |
+
Dimension of the hidden representations.
|
| 44 |
+
intermediate_size (`int`, *optional*, defaults to 11008):
|
| 45 |
+
Dimension of the MLP representations.
|
| 46 |
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
| 47 |
+
Number of hidden layers in the Transformer encoder.
|
| 48 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
| 49 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 50 |
+
num_key_value_heads (`int`, *optional*):
|
| 51 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
| 52 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
| 53 |
+
`num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
| 54 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
| 55 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
| 56 |
+
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
|
| 57 |
+
`num_attention_heads`.
|
| 58 |
+
pretraining_tp (`int`, *optional*, defaults to `1`):
|
| 59 |
+
Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
|
| 60 |
+
document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
|
| 61 |
+
necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
|
| 62 |
+
issue](https://github.com/pytorch/pytorch/issues/76232).
|
| 63 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
| 64 |
+
The non-linear activation function (function or string) in the decoder.
|
| 65 |
+
max_position_embeddings (`int`, *optional*, defaults to 2048):
|
| 66 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
| 67 |
+
just in case (e.g., 512 or 1024 or 2048).
|
| 68 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 69 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 70 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-12):
|
| 71 |
+
The epsilon used by the rms normalization layers.
|
| 72 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 73 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
| 74 |
+
relevant if `config.is_decoder=True`.
|
| 75 |
+
tie_word_embeddings(`bool`, *optional*, defaults to `False`):
|
| 76 |
+
Whether to tie weight embeddings
|
| 77 |
+
rope_scaling (`Dict`, *optional*):
|
| 78 |
+
Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
|
| 79 |
+
strategies: linear and dynamic. Their scaling factor must be an float greater than 1. The expected format
|
| 80 |
+
is `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
|
| 81 |
+
`max_position_embeddings` to the expected new maximum. See the following thread for more information on how
|
| 82 |
+
these scaling strategies behave:
|
| 83 |
+
https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
|
| 84 |
+
experimental feature, subject to breaking API changes in future versions.
|
| 85 |
+
|
| 86 |
+
Example:
|
| 87 |
+
|
| 88 |
+
```python
|
| 89 |
+
>>> from transformers import NGMEModel, LlamaConfig
|
| 90 |
+
|
| 91 |
+
>>> # Initializing a LLaMA llama-7b style configuration
|
| 92 |
+
>>> configuration = NGMEConfig()
|
| 93 |
+
|
| 94 |
+
>>> # Initializing a model from the llama-7b style configuration
|
| 95 |
+
>>> model = NGMEModel(configuration)
|
| 96 |
+
|
| 97 |
+
>>> # Accessing the model configuration
|
| 98 |
+
>>> configuration = model.config
|
| 99 |
+
```"""
|
| 100 |
+
model_type = "ngme"
|
| 101 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 102 |
+
|
| 103 |
+
def __init__(
|
| 104 |
+
self,
|
| 105 |
+
vocab_size=32000,
|
| 106 |
+
hidden_size=4096,
|
| 107 |
+
intermediate_size=11008,
|
| 108 |
+
num_hidden_layers=32,
|
| 109 |
+
num_attention_heads=32,
|
| 110 |
+
num_key_value_heads=None,
|
| 111 |
+
hidden_act="silu",
|
| 112 |
+
max_position_embeddings=2048,
|
| 113 |
+
initializer_range=0.02,
|
| 114 |
+
rms_norm_eps=1e-6,
|
| 115 |
+
use_cache=True,
|
| 116 |
+
pad_token_id=None,
|
| 117 |
+
bos_token_id=1,
|
| 118 |
+
eos_token_id=2,
|
| 119 |
+
pretraining_tp=1,
|
| 120 |
+
tie_word_embeddings=False,
|
| 121 |
+
rope_scaling=None,
|
| 122 |
+
use_flash_attn=False,
|
| 123 |
+
use_small_embedding=False,
|
| 124 |
+
unk_idx=-1,
|
| 125 |
+
**kwargs,
|
| 126 |
+
):
|
| 127 |
+
self.vocab_size = vocab_size
|
| 128 |
+
self.unk_idx = unk_idx
|
| 129 |
+
self.max_position_embeddings = max_position_embeddings
|
| 130 |
+
self.hidden_size = hidden_size
|
| 131 |
+
self.intermediate_size = intermediate_size
|
| 132 |
+
self.num_hidden_layers = num_hidden_layers
|
| 133 |
+
self.num_attention_heads = num_attention_heads
|
| 134 |
+
|
| 135 |
+
# for backward compatibility
|
| 136 |
+
if num_key_value_heads is None:
|
| 137 |
+
num_key_value_heads = num_attention_heads
|
| 138 |
+
|
| 139 |
+
self.num_key_value_heads = num_key_value_heads
|
| 140 |
+
self.hidden_act = hidden_act
|
| 141 |
+
self.initializer_range = initializer_range
|
| 142 |
+
self.rms_norm_eps = rms_norm_eps
|
| 143 |
+
self.pretraining_tp = pretraining_tp
|
| 144 |
+
self.use_cache = use_cache
|
| 145 |
+
self.rope_scaling = rope_scaling
|
| 146 |
+
self._rope_scaling_validation()
|
| 147 |
+
self.use_flash_attn = use_flash_attn
|
| 148 |
+
self.use_small_embedding = use_small_embedding
|
| 149 |
+
|
| 150 |
+
super().__init__(
|
| 151 |
+
pad_token_id=pad_token_id,
|
| 152 |
+
bos_token_id=bos_token_id,
|
| 153 |
+
eos_token_id=eos_token_id,
|
| 154 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 155 |
+
**kwargs,
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
def _rope_scaling_validation(self):
|
| 159 |
+
"""
|
| 160 |
+
Validate the `rope_scaling` configuration.
|
| 161 |
+
"""
|
| 162 |
+
if self.rope_scaling is None:
|
| 163 |
+
return
|
| 164 |
+
|
| 165 |
+
if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
|
| 166 |
+
raise ValueError(
|
| 167 |
+
"`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, "
|
| 168 |
+
f"got {self.rope_scaling}"
|
| 169 |
+
)
|
| 170 |
+
rope_scaling_type = self.rope_scaling.get("type", None)
|
| 171 |
+
rope_scaling_factor = self.rope_scaling.get("factor", None)
|
| 172 |
+
if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
|
| 173 |
+
raise ValueError(
|
| 174 |
+
f"`rope_scaling`'s name field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
|
| 175 |
+
)
|
| 176 |
+
if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
|
| 177 |
+
raise ValueError(f"`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}")
|
generation_config.json
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_from_model_config": true,
|
| 3 |
+
"bos_token_id": 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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
| 5 |
+
# and OPT implementations in this library. It has been modified from its
|
| 6 |
+
# original forms to accommodate minor architectural differences compared
|
| 7 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
""" PyTorch LLaMA model."""
|
| 21 |
+
import math
|
| 22 |
+
from typing import List, Optional, Tuple, Union
|
| 23 |
+
|
| 24 |
+
import torch
|
| 25 |
+
import torch.nn.functional as F
|
| 26 |
+
import torch.utils.checkpoint
|
| 27 |
+
from torch import nn
|
| 28 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 29 |
+
|
| 30 |
+
from transformers.activations import ACT2FN
|
| 31 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
|
| 32 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 33 |
+
from transformers.utils import logging
|
| 34 |
+
from transformers.generation.utils import SampleOutput
|
| 35 |
+
from transformers.generation.logits_process import LogitsProcessorList
|
| 36 |
+
from transformers.generation.stopping_criteria import StoppingCriteriaList
|
| 37 |
+
|
| 38 |
+
from .tokenization_ngme import NGMETokenizer
|
| 39 |
+
from .sampling import sample as sample_ngme
|
| 40 |
+
|
| 41 |
+
# Flash Attn imports
|
| 42 |
+
try:
|
| 43 |
+
from flash_attn.flash_attn_interface import flash_attn_varlen_qkvpacked_func
|
| 44 |
+
from flash_attn.bert_padding import unpad_input, pad_input
|
| 45 |
+
except Exception:
|
| 46 |
+
pass
|
| 47 |
+
|
| 48 |
+
try:
|
| 49 |
+
from einops import rearrange
|
| 50 |
+
except Exception:
|
| 51 |
+
pass
|
| 52 |
+
|
| 53 |
+
from .configuration_ngme import NGMEConfig
|
| 54 |
+
|
| 55 |
+
from ngme import (
|
| 56 |
+
soft_n_hot,
|
| 57 |
+
NGramsEmbedding,
|
| 58 |
+
collect_n_gram_sequences,
|
| 59 |
+
shift_with_pad,
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
logger = logging.get_logger(__name__)
|
| 63 |
+
|
| 64 |
+
# Copied from transformers.models.bart.modeling_bart._make_causal_mask
|
| 65 |
+
def _make_causal_mask(
|
| 66 |
+
input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
|
| 67 |
+
):
|
| 68 |
+
"""
|
| 69 |
+
Make causal mask used for bi-directional self-attention.
|
| 70 |
+
"""
|
| 71 |
+
bsz, tgt_len = input_ids_shape
|
| 72 |
+
mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
|
| 73 |
+
mask_cond = torch.arange(mask.size(-1), device=device)
|
| 74 |
+
mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
|
| 75 |
+
mask = mask.to(dtype)
|
| 76 |
+
|
| 77 |
+
if past_key_values_length > 0:
|
| 78 |
+
mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
|
| 79 |
+
return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
# Copied from transformers.models.bart.modeling_bart._expand_mask
|
| 83 |
+
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
|
| 84 |
+
"""
|
| 85 |
+
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
|
| 86 |
+
"""
|
| 87 |
+
bsz, src_len = mask.size()
|
| 88 |
+
tgt_len = tgt_len if tgt_len is not None else src_len
|
| 89 |
+
|
| 90 |
+
expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
|
| 91 |
+
|
| 92 |
+
inverted_mask = 1.0 - expanded_mask
|
| 93 |
+
|
| 94 |
+
return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class NGMERMSNorm(nn.Module):
|
| 98 |
+
def __init__(self, hidden_size, eps=1e-6):
|
| 99 |
+
"""
|
| 100 |
+
NGMERMSNorm is equivalent to T5LayerNorm
|
| 101 |
+
"""
|
| 102 |
+
super().__init__()
|
| 103 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 104 |
+
self.variance_epsilon = eps
|
| 105 |
+
|
| 106 |
+
def forward(self, hidden_states):
|
| 107 |
+
input_dtype = hidden_states.dtype
|
| 108 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 109 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 110 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 111 |
+
return self.weight * hidden_states.to(input_dtype)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
class NGMERotaryEmbedding(torch.nn.Module):
|
| 115 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
|
| 116 |
+
super().__init__()
|
| 117 |
+
|
| 118 |
+
self.dim = dim
|
| 119 |
+
self.max_position_embeddings = max_position_embeddings
|
| 120 |
+
self.base = base
|
| 121 |
+
inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
|
| 122 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 123 |
+
|
| 124 |
+
# Build here to make `torch.jit.trace` work.
|
| 125 |
+
self._set_cos_sin_cache(
|
| 126 |
+
seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
| 130 |
+
self.max_seq_len_cached = seq_len
|
| 131 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
|
| 132 |
+
|
| 133 |
+
freqs = torch.einsum("i,j->ij", t, self.inv_freq)
|
| 134 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
| 135 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 136 |
+
self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)
|
| 137 |
+
self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)
|
| 138 |
+
|
| 139 |
+
def forward(self, x, seq_len=None):
|
| 140 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
| 141 |
+
if seq_len > self.max_seq_len_cached:
|
| 142 |
+
self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
|
| 143 |
+
|
| 144 |
+
return (
|
| 145 |
+
self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
|
| 146 |
+
self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class NGMELinearScalingRotaryEmbedding(NGMERotaryEmbedding):
|
| 151 |
+
"""NGMERotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
|
| 152 |
+
|
| 153 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
|
| 154 |
+
self.scaling_factor = scaling_factor
|
| 155 |
+
super().__init__(dim, max_position_embeddings, base, device)
|
| 156 |
+
|
| 157 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
| 158 |
+
self.max_seq_len_cached = seq_len
|
| 159 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
|
| 160 |
+
t = t / self.scaling_factor
|
| 161 |
+
|
| 162 |
+
freqs = torch.einsum("i,j->ij", t, self.inv_freq)
|
| 163 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
| 164 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 165 |
+
self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)
|
| 166 |
+
self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
class NGMEDynamicNTKScalingRotaryEmbedding(NGMERotaryEmbedding):
|
| 170 |
+
"""NGMERotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
|
| 171 |
+
|
| 172 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
|
| 173 |
+
self.scaling_factor = scaling_factor
|
| 174 |
+
super().__init__(dim, max_position_embeddings, base, device)
|
| 175 |
+
|
| 176 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
| 177 |
+
self.max_seq_len_cached = seq_len
|
| 178 |
+
|
| 179 |
+
if seq_len > self.max_position_embeddings:
|
| 180 |
+
base = self.base * (
|
| 181 |
+
(self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
|
| 182 |
+
) ** (self.dim / (self.dim - 2))
|
| 183 |
+
inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
|
| 184 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 185 |
+
|
| 186 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
|
| 187 |
+
|
| 188 |
+
freqs = torch.einsum("i,j->ij", t, self.inv_freq)
|
| 189 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
| 190 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 191 |
+
self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)
|
| 192 |
+
self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def rotate_half(x):
|
| 196 |
+
"""Rotates half the hidden dims of the input."""
|
| 197 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 198 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
| 199 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
|
| 203 |
+
# The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
|
| 204 |
+
cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
|
| 205 |
+
sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
|
| 206 |
+
cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
|
| 207 |
+
sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
|
| 208 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
| 209 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
| 210 |
+
return q_embed, k_embed
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
class NGMEMLP(nn.Module):
|
| 214 |
+
def __init__(self, config):
|
| 215 |
+
super().__init__()
|
| 216 |
+
self.config = config
|
| 217 |
+
self.hidden_size = config.hidden_size
|
| 218 |
+
self.intermediate_size = config.intermediate_size
|
| 219 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 220 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 221 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
| 222 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 223 |
+
|
| 224 |
+
def forward(self, x):
|
| 225 |
+
if self.config.pretraining_tp > 1:
|
| 226 |
+
slice = self.intermediate_size // self.config.pretraining_tp
|
| 227 |
+
gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
|
| 228 |
+
up_proj_slices = self.up_proj.weight.split(slice, dim=0)
|
| 229 |
+
down_proj_slices = self.down_proj.weight.split(slice, dim=1)
|
| 230 |
+
|
| 231 |
+
gate_proj = torch.cat(
|
| 232 |
+
[F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
|
| 233 |
+
)
|
| 234 |
+
up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
|
| 235 |
+
|
| 236 |
+
intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
|
| 237 |
+
down_proj = [
|
| 238 |
+
F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
|
| 239 |
+
]
|
| 240 |
+
down_proj = sum(down_proj)
|
| 241 |
+
else:
|
| 242 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
| 243 |
+
|
| 244 |
+
return down_proj
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 248 |
+
"""
|
| 249 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
| 250 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
| 251 |
+
"""
|
| 252 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 253 |
+
if n_rep == 1:
|
| 254 |
+
return hidden_states
|
| 255 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
| 256 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
class NGMEAttention(nn.Module):
|
| 260 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 261 |
+
|
| 262 |
+
def __init__(self, config: NGMEConfig):
|
| 263 |
+
super().__init__()
|
| 264 |
+
self.config = config
|
| 265 |
+
self.hidden_size = config.hidden_size
|
| 266 |
+
self.num_heads = config.num_attention_heads
|
| 267 |
+
self.head_dim = self.hidden_size // self.num_heads
|
| 268 |
+
self.num_key_value_heads = config.num_key_value_heads
|
| 269 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
| 270 |
+
self.max_position_embeddings = config.max_position_embeddings
|
| 271 |
+
|
| 272 |
+
if (self.head_dim * self.num_heads) != self.hidden_size:
|
| 273 |
+
raise ValueError(
|
| 274 |
+
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
| 275 |
+
f" and `num_heads`: {self.num_heads})."
|
| 276 |
+
)
|
| 277 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
|
| 278 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
|
| 279 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
|
| 280 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
|
| 281 |
+
self._init_rope()
|
| 282 |
+
|
| 283 |
+
def _init_rope(self):
|
| 284 |
+
if self.config.rope_scaling is None:
|
| 285 |
+
self.rotary_emb = NGMERotaryEmbedding(self.head_dim, max_position_embeddings=self.max_position_embeddings)
|
| 286 |
+
else:
|
| 287 |
+
scaling_type = self.config.rope_scaling["type"]
|
| 288 |
+
scaling_factor = self.config.rope_scaling["factor"]
|
| 289 |
+
if scaling_type == "linear":
|
| 290 |
+
self.rotary_emb = NGMELinearScalingRotaryEmbedding(
|
| 291 |
+
self.head_dim, max_position_embeddings=self.max_position_embeddings, scaling_factor=scaling_factor
|
| 292 |
+
)
|
| 293 |
+
elif scaling_type == "dynamic":
|
| 294 |
+
self.rotary_emb = NGMEDynamicNTKScalingRotaryEmbedding(
|
| 295 |
+
self.head_dim, max_position_embeddings=self.max_position_embeddings, scaling_factor=scaling_factor
|
| 296 |
+
)
|
| 297 |
+
else:
|
| 298 |
+
raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
|
| 299 |
+
|
| 300 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
| 301 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
| 302 |
+
|
| 303 |
+
def forward(
|
| 304 |
+
self,
|
| 305 |
+
hidden_states: torch.Tensor,
|
| 306 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 307 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 308 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
| 309 |
+
output_attentions: bool = False,
|
| 310 |
+
use_cache: bool = False,
|
| 311 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 312 |
+
|
| 313 |
+
if self.config.use_flash_attn:
|
| 314 |
+
return self._flash_forward(
|
| 315 |
+
hidden_states,
|
| 316 |
+
attention_mask=attention_mask,
|
| 317 |
+
position_ids=position_ids,
|
| 318 |
+
past_key_value=past_key_value,
|
| 319 |
+
output_attentions=output_attentions,
|
| 320 |
+
use_cache=use_cache,
|
| 321 |
+
)
|
| 322 |
+
|
| 323 |
+
return self._forward(
|
| 324 |
+
hidden_states,
|
| 325 |
+
attention_mask=attention_mask,
|
| 326 |
+
position_ids=position_ids,
|
| 327 |
+
past_key_value=past_key_value,
|
| 328 |
+
output_attentions=output_attentions,
|
| 329 |
+
use_cache=use_cache,
|
| 330 |
+
)
|
| 331 |
+
|
| 332 |
+
def _forward(
|
| 333 |
+
self,
|
| 334 |
+
hidden_states: torch.Tensor,
|
| 335 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 336 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 337 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
| 338 |
+
output_attentions: bool = False,
|
| 339 |
+
use_cache: bool = False,
|
| 340 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 341 |
+
|
| 342 |
+
bsz, q_len, _ = hidden_states.size()
|
| 343 |
+
|
| 344 |
+
if self.config.pretraining_tp > 1:
|
| 345 |
+
key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
|
| 346 |
+
query_slices = self.q_proj.weight.split(
|
| 347 |
+
(self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
|
| 348 |
+
)
|
| 349 |
+
key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
|
| 350 |
+
value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
|
| 351 |
+
|
| 352 |
+
query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
|
| 353 |
+
query_states = torch.cat(query_states, dim=-1)
|
| 354 |
+
|
| 355 |
+
key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
|
| 356 |
+
key_states = torch.cat(key_states, dim=-1)
|
| 357 |
+
|
| 358 |
+
value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
|
| 359 |
+
value_states = torch.cat(value_states, dim=-1)
|
| 360 |
+
|
| 361 |
+
else:
|
| 362 |
+
query_states = self.q_proj(hidden_states)
|
| 363 |
+
key_states = self.k_proj(hidden_states)
|
| 364 |
+
value_states = self.v_proj(hidden_states)
|
| 365 |
+
|
| 366 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 367 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 368 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 369 |
+
|
| 370 |
+
kv_seq_len = key_states.shape[-2]
|
| 371 |
+
if past_key_value is not None:
|
| 372 |
+
kv_seq_len += past_key_value[0].shape[-2]
|
| 373 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
| 374 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
| 375 |
+
|
| 376 |
+
if past_key_value is not None:
|
| 377 |
+
# reuse k, v, self_attention
|
| 378 |
+
key_states = torch.cat([past_key_value[0], key_states], dim=2)
|
| 379 |
+
value_states = torch.cat([past_key_value[1], value_states], dim=2)
|
| 380 |
+
|
| 381 |
+
past_key_value = (key_states, value_states) if use_cache else None
|
| 382 |
+
|
| 383 |
+
# repeat k/v heads if n_kv_heads < n_heads
|
| 384 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
| 385 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
| 386 |
+
|
| 387 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
| 388 |
+
|
| 389 |
+
if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
|
| 390 |
+
raise ValueError(
|
| 391 |
+
f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
|
| 392 |
+
f" {attn_weights.size()}"
|
| 393 |
+
)
|
| 394 |
+
|
| 395 |
+
if attention_mask is not None:
|
| 396 |
+
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
| 397 |
+
raise ValueError(
|
| 398 |
+
f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
|
| 399 |
+
)
|
| 400 |
+
attn_weights = attn_weights + attention_mask
|
| 401 |
+
|
| 402 |
+
# upcast attention to fp32
|
| 403 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
| 404 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 405 |
+
|
| 406 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
| 407 |
+
raise ValueError(
|
| 408 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
| 409 |
+
f" {attn_output.size()}"
|
| 410 |
+
)
|
| 411 |
+
|
| 412 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 413 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
| 414 |
+
|
| 415 |
+
if self.config.pretraining_tp > 1:
|
| 416 |
+
attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
|
| 417 |
+
o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
|
| 418 |
+
attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
|
| 419 |
+
else:
|
| 420 |
+
attn_output = self.o_proj(attn_output)
|
| 421 |
+
|
| 422 |
+
if not output_attentions:
|
| 423 |
+
attn_weights = None
|
| 424 |
+
|
| 425 |
+
return attn_output, attn_weights, past_key_value
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
def _flash_forward(
|
| 429 |
+
self,
|
| 430 |
+
hidden_states: torch.Tensor,
|
| 431 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 432 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 433 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
| 434 |
+
output_attentions: bool = False,
|
| 435 |
+
use_cache: bool = False,
|
| 436 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 437 |
+
"""Input shape: Batch x Time x Channel
|
| 438 |
+
|
| 439 |
+
attention_mask: [bsz, q_len]
|
| 440 |
+
"""
|
| 441 |
+
if output_attentions:
|
| 442 |
+
warnings.warn("Output attentions is not supported for patched `LlamaAttention`, returning `None` instead.")
|
| 443 |
+
|
| 444 |
+
bsz, q_len, _ = hidden_states.size()
|
| 445 |
+
|
| 446 |
+
query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 447 |
+
key_states = self.k_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 448 |
+
value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 449 |
+
# [bsz, q_len, nh, hd]
|
| 450 |
+
# [bsz, nh, q_len, hd]
|
| 451 |
+
|
| 452 |
+
kv_seq_len = key_states.shape[-2]
|
| 453 |
+
if past_key_value is not None:
|
| 454 |
+
kv_seq_len += past_key_value[0].shape[-2]
|
| 455 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
| 456 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
| 457 |
+
|
| 458 |
+
# Past Key value support
|
| 459 |
+
if past_key_value is not None:
|
| 460 |
+
# reuse k, v, self_attention
|
| 461 |
+
key_states = torch.cat([past_key_value[0], key_states], dim=2)
|
| 462 |
+
value_states = torch.cat([past_key_value[1], value_states], dim=2)
|
| 463 |
+
|
| 464 |
+
past_key_value = (key_states, value_states) if use_cache else None
|
| 465 |
+
|
| 466 |
+
# PEFT Int4 support
|
| 467 |
+
query_states, key_states, value_states = [x.to(torch.bfloat16) for x in [query_states, key_states, value_states]]
|
| 468 |
+
|
| 469 |
+
assert all(
|
| 470 |
+
(i.dtype in [torch.float16, torch.bfloat16] for i in (query_states, key_states, value_states))
|
| 471 |
+
), "shit not all types"
|
| 472 |
+
|
| 473 |
+
# Flash attention codes from
|
| 474 |
+
# https://github.com/HazyResearch/flash-attention/blob/main/flash_attn/flash_attention.py
|
| 475 |
+
|
| 476 |
+
# transform the data into the format required by flash attention
|
| 477 |
+
qkv = torch.stack([query_states, key_states, value_states], dim=2) # [bsz, nh, 3, q_len, hd]
|
| 478 |
+
qkv = qkv.transpose(1, 3) # [bsz, q_len, 3, nh, hd]
|
| 479 |
+
# We have disabled _prepare_decoder_attention_mask in LlamaModel
|
| 480 |
+
# the attention_mask should be the same as the key_padding_mask
|
| 481 |
+
key_padding_mask = attention_mask
|
| 482 |
+
|
| 483 |
+
if key_padding_mask is None:
|
| 484 |
+
qkv = rearrange(qkv, "b s ... -> (b s) ...")
|
| 485 |
+
max_s = q_len
|
| 486 |
+
cu_q_lens = torch.arange(0, (bsz + 1) * q_len, step=q_len, dtype=torch.int32, device=qkv.device)
|
| 487 |
+
output = flash_attn_varlen_qkvpacked_func(qkv, cu_q_lens, max_s, 0.0, softmax_scale=None, causal=True)
|
| 488 |
+
output = rearrange(output, "(b s) ... -> b s ...", b=bsz)
|
| 489 |
+
else:
|
| 490 |
+
nheads = qkv.shape[-2]
|
| 491 |
+
x = rearrange(qkv, "b s three h d -> b s (three h d)")
|
| 492 |
+
x_unpad, indices, cu_q_lens, max_s = unpad_input(x, key_padding_mask)
|
| 493 |
+
x_unpad = rearrange(x_unpad, "nnz (three h d) -> nnz three h d", three=3, h=nheads)
|
| 494 |
+
output_unpad = flash_attn_varlen_qkvpacked_func(
|
| 495 |
+
x_unpad, cu_q_lens, max_s, 0.0, softmax_scale=None, causal=True
|
| 496 |
+
)
|
| 497 |
+
output = rearrange(
|
| 498 |
+
pad_input(rearrange(output_unpad, "nnz h d -> nnz (h d)"), indices, bsz, q_len),
|
| 499 |
+
"b s (h d) -> b s h d",
|
| 500 |
+
h=nheads,
|
| 501 |
+
)
|
| 502 |
+
return self.o_proj(rearrange(output, "b s h d -> b s (h d)")), None, past_key_value
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
class NGMEDecoderLayer(nn.Module):
|
| 506 |
+
def __init__(self, config: NGMEConfig):
|
| 507 |
+
super().__init__()
|
| 508 |
+
self.hidden_size = config.hidden_size
|
| 509 |
+
self.self_attn = NGMEAttention(config=config)
|
| 510 |
+
self.mlp = NGMEMLP(config)
|
| 511 |
+
self.input_layernorm = NGMERMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 512 |
+
self.post_attention_layernorm = NGMERMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 513 |
+
|
| 514 |
+
def forward(
|
| 515 |
+
self,
|
| 516 |
+
hidden_states: torch.Tensor,
|
| 517 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 518 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 519 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
| 520 |
+
output_attentions: Optional[bool] = False,
|
| 521 |
+
use_cache: Optional[bool] = False,
|
| 522 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
| 523 |
+
"""
|
| 524 |
+
Args:
|
| 525 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 526 |
+
attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
|
| 527 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 528 |
+
output_attentions (`bool`, *optional*):
|
| 529 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 530 |
+
returned tensors for more detail.
|
| 531 |
+
use_cache (`bool`, *optional*):
|
| 532 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
| 533 |
+
(see `past_key_values`).
|
| 534 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
| 535 |
+
"""
|
| 536 |
+
|
| 537 |
+
residual = hidden_states
|
| 538 |
+
|
| 539 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 540 |
+
|
| 541 |
+
# Self Attention
|
| 542 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
| 543 |
+
hidden_states=hidden_states,
|
| 544 |
+
attention_mask=attention_mask,
|
| 545 |
+
position_ids=position_ids,
|
| 546 |
+
past_key_value=past_key_value,
|
| 547 |
+
output_attentions=output_attentions,
|
| 548 |
+
use_cache=use_cache,
|
| 549 |
+
)
|
| 550 |
+
hidden_states = residual + hidden_states
|
| 551 |
+
|
| 552 |
+
# Fully Connected
|
| 553 |
+
residual = hidden_states
|
| 554 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 555 |
+
hidden_states = self.mlp(hidden_states)
|
| 556 |
+
hidden_states = residual + hidden_states
|
| 557 |
+
|
| 558 |
+
outputs = (hidden_states,)
|
| 559 |
+
|
| 560 |
+
if output_attentions:
|
| 561 |
+
outputs += (self_attn_weights,)
|
| 562 |
+
|
| 563 |
+
if use_cache:
|
| 564 |
+
outputs += (present_key_value,)
|
| 565 |
+
|
| 566 |
+
return outputs
|
| 567 |
+
|
| 568 |
+
|
| 569 |
+
class NGMEPreTrainedModel(PreTrainedModel):
|
| 570 |
+
config_class = NGMEConfig
|
| 571 |
+
base_model_prefix = "model"
|
| 572 |
+
supports_gradient_checkpointing = True
|
| 573 |
+
_no_split_modules = ["NGMEDecoderLayer"]
|
| 574 |
+
_skip_keys_device_placement = "past_key_values"
|
| 575 |
+
|
| 576 |
+
def _init_weights(self, module):
|
| 577 |
+
std = self.config.initializer_range
|
| 578 |
+
if isinstance(module, nn.Linear):
|
| 579 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 580 |
+
if module.bias is not None:
|
| 581 |
+
module.bias.data.zero_()
|
| 582 |
+
elif isinstance(module, NGramsEmbedding):
|
| 583 |
+
if self.config.use_small_embedding:
|
| 584 |
+
nn.init.uniform_(module.weight, a=-1e-4, b=1e-4)
|
| 585 |
+
else:
|
| 586 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 587 |
+
if module.padding_idx is not None:
|
| 588 |
+
module.weight.data[module.padding_idx].zero_()
|
| 589 |
+
|
| 590 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
| 591 |
+
if isinstance(module, NGMEModel):
|
| 592 |
+
module.gradient_checkpointing = value
|
| 593 |
+
|
| 594 |
+
|
| 595 |
+
class NGMEModel(NGMEPreTrainedModel):
|
| 596 |
+
"""
|
| 597 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`NGMEDecoderLayer`]
|
| 598 |
+
|
| 599 |
+
Args:
|
| 600 |
+
config: NGMEConfig
|
| 601 |
+
"""
|
| 602 |
+
|
| 603 |
+
def __init__(self, config: NGMEConfig):
|
| 604 |
+
super().__init__(config)
|
| 605 |
+
self.padding_idx = config.pad_token_id
|
| 606 |
+
self.vocab_size = config.vocab_size
|
| 607 |
+
|
| 608 |
+
self.embed_tokens = NGramsEmbedding(config.vocab_size, config.hidden_size, self.padding_idx, unk_idx=config.unk_idx)
|
| 609 |
+
|
| 610 |
+
if self.config.use_small_embedding:
|
| 611 |
+
self.embed_layer_norm = nn.LayerNorm(config.hidden_size)
|
| 612 |
+
|
| 613 |
+
self.layers = nn.ModuleList([NGMEDecoderLayer(config) for _ in range(config.num_hidden_layers)])
|
| 614 |
+
self.norm = NGMERMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 615 |
+
|
| 616 |
+
self.gradient_checkpointing = False
|
| 617 |
+
# Initialize weights and apply final processing
|
| 618 |
+
self.post_init()
|
| 619 |
+
|
| 620 |
+
def get_input_embeddings(self):
|
| 621 |
+
return self.embed_tokens
|
| 622 |
+
|
| 623 |
+
def set_input_embeddings(self, value):
|
| 624 |
+
self.embed_tokens = value
|
| 625 |
+
|
| 626 |
+
# Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
|
| 627 |
+
def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
|
| 628 |
+
|
| 629 |
+
if self.config.use_flash_attn:
|
| 630 |
+
return attention_mask
|
| 631 |
+
|
| 632 |
+
# create causal mask
|
| 633 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
| 634 |
+
combined_attention_mask = None
|
| 635 |
+
if input_shape[-1] > 1:
|
| 636 |
+
combined_attention_mask = _make_causal_mask(
|
| 637 |
+
input_shape,
|
| 638 |
+
inputs_embeds.dtype,
|
| 639 |
+
device=inputs_embeds.device,
|
| 640 |
+
past_key_values_length=past_key_values_length,
|
| 641 |
+
)
|
| 642 |
+
|
| 643 |
+
if attention_mask is not None:
|
| 644 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
| 645 |
+
expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
|
| 646 |
+
inputs_embeds.device
|
| 647 |
+
)
|
| 648 |
+
combined_attention_mask = (
|
| 649 |
+
expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
|
| 650 |
+
)
|
| 651 |
+
|
| 652 |
+
return combined_attention_mask
|
| 653 |
+
|
| 654 |
+
def forward(
|
| 655 |
+
self,
|
| 656 |
+
input_ids: torch.LongTensor = None,
|
| 657 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 658 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 659 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 660 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 661 |
+
use_cache: Optional[bool] = None,
|
| 662 |
+
output_attentions: Optional[bool] = None,
|
| 663 |
+
output_hidden_states: Optional[bool] = None,
|
| 664 |
+
return_dict: Optional[bool] = None,
|
| 665 |
+
ngram_sequences: List[torch.Tensor] = []
|
| 666 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
| 667 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 668 |
+
output_hidden_states = (
|
| 669 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 670 |
+
)
|
| 671 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 672 |
+
|
| 673 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 674 |
+
|
| 675 |
+
# retrieve input_ids and inputs_embeds
|
| 676 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 677 |
+
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
|
| 678 |
+
elif input_ids is not None:
|
| 679 |
+
batch_size, seq_length = input_ids.shape
|
| 680 |
+
elif inputs_embeds is not None:
|
| 681 |
+
batch_size, seq_length, _ = inputs_embeds.shape
|
| 682 |
+
else:
|
| 683 |
+
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
|
| 684 |
+
|
| 685 |
+
seq_length_with_past = seq_length
|
| 686 |
+
past_key_values_length = 0
|
| 687 |
+
|
| 688 |
+
if past_key_values is not None:
|
| 689 |
+
past_key_values_length = past_key_values[0][0].shape[2]
|
| 690 |
+
seq_length_with_past = seq_length_with_past + past_key_values_length
|
| 691 |
+
|
| 692 |
+
if position_ids is None:
|
| 693 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
| 694 |
+
position_ids = torch.arange(
|
| 695 |
+
past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
|
| 696 |
+
)
|
| 697 |
+
position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
|
| 698 |
+
else:
|
| 699 |
+
position_ids = position_ids.view(-1, seq_length).long()
|
| 700 |
+
|
| 701 |
+
if inputs_embeds is None:
|
| 702 |
+
inputs_embeds = self.embed_tokens(input_ids, ngram_sequences)
|
| 703 |
+
|
| 704 |
+
if self.config.use_small_embedding:
|
| 705 |
+
inputs_embeds = self.embed_layer_norm(inputs_embeds)
|
| 706 |
+
|
| 707 |
+
# embed positions
|
| 708 |
+
if attention_mask is None:
|
| 709 |
+
attention_mask = torch.ones(
|
| 710 |
+
(batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
|
| 711 |
+
)
|
| 712 |
+
attention_mask = self._prepare_decoder_attention_mask(
|
| 713 |
+
attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
|
| 714 |
+
)
|
| 715 |
+
|
| 716 |
+
hidden_states = inputs_embeds
|
| 717 |
+
|
| 718 |
+
if self.gradient_checkpointing and self.training:
|
| 719 |
+
if use_cache:
|
| 720 |
+
logger.warning_once(
|
| 721 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
| 722 |
+
)
|
| 723 |
+
use_cache = False
|
| 724 |
+
|
| 725 |
+
# decoder layers
|
| 726 |
+
all_hidden_states = () if output_hidden_states else None
|
| 727 |
+
all_self_attns = () if output_attentions else None
|
| 728 |
+
next_decoder_cache = () if use_cache else None
|
| 729 |
+
|
| 730 |
+
for idx, decoder_layer in enumerate(self.layers):
|
| 731 |
+
if output_hidden_states:
|
| 732 |
+
all_hidden_states += (hidden_states,)
|
| 733 |
+
|
| 734 |
+
past_key_value = past_key_values[idx] if past_key_values is not None else None
|
| 735 |
+
|
| 736 |
+
if self.gradient_checkpointing and self.training:
|
| 737 |
+
|
| 738 |
+
def create_custom_forward(module):
|
| 739 |
+
def custom_forward(*inputs):
|
| 740 |
+
# None for past_key_value
|
| 741 |
+
return module(*inputs, output_attentions, None)
|
| 742 |
+
|
| 743 |
+
return custom_forward
|
| 744 |
+
|
| 745 |
+
layer_outputs = torch.utils.checkpoint.checkpoint(
|
| 746 |
+
create_custom_forward(decoder_layer),
|
| 747 |
+
hidden_states,
|
| 748 |
+
attention_mask,
|
| 749 |
+
position_ids,
|
| 750 |
+
None,
|
| 751 |
+
)
|
| 752 |
+
else:
|
| 753 |
+
layer_outputs = decoder_layer(
|
| 754 |
+
hidden_states,
|
| 755 |
+
attention_mask=attention_mask,
|
| 756 |
+
position_ids=position_ids,
|
| 757 |
+
past_key_value=past_key_value,
|
| 758 |
+
output_attentions=output_attentions,
|
| 759 |
+
use_cache=use_cache,
|
| 760 |
+
)
|
| 761 |
+
|
| 762 |
+
hidden_states = layer_outputs[0]
|
| 763 |
+
|
| 764 |
+
if use_cache:
|
| 765 |
+
next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
|
| 766 |
+
|
| 767 |
+
if output_attentions:
|
| 768 |
+
all_self_attns += (layer_outputs[1],)
|
| 769 |
+
|
| 770 |
+
hidden_states = self.norm(hidden_states)
|
| 771 |
+
|
| 772 |
+
# add hidden states from the last decoder layer
|
| 773 |
+
if output_hidden_states:
|
| 774 |
+
all_hidden_states += (hidden_states,)
|
| 775 |
+
|
| 776 |
+
next_cache = next_decoder_cache if use_cache else None
|
| 777 |
+
if not return_dict:
|
| 778 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
| 779 |
+
return BaseModelOutputWithPast(
|
| 780 |
+
last_hidden_state=hidden_states,
|
| 781 |
+
past_key_values=next_cache,
|
| 782 |
+
hidden_states=all_hidden_states,
|
| 783 |
+
attentions=all_self_attns,
|
| 784 |
+
)
|
| 785 |
+
|
| 786 |
+
|
| 787 |
+
class NGMEForCausalLM(NGMEPreTrainedModel):
|
| 788 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 789 |
+
|
| 790 |
+
def __init__(self, config):
|
| 791 |
+
super().__init__(config)
|
| 792 |
+
self.model = NGMEModel(config)
|
| 793 |
+
self.vocab_size = config.vocab_size
|
| 794 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 795 |
+
|
| 796 |
+
self.tokenizer: Optional[NGMETokenizer] = None
|
| 797 |
+
weight = torch.ones(config.vocab_size)
|
| 798 |
+
weight[config.unk_idx] = 0
|
| 799 |
+
self.loss_fct = CrossEntropyLoss(weight=weight)
|
| 800 |
+
|
| 801 |
+
# Initialize weights and apply final processing
|
| 802 |
+
self.post_init()
|
| 803 |
+
|
| 804 |
+
def get_input_embeddings(self):
|
| 805 |
+
return self.model.embed_tokens
|
| 806 |
+
|
| 807 |
+
def set_input_embeddings(self, value):
|
| 808 |
+
self.model.embed_tokens = value
|
| 809 |
+
|
| 810 |
+
def get_output_embeddings(self):
|
| 811 |
+
return self.lm_head
|
| 812 |
+
|
| 813 |
+
def set_output_embeddings(self, new_embeddings):
|
| 814 |
+
self.lm_head = new_embeddings
|
| 815 |
+
|
| 816 |
+
def set_decoder(self, decoder):
|
| 817 |
+
self.model = decoder
|
| 818 |
+
|
| 819 |
+
def get_decoder(self):
|
| 820 |
+
return self.model
|
| 821 |
+
|
| 822 |
+
def _collect_ngram_labels(self,
|
| 823 |
+
unigram_labels: torch.LongTensor,
|
| 824 |
+
label_gram_2_sequence: Optional[torch.LongTensor] = None,
|
| 825 |
+
label_gram_3_sequence: Optional[torch.LongTensor] = None,
|
| 826 |
+
label_gram_4_sequence: Optional[torch.LongTensor] = None,
|
| 827 |
+
label_target_gram_2_sequence: Optional[torch.LongTensor] = None,
|
| 828 |
+
label_target_gram_3_sequence: Optional[torch.LongTensor] = None,
|
| 829 |
+
label_target_gram_4_sequence: Optional[torch.LongTensor] = None
|
| 830 |
+
):
|
| 831 |
+
|
| 832 |
+
ngram_labels = [unigram_labels[..., 1:].contiguous()]
|
| 833 |
+
|
| 834 |
+
if label_gram_2_sequence is not None:
|
| 835 |
+
if label_target_gram_2_sequence is not None:
|
| 836 |
+
two_gram_labels = label_target_gram_2_sequence[..., 1:].contiguous()
|
| 837 |
+
else:
|
| 838 |
+
two_gram_labels = shift_with_pad(label_gram_2_sequence, 2, unigram_labels)
|
| 839 |
+
ngram_labels.append(two_gram_labels)
|
| 840 |
+
|
| 841 |
+
if label_gram_3_sequence is not None:
|
| 842 |
+
if label_target_gram_3_sequence is not None:
|
| 843 |
+
three_gram_labels = label_target_gram_3_sequence[..., 1:].contiguous()
|
| 844 |
+
else:
|
| 845 |
+
three_gram_labels = shift_with_pad(label_gram_3_sequence, 3, unigram_labels)
|
| 846 |
+
ngram_labels.append(three_gram_labels)
|
| 847 |
+
|
| 848 |
+
if label_gram_4_sequence is not None:
|
| 849 |
+
if label_target_gram_4_sequence is not None:
|
| 850 |
+
four_gram_labels = label_target_gram_4_sequence[..., 1:].contiguous()
|
| 851 |
+
else:
|
| 852 |
+
four_gram_labels = shift_with_pad(label_gram_4_sequence, 4, unigram_labels)
|
| 853 |
+
ngram_labels.append(four_gram_labels)
|
| 854 |
+
|
| 855 |
+
return ngram_labels
|
| 856 |
+
|
| 857 |
+
|
| 858 |
+
def forward(
|
| 859 |
+
self,
|
| 860 |
+
input_ids: torch.LongTensor = None,
|
| 861 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 862 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 863 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 864 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 865 |
+
labels: Optional[torch.LongTensor] = None,
|
| 866 |
+
use_cache: Optional[bool] = None,
|
| 867 |
+
output_attentions: Optional[bool] = None,
|
| 868 |
+
output_hidden_states: Optional[bool] = None,
|
| 869 |
+
return_dict: Optional[bool] = None,
|
| 870 |
+
label_gram_2_sequence: Optional[torch.LongTensor] = None,
|
| 871 |
+
label_gram_3_sequence: Optional[torch.LongTensor] = None,
|
| 872 |
+
label_gram_4_sequence: Optional[torch.LongTensor] = None,
|
| 873 |
+
label_target_gram_2_sequence: Optional[torch.LongTensor] = None,
|
| 874 |
+
label_target_gram_3_sequence: Optional[torch.LongTensor] = None,
|
| 875 |
+
label_target_gram_4_sequence: Optional[torch.LongTensor] = None,
|
| 876 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
| 877 |
+
|
| 878 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 879 |
+
output_hidden_states = (
|
| 880 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 881 |
+
)
|
| 882 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 883 |
+
|
| 884 |
+
ngram_sequences = collect_n_gram_sequences(
|
| 885 |
+
gram_2_sequence=label_gram_2_sequence,
|
| 886 |
+
gram_3_sequence=label_gram_3_sequence,
|
| 887 |
+
gram_4_sequence=label_gram_4_sequence,
|
| 888 |
+
)
|
| 889 |
+
|
| 890 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
| 891 |
+
outputs = self.model(
|
| 892 |
+
input_ids=input_ids,
|
| 893 |
+
attention_mask=attention_mask,
|
| 894 |
+
position_ids=position_ids,
|
| 895 |
+
past_key_values=past_key_values,
|
| 896 |
+
inputs_embeds=inputs_embeds,
|
| 897 |
+
use_cache=use_cache,
|
| 898 |
+
output_attentions=output_attentions,
|
| 899 |
+
output_hidden_states=output_hidden_states,
|
| 900 |
+
return_dict=return_dict,
|
| 901 |
+
ngram_sequences=ngram_sequences
|
| 902 |
+
)
|
| 903 |
+
|
| 904 |
+
hidden_states = outputs[0]
|
| 905 |
+
if self.config.pretraining_tp > 1:
|
| 906 |
+
lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
|
| 907 |
+
logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
|
| 908 |
+
logits = torch.cat(logits, dim=-1)
|
| 909 |
+
else:
|
| 910 |
+
logits = self.lm_head(hidden_states)
|
| 911 |
+
|
| 912 |
+
logits = logits.float()
|
| 913 |
+
|
| 914 |
+
loss = None
|
| 915 |
+
if labels is not None:
|
| 916 |
+
# Shift so that tokens < n predict n
|
| 917 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
| 918 |
+
|
| 919 |
+
ngram_labels = self._collect_ngram_labels(
|
| 920 |
+
unigram_labels=labels,
|
| 921 |
+
label_gram_2_sequence=label_gram_2_sequence,
|
| 922 |
+
label_gram_3_sequence=label_gram_3_sequence,
|
| 923 |
+
label_gram_4_sequence=label_gram_4_sequence,
|
| 924 |
+
label_target_gram_2_sequence=label_target_gram_2_sequence,
|
| 925 |
+
label_target_gram_3_sequence=label_target_gram_3_sequence,
|
| 926 |
+
label_target_gram_4_sequence=label_target_gram_4_sequence,
|
| 927 |
+
)
|
| 928 |
+
|
| 929 |
+
shift_labels = torch.stack(ngram_labels, dim=0)
|
| 930 |
+
shift_labels = soft_n_hot(shift_labels, self.config.vocab_size, strategy="exp")
|
| 931 |
+
|
| 932 |
+
# Flatten the tokens
|
| 933 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
| 934 |
+
shift_labels = shift_labels.view(-1, shift_labels.size(-1))
|
| 935 |
+
# Enable model parallelism
|
| 936 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
| 937 |
+
loss = self.loss_fct(shift_logits, shift_labels)
|
| 938 |
+
|
| 939 |
+
if not return_dict:
|
| 940 |
+
output = (logits,) + outputs[1:]
|
| 941 |
+
return (loss,) + output if loss is not None else output
|
| 942 |
+
|
| 943 |
+
return CausalLMOutputWithPast(
|
| 944 |
+
loss=loss,
|
| 945 |
+
logits=logits,
|
| 946 |
+
past_key_values=outputs.past_key_values,
|
| 947 |
+
hidden_states=outputs.hidden_states,
|
| 948 |
+
attentions=outputs.attentions,
|
| 949 |
+
)
|
| 950 |
+
|
| 951 |
+
def prepare_inputs_for_generation(
|
| 952 |
+
self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
|
| 953 |
+
):
|
| 954 |
+
if past_key_values:
|
| 955 |
+
input_ids = input_ids[:, -1:]
|
| 956 |
+
|
| 957 |
+
position_ids = kwargs.get("position_ids", None)
|
| 958 |
+
if attention_mask is not None and position_ids is None:
|
| 959 |
+
# create position_ids on the fly for batch generation
|
| 960 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
| 961 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
| 962 |
+
if past_key_values:
|
| 963 |
+
position_ids = position_ids[:, -1].unsqueeze(-1)
|
| 964 |
+
|
| 965 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
| 966 |
+
if inputs_embeds is not None and past_key_values is None:
|
| 967 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
| 968 |
+
else:
|
| 969 |
+
model_inputs = {"input_ids": input_ids}
|
| 970 |
+
|
| 971 |
+
model_inputs.update(
|
| 972 |
+
{
|
| 973 |
+
"position_ids": position_ids,
|
| 974 |
+
"past_key_values": past_key_values,
|
| 975 |
+
"use_cache": kwargs.get("use_cache"),
|
| 976 |
+
"attention_mask": attention_mask,
|
| 977 |
+
}
|
| 978 |
+
)
|
| 979 |
+
return model_inputs
|
| 980 |
+
|
| 981 |
+
@staticmethod
|
| 982 |
+
def _reorder_cache(past_key_values, beam_idx):
|
| 983 |
+
reordered_past = ()
|
| 984 |
+
for layer_past in past_key_values:
|
| 985 |
+
reordered_past += (
|
| 986 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
|
| 987 |
+
)
|
| 988 |
+
return reordered_past
|
| 989 |
+
|
| 990 |
+
def sample(self, input_ids: torch.LongTensor, logits_processor: Optional[LogitsProcessorList] = None, stopping_criteria: Optional[StoppingCriteriaList] = None, logits_warper: Optional[LogitsProcessorList] = None, max_length: Optional[int] = None, pad_token_id: Optional[int] = None, eos_token_id: Optional[Union[int, List[int]]] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, output_scores: Optional[bool] = None, return_dict_in_generate: Optional[bool] = None, synced_gpus: bool = False, streamer = None, **model_kwargs) -> Union[SampleOutput, torch.LongTensor]:
|
| 991 |
+
if not hasattr(self, "tokenizer"):
|
| 992 |
+
raise ValueError(
|
| 993 |
+
"You are trying to sample from a model that does not have a tokenizer."
|
| 994 |
+
"Add a tokenizer as an attribute of your model (either manually or automatically)."
|
| 995 |
+
)
|
| 996 |
+
|
| 997 |
+
return sample_ngme(self, input_ids, logits_processor=logits_processor, stopping_criteria=stopping_criteria, logits_warper=logits_warper, max_length=max_length, pad_token_id=pad_token_id, eos_token_id=eos_token_id, output_attentions=output_attentions, output_hidden_states=output_hidden_states, output_scores=output_scores, return_dict_in_generate=return_dict_in_generate, synced_gpus=synced_gpus, streamer=streamer, **model_kwargs)
|
| 998 |
+
|
| 999 |
+
|
| 1000 |
+
class NGMEForSequenceClassification(NGMEPreTrainedModel):
|
| 1001 |
+
def __init__(self, config):
|
| 1002 |
+
super().__init__(config)
|
| 1003 |
+
self.num_labels = config.num_labels
|
| 1004 |
+
self.model = NGMEModel(config)
|
| 1005 |
+
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
|
| 1006 |
+
|
| 1007 |
+
# Initialize weights and apply final processing
|
| 1008 |
+
self.post_init()
|
| 1009 |
+
|
| 1010 |
+
def get_input_embeddings(self):
|
| 1011 |
+
return self.model.embed_tokens
|
| 1012 |
+
|
| 1013 |
+
def set_input_embeddings(self, value):
|
| 1014 |
+
self.model.embed_tokens = value
|
| 1015 |
+
|
| 1016 |
+
def forward(
|
| 1017 |
+
self,
|
| 1018 |
+
input_ids: torch.LongTensor = None,
|
| 1019 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1020 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1021 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 1022 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1023 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1024 |
+
use_cache: Optional[bool] = None,
|
| 1025 |
+
output_attentions: Optional[bool] = None,
|
| 1026 |
+
output_hidden_states: Optional[bool] = None,
|
| 1027 |
+
return_dict: Optional[bool] = None,
|
| 1028 |
+
label_gram_2_sequence: Optional[torch.LongTensor] = None,
|
| 1029 |
+
label_gram_3_sequence: Optional[torch.LongTensor] = None,
|
| 1030 |
+
label_gram_4_sequence: Optional[torch.LongTensor] = None,
|
| 1031 |
+
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
| 1032 |
+
r"""
|
| 1033 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1034 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
| 1035 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 1036 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 1037 |
+
"""
|
| 1038 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1039 |
+
|
| 1040 |
+
ngram_sequences = collect_n_gram_sequences(
|
| 1041 |
+
gram_2_sequence=label_gram_2_sequence,
|
| 1042 |
+
gram_3_sequence=label_gram_3_sequence,
|
| 1043 |
+
gram_4_sequence=label_gram_4_sequence,
|
| 1044 |
+
)
|
| 1045 |
+
|
| 1046 |
+
transformer_outputs = self.model(
|
| 1047 |
+
input_ids,
|
| 1048 |
+
attention_mask=attention_mask,
|
| 1049 |
+
position_ids=position_ids,
|
| 1050 |
+
past_key_values=past_key_values,
|
| 1051 |
+
inputs_embeds=inputs_embeds,
|
| 1052 |
+
use_cache=use_cache,
|
| 1053 |
+
output_attentions=output_attentions,
|
| 1054 |
+
output_hidden_states=output_hidden_states,
|
| 1055 |
+
return_dict=return_dict,
|
| 1056 |
+
ngram_sequences=ngram_sequences
|
| 1057 |
+
)
|
| 1058 |
+
hidden_states = transformer_outputs[0]
|
| 1059 |
+
logits = self.score(hidden_states)
|
| 1060 |
+
|
| 1061 |
+
if input_ids is not None:
|
| 1062 |
+
batch_size = input_ids.shape[0]
|
| 1063 |
+
else:
|
| 1064 |
+
batch_size = inputs_embeds.shape[0]
|
| 1065 |
+
|
| 1066 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
| 1067 |
+
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
|
| 1068 |
+
if self.config.pad_token_id is None:
|
| 1069 |
+
sequence_lengths = -1
|
| 1070 |
+
else:
|
| 1071 |
+
if input_ids is not None:
|
| 1072 |
+
sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).long().argmax(-1) - 1).to(
|
| 1073 |
+
logits.device
|
| 1074 |
+
)
|
| 1075 |
+
else:
|
| 1076 |
+
sequence_lengths = -1
|
| 1077 |
+
|
| 1078 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
|
| 1079 |
+
|
| 1080 |
+
loss = None
|
| 1081 |
+
|
| 1082 |
+
if labels is not None:
|
| 1083 |
+
labels = labels.to(logits.device)
|
| 1084 |
+
if self.config.problem_type is None:
|
| 1085 |
+
if self.num_labels == 1:
|
| 1086 |
+
self.config.problem_type = "regression"
|
| 1087 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 1088 |
+
self.config.problem_type = "single_label_classification"
|
| 1089 |
+
else:
|
| 1090 |
+
self.config.problem_type = "multi_label_classification"
|
| 1091 |
+
|
| 1092 |
+
if self.config.problem_type == "regression":
|
| 1093 |
+
loss_fct = MSELoss()
|
| 1094 |
+
if self.num_labels == 1:
|
| 1095 |
+
loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
|
| 1096 |
+
else:
|
| 1097 |
+
loss = loss_fct(pooled_logits, labels)
|
| 1098 |
+
elif self.config.problem_type == "single_label_classification":
|
| 1099 |
+
loss_fct = CrossEntropyLoss()
|
| 1100 |
+
loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
|
| 1101 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 1102 |
+
loss_fct = BCEWithLogitsLoss()
|
| 1103 |
+
loss = loss_fct(pooled_logits, labels)
|
| 1104 |
+
if not return_dict:
|
| 1105 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
| 1106 |
+
return ((loss,) + output) if loss is not None else output
|
| 1107 |
+
|
| 1108 |
+
return SequenceClassifierOutputWithPast(
|
| 1109 |
+
loss=loss,
|
| 1110 |
+
logits=pooled_logits,
|
| 1111 |
+
past_key_values=transformer_outputs.past_key_values,
|
| 1112 |
+
hidden_states=transformer_outputs.hidden_states,
|
| 1113 |
+
attentions=transformer_outputs.attentions,
|
| 1114 |
+
)
|
pytorch_model.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ed7ad7139c105552780804f22420162ed698f8db3b29854dfaf0979b3fcdab51
|
| 3 |
+
size 907246313
|
sampling.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import warnings
|
| 2 |
+
from typing import List, Optional, Union
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.distributed as dist
|
| 6 |
+
from torch import nn
|
| 7 |
+
from transformers import BatchEncoding
|
| 8 |
+
from transformers.generation.logits_process import (
|
| 9 |
+
LogitsProcessorList,
|
| 10 |
+
)
|
| 11 |
+
from transformers.generation.stopping_criteria import (
|
| 12 |
+
StoppingCriteriaList,
|
| 13 |
+
validate_stopping_criteria,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
from transformers.generation.utils import SampleOutput, SampleEncoderDecoderOutput, SampleDecoderOnlyOutput
|
| 17 |
+
|
| 18 |
+
def sample(
|
| 19 |
+
self,
|
| 20 |
+
input_ids: torch.LongTensor,
|
| 21 |
+
logits_processor: Optional[LogitsProcessorList] = None,
|
| 22 |
+
stopping_criteria: Optional[StoppingCriteriaList] = None,
|
| 23 |
+
logits_warper: Optional[LogitsProcessorList] = None,
|
| 24 |
+
max_length: Optional[int] = None,
|
| 25 |
+
pad_token_id: Optional[int] = None,
|
| 26 |
+
eos_token_id: Optional[Union[int, List[int]]] = None,
|
| 27 |
+
output_attentions: Optional[bool] = None,
|
| 28 |
+
output_hidden_states: Optional[bool] = None,
|
| 29 |
+
output_scores: Optional[bool] = None,
|
| 30 |
+
return_dict_in_generate: Optional[bool] = None,
|
| 31 |
+
synced_gpus: Optional[bool] = False,
|
| 32 |
+
**model_kwargs,
|
| 33 |
+
) -> Union[SampleOutput, torch.LongTensor]:
|
| 34 |
+
|
| 35 |
+
if type(input_ids) in [dict, BatchEncoding]:
|
| 36 |
+
input_ids, ngram_sequences = input_ids["input_ids"], input_ids
|
| 37 |
+
del ngram_sequences["input_ids"]
|
| 38 |
+
del ngram_sequences["attention_mask"]
|
| 39 |
+
else:
|
| 40 |
+
ngram_sequences = {}
|
| 41 |
+
|
| 42 |
+
# init values
|
| 43 |
+
logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()
|
| 44 |
+
stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()
|
| 45 |
+
if max_length is not None:
|
| 46 |
+
warnings.warn(
|
| 47 |
+
"`max_length` is deprecated in this function, use"
|
| 48 |
+
" `stopping_criteria=StoppingCriteriaList(MaxLengthCriteria(max_length=max_length))` instead.",
|
| 49 |
+
UserWarning,
|
| 50 |
+
)
|
| 51 |
+
stopping_criteria = validate_stopping_criteria(stopping_criteria, max_length)
|
| 52 |
+
logits_warper = logits_warper if logits_warper is not None else LogitsProcessorList()
|
| 53 |
+
pad_token_id = pad_token_id if pad_token_id is not None else self.generation_config.pad_token_id
|
| 54 |
+
eos_token_id = eos_token_id if eos_token_id is not None else self.generation_config.eos_token_id
|
| 55 |
+
if isinstance(eos_token_id, int):
|
| 56 |
+
eos_token_id = [eos_token_id]
|
| 57 |
+
|
| 58 |
+
eos_token_id_tensor = torch.tensor(eos_token_id).to(input_ids.device) if eos_token_id is not None else None
|
| 59 |
+
output_scores = output_scores if output_scores is not None else self.generation_config.output_scores
|
| 60 |
+
output_attentions = (
|
| 61 |
+
output_attentions if output_attentions is not None else self.generation_config.output_attentions
|
| 62 |
+
)
|
| 63 |
+
output_hidden_states = (
|
| 64 |
+
output_hidden_states if output_hidden_states is not None else self.generation_config.output_hidden_states
|
| 65 |
+
)
|
| 66 |
+
return_dict_in_generate = (
|
| 67 |
+
return_dict_in_generate
|
| 68 |
+
if return_dict_in_generate is not None
|
| 69 |
+
else self.generation_config.return_dict_in_generate
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
# init attention / hidden states / scores tuples
|
| 73 |
+
scores = () if (return_dict_in_generate and output_scores) else None
|
| 74 |
+
decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
|
| 75 |
+
cross_attentions = () if (return_dict_in_generate and output_attentions) else None
|
| 76 |
+
decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None
|
| 77 |
+
|
| 78 |
+
# if model is an encoder-decoder, retrieve encoder attention weights and hidden states
|
| 79 |
+
if return_dict_in_generate and self.config.is_encoder_decoder:
|
| 80 |
+
encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
|
| 81 |
+
encoder_hidden_states = (
|
| 82 |
+
model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
# keep track of which sequences are already finished
|
| 86 |
+
unfinished_sequences = torch.ones(input_ids.shape[0], dtype=torch.long, device=input_ids.device)
|
| 87 |
+
|
| 88 |
+
this_peer_finished = False # used by synced_gpus only
|
| 89 |
+
# auto-regressive generation
|
| 90 |
+
while True:
|
| 91 |
+
if synced_gpus:
|
| 92 |
+
# Under synced_gpus the `forward` call must continue until all gpus complete their sequence.
|
| 93 |
+
# The following logic allows an early break if all peers finished generating their sequence
|
| 94 |
+
this_peer_finished_flag = torch.tensor(0.0 if this_peer_finished else 1.0).to(input_ids.device)
|
| 95 |
+
# send 0.0 if we finished, 1.0 otherwise
|
| 96 |
+
dist.all_reduce(this_peer_finished_flag, op=dist.ReduceOp.SUM)
|
| 97 |
+
# did all peers finish? the reduced sum will be 0.0 then
|
| 98 |
+
if this_peer_finished_flag.item() == 0.0:
|
| 99 |
+
break
|
| 100 |
+
|
| 101 |
+
# prepare model inputs
|
| 102 |
+
model_inputs = {"input_ids": input_ids}
|
| 103 |
+
|
| 104 |
+
# forward pass to get next token
|
| 105 |
+
outputs = self(
|
| 106 |
+
**model_inputs,
|
| 107 |
+
return_dict=True,
|
| 108 |
+
output_attentions=output_attentions,
|
| 109 |
+
output_hidden_states=output_hidden_states,
|
| 110 |
+
**ngram_sequences
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
if synced_gpus and this_peer_finished:
|
| 114 |
+
continue # don't waste resources running the code we don't need
|
| 115 |
+
|
| 116 |
+
next_token_logits = outputs.logits[:, -1, :]
|
| 117 |
+
|
| 118 |
+
# pre-process distribution
|
| 119 |
+
next_token_scores = logits_processor(input_ids, next_token_logits)
|
| 120 |
+
next_token_scores = logits_warper(input_ids, next_token_scores)
|
| 121 |
+
|
| 122 |
+
# Store scores, attentions and hidden_states when required
|
| 123 |
+
if return_dict_in_generate:
|
| 124 |
+
if output_scores:
|
| 125 |
+
scores += (next_token_scores,)
|
| 126 |
+
if output_attentions:
|
| 127 |
+
decoder_attentions += (
|
| 128 |
+
(outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)
|
| 129 |
+
)
|
| 130 |
+
if self.config.is_encoder_decoder:
|
| 131 |
+
cross_attentions += (outputs.cross_attentions,)
|
| 132 |
+
|
| 133 |
+
if output_hidden_states:
|
| 134 |
+
decoder_hidden_states += (
|
| 135 |
+
(outputs.decoder_hidden_states,)
|
| 136 |
+
if self.config.is_encoder_decoder
|
| 137 |
+
else (outputs.hidden_states,)
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
# sample
|
| 141 |
+
probs = nn.functional.softmax(next_token_scores, dim=-1)
|
| 142 |
+
next_tokens = torch.multinomial(probs, num_samples=1).squeeze(1)
|
| 143 |
+
|
| 144 |
+
# finished sentences should have their next token be a padding token
|
| 145 |
+
if eos_token_id is not None:
|
| 146 |
+
if pad_token_id is None:
|
| 147 |
+
raise ValueError("If `eos_token_id` is defined, make sure that `pad_token_id` is defined.")
|
| 148 |
+
next_tokens = next_tokens * unfinished_sequences + pad_token_id * (1 - unfinished_sequences)
|
| 149 |
+
|
| 150 |
+
# update generated ids, model inputs, and length for next step
|
| 151 |
+
input_ids = torch.cat([input_ids, next_tokens[:, None]], dim=-1)
|
| 152 |
+
decoded = self.tokenizer.batch_decode(input_ids)[0]
|
| 153 |
+
encoded = self.tokenizer(
|
| 154 |
+
decoded, return_tensors="pt", return_ngram_sequences=True
|
| 155 |
+
)
|
| 156 |
+
input_ids = encoded.input_ids.to(self.device)
|
| 157 |
+
|
| 158 |
+
ngram_sequences = {}
|
| 159 |
+
|
| 160 |
+
if "label_gram_2_sequence" in encoded:
|
| 161 |
+
ngram_sequences["label_gram_2_sequence"] = encoded["label_gram_2_sequence"].to(self.device)
|
| 162 |
+
|
| 163 |
+
if "label_gram_3_sequence" in encoded:
|
| 164 |
+
ngram_sequences["label_gram_3_sequence"] = encoded["label_gram_3_sequence"].to(self.device)
|
| 165 |
+
|
| 166 |
+
if "label_gram_4_sequence" in encoded:
|
| 167 |
+
ngram_sequences["label_gram_4_sequence"] = encoded["label_gram_4_sequence"].to(self.device)
|
| 168 |
+
|
| 169 |
+
model_kwargs = self._update_model_kwargs_for_generation(
|
| 170 |
+
outputs, model_kwargs, is_encoder_decoder=self.config.is_encoder_decoder
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
# if eos_token was found in one sentence, set sentence to finished
|
| 174 |
+
if eos_token_id_tensor is not None:
|
| 175 |
+
unfinished_sequences = unfinished_sequences.mul(
|
| 176 |
+
next_tokens.tile(eos_token_id_tensor.shape[0], 1).ne(eos_token_id_tensor.unsqueeze(1)).prod(dim=0)
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
# stop when each sentence is finished, or if we exceed the maximum length
|
| 180 |
+
if unfinished_sequences.max() == 0 or stopping_criteria(input_ids, scores):
|
| 181 |
+
if not synced_gpus:
|
| 182 |
+
break
|
| 183 |
+
else:
|
| 184 |
+
this_peer_finished = True
|
| 185 |
+
|
| 186 |
+
if return_dict_in_generate:
|
| 187 |
+
if self.config.is_encoder_decoder:
|
| 188 |
+
return SampleEncoderDecoderOutput(
|
| 189 |
+
sequences=input_ids,
|
| 190 |
+
scores=scores,
|
| 191 |
+
encoder_attentions=encoder_attentions,
|
| 192 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 193 |
+
decoder_attentions=decoder_attentions,
|
| 194 |
+
cross_attentions=cross_attentions,
|
| 195 |
+
decoder_hidden_states=decoder_hidden_states,
|
| 196 |
+
)
|
| 197 |
+
else:
|
| 198 |
+
return SampleDecoderOnlyOutput(
|
| 199 |
+
sequences=input_ids,
|
| 200 |
+
scores=scores,
|
| 201 |
+
attentions=decoder_attentions,
|
| 202 |
+
hidden_states=decoder_hidden_states,
|
| 203 |
+
)
|
| 204 |
+
else:
|
| 205 |
+
return input_ids
|
tokenization_ngme.py
ADDED
|
@@ -0,0 +1,1250 @@
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import unittest
|
| 3 |
+
import os
|
| 4 |
+
from collections import Counter
|
| 5 |
+
from typing import Dict, List, Optional, Sized, Tuple, Union, Any
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
import numpy as np
|
| 9 |
+
from nltk import ngrams as ngram_tokenizer
|
| 10 |
+
from tokenizers import AddedToken
|
| 11 |
+
from transformers import PreTrainedTokenizer
|
| 12 |
+
from transformers.tokenization_utils_base import (BatchEncoding, EncodedInput,
|
| 13 |
+
TruncationStrategy)
|
| 14 |
+
from transformers.utils import logging
|
| 15 |
+
from transformers.utils.generic import PaddingStrategy, TensorType, to_py_obj
|
| 16 |
+
|
| 17 |
+
logger = logging.get_logger(__name__)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def load_vocab(vocab_file):
|
| 21 |
+
"""Loads a vocabulary file into a dictionary."""
|
| 22 |
+
with open(vocab_file, "r", encoding="utf-8") as f:
|
| 23 |
+
vocab = json.load(f)
|
| 24 |
+
return vocab
|
| 25 |
+
|
| 26 |
+
def all_same(items):
|
| 27 |
+
return all(x == items[0] for x in items)
|
| 28 |
+
|
| 29 |
+
class NGMETokenizer(PreTrainedTokenizer):
|
| 30 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 31 |
+
vocab_file = "vocab.json"
|
| 32 |
+
vocab_files_names = {"vocab_file": vocab_file}
|
| 33 |
+
|
| 34 |
+
def __init__(
|
| 35 |
+
self, vocab_file, eos_token="\n", pad_token="\n", unk_token="<unk>", **kwargs
|
| 36 |
+
):
|
| 37 |
+
super().__init__(
|
| 38 |
+
eos_token=eos_token, pad_token=pad_token, unk_token=unk_token, **kwargs
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
eos_token = (
|
| 43 |
+
AddedToken(
|
| 44 |
+
eos_token,
|
| 45 |
+
lstrip=False,
|
| 46 |
+
rstrip=False,
|
| 47 |
+
)
|
| 48 |
+
if isinstance(eos_token, str)
|
| 49 |
+
else eos_token
|
| 50 |
+
)
|
| 51 |
+
pad_token = (
|
| 52 |
+
AddedToken(
|
| 53 |
+
pad_token,
|
| 54 |
+
lstrip=False,
|
| 55 |
+
rstrip=False,
|
| 56 |
+
)
|
| 57 |
+
if isinstance(pad_token, str)
|
| 58 |
+
else pad_token
|
| 59 |
+
)
|
| 60 |
+
unk_token = (
|
| 61 |
+
AddedToken(
|
| 62 |
+
unk_token,
|
| 63 |
+
lstrip=False,
|
| 64 |
+
rstrip=False,
|
| 65 |
+
)
|
| 66 |
+
if isinstance(unk_token, str)
|
| 67 |
+
else unk_token
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
self._ngram2word2idx = {}
|
| 71 |
+
self._ngram2idx2word = {}
|
| 72 |
+
self._current_max_idx = 0
|
| 73 |
+
self._frequencies: Counter = Counter()
|
| 74 |
+
|
| 75 |
+
self._load_from_file(vocab_file)
|
| 76 |
+
|
| 77 |
+
for n in range(2, self.ngram+1):
|
| 78 |
+
self.model_input_names.append(f"ngram_{n}_sequence")
|
| 79 |
+
|
| 80 |
+
# TODO: COuld also be whitespace if n+1gram dont contain it
|
| 81 |
+
self._special_token = "Ġ"
|
| 82 |
+
assert self._special_token not in self._ngram2word2idx[1]
|
| 83 |
+
|
| 84 |
+
def __call__(self, *args, **kwargs) -> BatchEncoding:
|
| 85 |
+
if "return_ngram_sequences" in kwargs:
|
| 86 |
+
return_ngram_sequences = kwargs["return_ngram_sequences"]
|
| 87 |
+
del kwargs["return_ngram_sequences"]
|
| 88 |
+
else:
|
| 89 |
+
return_ngram_sequences = False
|
| 90 |
+
|
| 91 |
+
# We could check the args and kwargs beforehand and apply extra ngram sequences based on it, but
|
| 92 |
+
# we let HF handle all logic and reverse take the char sequence from the ids
|
| 93 |
+
batch_encoding = super().__call__(*args, **kwargs)
|
| 94 |
+
|
| 95 |
+
if return_ngram_sequences:
|
| 96 |
+
ngram_sequences = self.create_ngram_sequences(args[0])
|
| 97 |
+
# NOTE: This is pretty hard coded, lets just throw an error if the user wants to use it differently
|
| 98 |
+
|
| 99 |
+
if "padding" in kwargs:
|
| 100 |
+
if kwargs["padding"] == "max_length":
|
| 101 |
+
padded_sequences = {}
|
| 102 |
+
for n_key, sequence in ngram_sequences.items():
|
| 103 |
+
padded_sequences[n_key] = self.pad_sequence_right(sequence, len(batch_encoding["input_ids"][0]), self.pad_token_id)
|
| 104 |
+
|
| 105 |
+
ngram_sequences = padded_sequences
|
| 106 |
+
else:
|
| 107 |
+
raise ValueError(f"Padding {kwargs['padding']} not supported for ngram sequences")
|
| 108 |
+
|
| 109 |
+
if "truncation" in kwargs and kwargs["truncation"]:
|
| 110 |
+
truncated_sequences = {}
|
| 111 |
+
for n_key, sequence in ngram_sequences.items():
|
| 112 |
+
truncated_sequences[n_key] = self.truncate_sequence_right(sequence, len(batch_encoding["input_ids"][0]))
|
| 113 |
+
ngram_sequences = truncated_sequences
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
batch_encoding.update(ngram_sequences)
|
| 117 |
+
|
| 118 |
+
if "return_tensors" in kwargs:
|
| 119 |
+
batch_encoding.convert_to_tensors(kwargs["return_tensors"])
|
| 120 |
+
|
| 121 |
+
return batch_encoding
|
| 122 |
+
|
| 123 |
+
def pad_sequence_right(self, batched_sequence: List[List[int]], padding_length: int, padding_value: int) -> List[List[int]]:
|
| 124 |
+
padded_sequence = []
|
| 125 |
+
for sequence in batched_sequence:
|
| 126 |
+
padded_sequence.append(sequence + [padding_value] * (padding_length - len(sequence)))
|
| 127 |
+
return padded_sequence
|
| 128 |
+
|
| 129 |
+
def truncate_sequence_right(self, batched_sequence: List[List[int]], max_length: int) -> List[List[int]]:
|
| 130 |
+
truncated_sequence = []
|
| 131 |
+
for sequence in batched_sequence:
|
| 132 |
+
truncated_sequence.append(sequence[:max_length])
|
| 133 |
+
return truncated_sequence
|
| 134 |
+
|
| 135 |
+
def create_ngram_sequences(self, char_sequences: List[str]) -> Dict[str, Any]:
|
| 136 |
+
|
| 137 |
+
ngram_sequences_output = {}
|
| 138 |
+
|
| 139 |
+
if isinstance(char_sequences, str):
|
| 140 |
+
char_sequences = [char_sequences]
|
| 141 |
+
|
| 142 |
+
for n in range(2, self.ngram+1):
|
| 143 |
+
ngram_sequences = []
|
| 144 |
+
for char_sequence in char_sequences:
|
| 145 |
+
ngrams = ["".join(ngram) for ngram in ngram_tokenizer(char_sequence, n)]
|
| 146 |
+
# Fill in the front with existign unigrams, for same length and
|
| 147 |
+
# because the timestep t should not look ahead
|
| 148 |
+
ngrams = list(char_sequence[:n-1]) + ngrams
|
| 149 |
+
encoded_ngrams = self.encode(ngrams) if len(ngrams) > 0 else []
|
| 150 |
+
ngram_sequences.append(encoded_ngrams)
|
| 151 |
+
|
| 152 |
+
ngram_sequences_output[f"label_gram_{n}_sequence"] = ngram_sequences
|
| 153 |
+
|
| 154 |
+
return ngram_sequences_output
|
| 155 |
+
|
| 156 |
+
def _seq_size(self, encoded) -> Union[int, List[int]]:
|
| 157 |
+
if isinstance(encoded, torch.Tensor):
|
| 158 |
+
encoded = encoded.tolist()
|
| 159 |
+
|
| 160 |
+
if isinstance(encoded[0], list):
|
| 161 |
+
return [len(enc) for enc in encoded]
|
| 162 |
+
|
| 163 |
+
return len(encoded)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def _load_from_file(self, filename: str):
|
| 167 |
+
"""Loads a dictionary from a file."""
|
| 168 |
+
vocab_file = load_vocab(filename)
|
| 169 |
+
self.ngram = vocab_file["ngram"]
|
| 170 |
+
|
| 171 |
+
if "\n" not in vocab_file["vocab"]:
|
| 172 |
+
self._add_ngram("\n", 1)
|
| 173 |
+
|
| 174 |
+
for token in vocab_file["vocab"]:
|
| 175 |
+
self._add_ngram(token["token"], token["ngram"])
|
| 176 |
+
self._frequencies.update({token["token"]: token["frequency"]})
|
| 177 |
+
|
| 178 |
+
def _add_ngram(self, word, ngram: int) -> int:
|
| 179 |
+
"""Add a new n-gram token to the dictionary."""
|
| 180 |
+
self._frequencies.update({word: 1})
|
| 181 |
+
|
| 182 |
+
if ngram not in self._ngram2idx2word:
|
| 183 |
+
self._ngram2idx2word[ngram] = {self._current_max_idx: word}
|
| 184 |
+
self._ngram2word2idx[ngram] = {word: self._current_max_idx}
|
| 185 |
+
self._current_max_idx += 1
|
| 186 |
+
else:
|
| 187 |
+
if word not in self._ngram2word2idx[ngram]:
|
| 188 |
+
self._ngram2idx2word[ngram][self._current_max_idx] = word
|
| 189 |
+
self._ngram2word2idx[ngram][word] = self._current_max_idx
|
| 190 |
+
self._current_max_idx += 1
|
| 191 |
+
|
| 192 |
+
return self._ngram2word2idx[ngram][word]
|
| 193 |
+
|
| 194 |
+
def _is_contiguous(self):
|
| 195 |
+
vocab_size = len(self)
|
| 196 |
+
return list(range(vocab_size)) == [
|
| 197 |
+
idx for idx, token in self._get_all_tokens()
|
| 198 |
+
]
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def _get_all_tokens(self):
|
| 202 |
+
"""Returns all tokens in the dictionary."""
|
| 203 |
+
for ngram in range(1, self.ngram + 1):
|
| 204 |
+
for idx, token in self._ngram2idx2word[ngram].items():
|
| 205 |
+
yield idx, token
|
| 206 |
+
|
| 207 |
+
def save_vocabulary(
|
| 208 |
+
self, save_directory: str, filename_prefix: Optional[str] = None
|
| 209 |
+
) -> Tuple[str]:
|
| 210 |
+
filename = os.path.join(
|
| 211 |
+
save_directory,
|
| 212 |
+
(filename_prefix + "-" if filename_prefix else ""),
|
| 213 |
+
self.vocab_file,
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
index = 0
|
| 217 |
+
vocab = {"ngram": self.ngram, "vocab": []}
|
| 218 |
+
|
| 219 |
+
for ngram in range(1, self.ngram + 1):
|
| 220 |
+
for idx, token in self._ngram2idx2word[ngram].items():
|
| 221 |
+
if index != idx:
|
| 222 |
+
index = idx
|
| 223 |
+
|
| 224 |
+
try:
|
| 225 |
+
frequency = self._frequencies[token]
|
| 226 |
+
except KeyError:
|
| 227 |
+
frequency = -1
|
| 228 |
+
|
| 229 |
+
index += 1
|
| 230 |
+
vocab["vocab"].append(
|
| 231 |
+
{
|
| 232 |
+
"token": token,
|
| 233 |
+
"index": idx,
|
| 234 |
+
"frequency": frequency,
|
| 235 |
+
"ngram": ngram,
|
| 236 |
+
}
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
with open(filename, "w", encoding="utf-8") as writer:
|
| 240 |
+
json.dump(vocab, writer, indent=4, ensure_ascii=False)
|
| 241 |
+
|
| 242 |
+
return (filename,)
|
| 243 |
+
|
| 244 |
+
@property
|
| 245 |
+
def vocab_size(self) -> int:
|
| 246 |
+
return self._current_max_idx
|
| 247 |
+
|
| 248 |
+
def _tokenize(self, text: str) -> List[str]:
|
| 249 |
+
return list(text)
|
| 250 |
+
|
| 251 |
+
def get_idx(self, token: str, ngram: Optional[int] = None) -> int:
|
| 252 |
+
if ngram:
|
| 253 |
+
if token in self._ngram2word2idx[ngram]:
|
| 254 |
+
return self._ngram2word2idx[ngram][token]
|
| 255 |
+
else:
|
| 256 |
+
return self._ngram2word2idx[1]["<unk>"]
|
| 257 |
+
|
| 258 |
+
for ngram in range(1, self.ngram + 1):
|
| 259 |
+
if token in self._ngram2word2idx[ngram]:
|
| 260 |
+
return self._ngram2word2idx[ngram][token]
|
| 261 |
+
|
| 262 |
+
return self._ngram2word2idx[1]["<unk>"]
|
| 263 |
+
|
| 264 |
+
def _convert_ngram_tokens_to_ids(self, ngram_tokens: List[str]) -> List[int]:
|
| 265 |
+
return [self.get_idx(token) for token in ngram_tokens]
|
| 266 |
+
|
| 267 |
+
def convert_tokens_to_ids(self, tokens: List[str]):
|
| 268 |
+
if not tokens:
|
| 269 |
+
return []
|
| 270 |
+
|
| 271 |
+
if isinstance(tokens, str):
|
| 272 |
+
return self.get_idx(tokens)
|
| 273 |
+
|
| 274 |
+
return self._convert_ngram_tokens_to_ids(tokens)
|
| 275 |
+
|
| 276 |
+
def _convert_id_to_token(self, index: int) -> str:
|
| 277 |
+
return self.get_item_for_index(index)
|
| 278 |
+
|
| 279 |
+
def get_item_for_index(self, idx) -> str:
|
| 280 |
+
|
| 281 |
+
"""Return the token for a given index."""
|
| 282 |
+
for idxs in self._ngram2idx2word.values():
|
| 283 |
+
if idx in idxs:
|
| 284 |
+
return idxs[idx]
|
| 285 |
+
|
| 286 |
+
return self.unk_token
|
| 287 |
+
|
| 288 |
+
def convert_tokens_to_string(self, tokens):
|
| 289 |
+
return "".join(tokens)
|
| 290 |
+
|
| 291 |
+
def create_weight_tensor(self) -> torch.Tensor:
|
| 292 |
+
unked_freqs = self._frequencies.most_common()
|
| 293 |
+
|
| 294 |
+
t = torch.ones(len(self))
|
| 295 |
+
|
| 296 |
+
for token, freq in unked_freqs:
|
| 297 |
+
t[self._ngram2word2idx[self._token_to_n_order(token)][token]] = freq
|
| 298 |
+
|
| 299 |
+
# Ensure the only whitespace character is weighted
|
| 300 |
+
t[self._ngram2word2idx[1][" "]] = 1.0
|
| 301 |
+
|
| 302 |
+
max_t = max(t)
|
| 303 |
+
|
| 304 |
+
normed_weights = torch.tensor([(1 - (x / (max_t + 1))).item() for x in t])
|
| 305 |
+
|
| 306 |
+
marker_tokens = [self.get_idx("<unk>", n) for n in range(1, self.ngram+1)]
|
| 307 |
+
marker_tokens.extend([self.get_idx("<start>", n) for n in range(1, self.ngram+1)])
|
| 308 |
+
# Instead of explicit ignore indexes, we use the weight vector and set target idxs to 0
|
| 309 |
+
for marker in marker_tokens:
|
| 310 |
+
normed_weights[marker] = 0
|
| 311 |
+
|
| 312 |
+
return normed_weights
|
| 313 |
+
|
| 314 |
+
def _token_to_n_order(self, token: str) -> int:
|
| 315 |
+
"""Get N-gram order for a token"""
|
| 316 |
+
for n_gram, word2idx in self._ngram2word2idx.items():
|
| 317 |
+
if token in word2idx:
|
| 318 |
+
return n_gram
|
| 319 |
+
|
| 320 |
+
return 0
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
class GPTNGMETokenizer(PreTrainedTokenizer):
|
| 324 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 325 |
+
vocab_file = "vocab.json"
|
| 326 |
+
vocab_files_names = {"vocab_file": vocab_file}
|
| 327 |
+
|
| 328 |
+
def __init__(
|
| 329 |
+
self, vocab_file, eos_token="\n", pad_token="\n", unk_token="<unk>", **kwargs
|
| 330 |
+
):
|
| 331 |
+
eos_token = (
|
| 332 |
+
AddedToken(
|
| 333 |
+
eos_token,
|
| 334 |
+
lstrip=False,
|
| 335 |
+
rstrip=False,
|
| 336 |
+
)
|
| 337 |
+
if isinstance(eos_token, str)
|
| 338 |
+
else eos_token
|
| 339 |
+
)
|
| 340 |
+
pad_token = (
|
| 341 |
+
AddedToken(
|
| 342 |
+
pad_token,
|
| 343 |
+
lstrip=False,
|
| 344 |
+
rstrip=False,
|
| 345 |
+
)
|
| 346 |
+
if isinstance(pad_token, str)
|
| 347 |
+
else pad_token
|
| 348 |
+
)
|
| 349 |
+
unk_token = (
|
| 350 |
+
AddedToken(
|
| 351 |
+
unk_token,
|
| 352 |
+
lstrip=False,
|
| 353 |
+
rstrip=False,
|
| 354 |
+
)
|
| 355 |
+
if isinstance(unk_token, str)
|
| 356 |
+
else unk_token
|
| 357 |
+
)
|
| 358 |
+
|
| 359 |
+
super().__init__(
|
| 360 |
+
eos_token=eos_token, pad_token=pad_token, unk_token=unk_token, **kwargs
|
| 361 |
+
)
|
| 362 |
+
|
| 363 |
+
self._ngram2word2idx = {}
|
| 364 |
+
self._ngram2idx2word = {}
|
| 365 |
+
self._current_max_idx = 0
|
| 366 |
+
self._frequencies: Counter = Counter()
|
| 367 |
+
|
| 368 |
+
self._load_from_file(vocab_file)
|
| 369 |
+
|
| 370 |
+
def _load_from_file(self, filename: str):
|
| 371 |
+
"""Loads a dictionary from a file."""
|
| 372 |
+
vocab_file = load_vocab(filename)
|
| 373 |
+
self.ngram = vocab_file["ngram"]
|
| 374 |
+
|
| 375 |
+
if "\n" not in vocab_file["vocab"]:
|
| 376 |
+
self._add_ngram("\n", 1)
|
| 377 |
+
|
| 378 |
+
for token in vocab_file["vocab"]:
|
| 379 |
+
self._add_ngram(token["token"], token["ngram"])
|
| 380 |
+
self._frequencies.update({token["token"]: token["frequency"]})
|
| 381 |
+
|
| 382 |
+
def _add_ngram(self, word, ngram: int) -> int:
|
| 383 |
+
"""Add a new n-gram token to the dictionary."""
|
| 384 |
+
self._frequencies.update({word: 1})
|
| 385 |
+
|
| 386 |
+
if ngram not in self._ngram2idx2word:
|
| 387 |
+
self._ngram2idx2word[ngram] = {self._current_max_idx: word}
|
| 388 |
+
self._ngram2word2idx[ngram] = {word: self._current_max_idx}
|
| 389 |
+
self._current_max_idx += 1
|
| 390 |
+
else:
|
| 391 |
+
if word not in self._ngram2word2idx[ngram]:
|
| 392 |
+
self._ngram2idx2word[ngram][self._current_max_idx] = word
|
| 393 |
+
self._ngram2word2idx[ngram][word] = self._current_max_idx
|
| 394 |
+
self._current_max_idx += 1
|
| 395 |
+
|
| 396 |
+
return self._ngram2word2idx[ngram][word]
|
| 397 |
+
|
| 398 |
+
def _is_contiguous(self):
|
| 399 |
+
vocab_size = len(self)
|
| 400 |
+
return list(range(vocab_size)) == [
|
| 401 |
+
idx for idx, token in self._get_all_tokens()
|
| 402 |
+
]
|
| 403 |
+
|
| 404 |
+
def _get_all_tokens(self):
|
| 405 |
+
"""Returns all tokens in the dictionary."""
|
| 406 |
+
for ngram in range(1, self.ngram + 1):
|
| 407 |
+
for idx, token in self._ngram2idx2word[ngram].items():
|
| 408 |
+
yield idx, token
|
| 409 |
+
|
| 410 |
+
def save_vocabulary(
|
| 411 |
+
self, save_directory: str, filename_prefix: Optional[str] = None
|
| 412 |
+
) -> Tuple[str]:
|
| 413 |
+
filename = os.path.join(
|
| 414 |
+
save_directory,
|
| 415 |
+
(filename_prefix + "-" if filename_prefix else ""),
|
| 416 |
+
self.vocab_file,
|
| 417 |
+
)
|
| 418 |
+
|
| 419 |
+
index = 0
|
| 420 |
+
vocab = {"ngram": self.ngram, "vocab": []}
|
| 421 |
+
|
| 422 |
+
for ngram in range(1, self.ngram + 1):
|
| 423 |
+
for idx, token in self._ngram2idx2word[ngram].items():
|
| 424 |
+
if index != idx:
|
| 425 |
+
index = idx
|
| 426 |
+
|
| 427 |
+
try:
|
| 428 |
+
frequency = self._frequencies[token]
|
| 429 |
+
except KeyError:
|
| 430 |
+
frequency = -1
|
| 431 |
+
|
| 432 |
+
index += 1
|
| 433 |
+
vocab["vocab"].append(
|
| 434 |
+
{
|
| 435 |
+
"token": token,
|
| 436 |
+
"index": idx,
|
| 437 |
+
"frequency": frequency,
|
| 438 |
+
"ngram": ngram,
|
| 439 |
+
}
|
| 440 |
+
)
|
| 441 |
+
|
| 442 |
+
with open(filename, "w", encoding="utf-8") as writer:
|
| 443 |
+
json.dump(vocab, writer, indent=4, ensure_ascii=False)
|
| 444 |
+
|
| 445 |
+
return (filename,)
|
| 446 |
+
|
| 447 |
+
@property
|
| 448 |
+
def vocab_size(self) -> int:
|
| 449 |
+
return self._current_max_idx
|
| 450 |
+
|
| 451 |
+
def retokenize(self, input_ids, *args, **kwargs):
|
| 452 |
+
decoded = self.convert_ids_to_tokens(input_ids)
|
| 453 |
+
sequence = "".join(decoded)
|
| 454 |
+
new_decoded = self(sequence, *args, **kwargs).input_ids
|
| 455 |
+
return new_decoded
|
| 456 |
+
|
| 457 |
+
def _tokenize(self, text):
|
| 458 |
+
ngram_sequences = []
|
| 459 |
+
for n in range(1, self.ngram + 1):
|
| 460 |
+
words = ["<start>" for _ in range(1, n)]
|
| 461 |
+
words.extend(list(text))
|
| 462 |
+
|
| 463 |
+
tokens = []
|
| 464 |
+
for i, word in enumerate(ngram_tokenizer(words, n)):
|
| 465 |
+
if "<start>" in word:
|
| 466 |
+
word = [w for w in list(word) if w != "<start>"]
|
| 467 |
+
tokens.append("".join(word))
|
| 468 |
+
|
| 469 |
+
ngram_sequences.append(tokens)
|
| 470 |
+
|
| 471 |
+
return ngram_sequences
|
| 472 |
+
|
| 473 |
+
def get_idx(self, token: str, ngram: Optional[int] = None) -> int:
|
| 474 |
+
if ngram:
|
| 475 |
+
if token in self._ngram2word2idx[ngram]:
|
| 476 |
+
return self._ngram2word2idx[ngram][token]
|
| 477 |
+
else:
|
| 478 |
+
return self._ngram2word2idx[1]["<unk>"]
|
| 479 |
+
|
| 480 |
+
for ngram in range(1, self.ngram + 1):
|
| 481 |
+
if token in self._ngram2word2idx[ngram]:
|
| 482 |
+
return self._ngram2word2idx[ngram][token]
|
| 483 |
+
|
| 484 |
+
return self._ngram2word2idx[1]["<unk>"]
|
| 485 |
+
|
| 486 |
+
def _convert_ngram_tokens_to_ids(self, ngram_tokens: List[str]) -> List[int]:
|
| 487 |
+
return [self.get_idx(token) for token in ngram_tokens]
|
| 488 |
+
|
| 489 |
+
def convert_tokens_to_ids(self, tokens: List[List[str]]):
|
| 490 |
+
if not tokens:
|
| 491 |
+
return []
|
| 492 |
+
|
| 493 |
+
if isinstance(tokens, str):
|
| 494 |
+
return self.get_idx(tokens)
|
| 495 |
+
|
| 496 |
+
return [
|
| 497 |
+
self._convert_ngram_tokens_to_ids(ngram_tokens) for ngram_tokens in tokens
|
| 498 |
+
]
|
| 499 |
+
|
| 500 |
+
def _convert_id_to_token(self, index: int) -> str:
|
| 501 |
+
return self.get_item_for_index(index)
|
| 502 |
+
|
| 503 |
+
def get_item_for_index(self, idx) -> str:
|
| 504 |
+
"""Return the token for a given index."""
|
| 505 |
+
for idxs in self._ngram2idx2word.values():
|
| 506 |
+
if idx in idxs:
|
| 507 |
+
return idxs[idx]
|
| 508 |
+
|
| 509 |
+
return self.unk_token
|
| 510 |
+
|
| 511 |
+
def _decode(
|
| 512 |
+
self, token_ids: List[List[int]], skip_special_tokens: bool = False, **kwargs
|
| 513 |
+
) -> str:
|
| 514 |
+
return "".join(self.convert_ids_to_tokens(token_ids[0]))
|
| 515 |
+
|
| 516 |
+
def debug_decode(self, token_ids: List[List[int]]):
|
| 517 |
+
for n in range(1, self.ngram+1):
|
| 518 |
+
print(f"{n}-gram: {self.convert_ids_to_tokens(token_ids[n-1])}")
|
| 519 |
+
|
| 520 |
+
def _pad(
|
| 521 |
+
self,
|
| 522 |
+
encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],
|
| 523 |
+
max_length: Optional[int] = None,
|
| 524 |
+
padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
|
| 525 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 526 |
+
return_attention_mask: Optional[bool] = None,
|
| 527 |
+
) -> dict:
|
| 528 |
+
"""
|
| 529 |
+
Pad encoded inputs (on left/right and up to predefined length or max length in the batch)
|
| 530 |
+
|
| 531 |
+
Args:
|
| 532 |
+
encoded_inputs:
|
| 533 |
+
Dictionary of tokenized inputs (`List[int]`) or batch of tokenized inputs (`List[List[int]]`).
|
| 534 |
+
max_length: maximum length of the returned list and optionally padding length (see below).
|
| 535 |
+
Will truncate by taking into account the special tokens.
|
| 536 |
+
padding_strategy: PaddingStrategy to use for padding.
|
| 537 |
+
|
| 538 |
+
- PaddingStrategy.LONGEST Pad to the longest sequence in the batch
|
| 539 |
+
- PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
|
| 540 |
+
- PaddingStrategy.DO_NOT_PAD: Do not pad
|
| 541 |
+
The tokenizer padding sides are defined in self.padding_side:
|
| 542 |
+
|
| 543 |
+
- 'left': pads on the left of the sequences
|
| 544 |
+
- 'right': pads on the right of the sequences
|
| 545 |
+
pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.
|
| 546 |
+
This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability
|
| 547 |
+
`>= 7.5` (Volta).
|
| 548 |
+
return_attention_mask:
|
| 549 |
+
(optional) Set to False to avoid returning attention mask (default: set to model specifics)
|
| 550 |
+
"""
|
| 551 |
+
# encoded_inputs == one sample -> List[List[int]]
|
| 552 |
+
|
| 553 |
+
# Load from model defaults
|
| 554 |
+
if return_attention_mask is None:
|
| 555 |
+
return_attention_mask = "attention_mask" in self.model_input_names
|
| 556 |
+
|
| 557 |
+
required_input = encoded_inputs[self.model_input_names[0]]
|
| 558 |
+
# PHA: Check if we have a list of list of list, then we unpack
|
| 559 |
+
if (
|
| 560 |
+
len(required_input) != 0
|
| 561 |
+
and isinstance(required_input[0], list)
|
| 562 |
+
and isinstance(required_input[0][0], list)
|
| 563 |
+
):
|
| 564 |
+
required_input = required_input[0]
|
| 565 |
+
|
| 566 |
+
if padding_strategy == PaddingStrategy.LONGEST:
|
| 567 |
+
max_length = len(required_input)
|
| 568 |
+
|
| 569 |
+
if (
|
| 570 |
+
max_length is not None
|
| 571 |
+
and pad_to_multiple_of is not None
|
| 572 |
+
and (max_length % pad_to_multiple_of != 0)
|
| 573 |
+
):
|
| 574 |
+
max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
|
| 575 |
+
|
| 576 |
+
needs_to_be_padded = (
|
| 577 |
+
padding_strategy != PaddingStrategy.DO_NOT_PAD
|
| 578 |
+
and len(required_input[0]) != max_length
|
| 579 |
+
)
|
| 580 |
+
|
| 581 |
+
# Initialize attention mask if not present.
|
| 582 |
+
if return_attention_mask and "attention_mask" not in encoded_inputs:
|
| 583 |
+
if len(required_input) == 0:
|
| 584 |
+
encoded_inputs["attention_mask"] = []
|
| 585 |
+
else:
|
| 586 |
+
encoded_inputs["attention_mask"] = [1] * len(required_input[0])
|
| 587 |
+
|
| 588 |
+
if needs_to_be_padded:
|
| 589 |
+
difference = max_length - len(required_input[0])
|
| 590 |
+
|
| 591 |
+
if self.padding_side == "right":
|
| 592 |
+
if return_attention_mask:
|
| 593 |
+
encoded_inputs["attention_mask"] = (
|
| 594 |
+
encoded_inputs["attention_mask"] + [0] * difference
|
| 595 |
+
)
|
| 596 |
+
if "token_type_ids" in encoded_inputs:
|
| 597 |
+
encoded_inputs["token_type_ids"] = (
|
| 598 |
+
encoded_inputs["token_type_ids"]
|
| 599 |
+
+ [self.pad_token_type_id] * difference
|
| 600 |
+
)
|
| 601 |
+
if "special_tokens_mask" in encoded_inputs:
|
| 602 |
+
encoded_inputs["special_tokens_mask"] = (
|
| 603 |
+
encoded_inputs["special_tokens_mask"] + [1] * difference
|
| 604 |
+
)
|
| 605 |
+
for i in range(len(encoded_inputs[self.model_input_names[0]])):
|
| 606 |
+
encoded_inputs[self.model_input_names[0]][i] = (
|
| 607 |
+
required_input[i] + [self.pad_token_id] * difference
|
| 608 |
+
)
|
| 609 |
+
elif self.padding_side == "left":
|
| 610 |
+
if return_attention_mask:
|
| 611 |
+
encoded_inputs["attention_mask"] = [
|
| 612 |
+
0
|
| 613 |
+
] * difference + encoded_inputs["attention_mask"]
|
| 614 |
+
if "token_type_ids" in encoded_inputs:
|
| 615 |
+
encoded_inputs["token_type_ids"] = [
|
| 616 |
+
self.pad_token_type_id
|
| 617 |
+
] * difference + encoded_inputs["token_type_ids"]
|
| 618 |
+
if "special_tokens_mask" in encoded_inputs:
|
| 619 |
+
encoded_inputs["special_tokens_mask"] = [
|
| 620 |
+
1
|
| 621 |
+
] * difference + encoded_inputs["special_tokens_mask"]
|
| 622 |
+
|
| 623 |
+
for i in range(len(encoded_inputs[self.model_input_names[0]])):
|
| 624 |
+
encoded_inputs[self.model_input_names[0]][i] = [
|
| 625 |
+
self.pad_token_id
|
| 626 |
+
] * difference + required_input[i]
|
| 627 |
+
else:
|
| 628 |
+
raise ValueError("Invalid padding strategy:" + str(self.padding_side))
|
| 629 |
+
|
| 630 |
+
return encoded_inputs
|
| 631 |
+
|
| 632 |
+
def pad(
|
| 633 |
+
self,
|
| 634 |
+
encoded_inputs: Union[
|
| 635 |
+
BatchEncoding,
|
| 636 |
+
List[BatchEncoding],
|
| 637 |
+
Dict[str, EncodedInput],
|
| 638 |
+
Dict[str, List[EncodedInput]],
|
| 639 |
+
List[Dict[str, EncodedInput]],
|
| 640 |
+
],
|
| 641 |
+
padding: Union[bool, str, PaddingStrategy] = True,
|
| 642 |
+
max_length: Optional[int] = None,
|
| 643 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 644 |
+
return_attention_mask: Optional[bool] = None,
|
| 645 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 646 |
+
verbose: bool = True,
|
| 647 |
+
) -> BatchEncoding:
|
| 648 |
+
"""
|
| 649 |
+
Pad a single encoded input or a batch of encoded inputs up to predefined length or to the max sequence length
|
| 650 |
+
in the batch.
|
| 651 |
+
|
| 652 |
+
Padding side (left/right) padding token ids are defined at the tokenizer level (with `self.padding_side`,
|
| 653 |
+
|
| 654 |
+
`self.pad_token_id` and `self.pad_token_type_id`).
|
| 655 |
+
|
| 656 |
+
Please note that with a fast tokenizer, using the `__call__` method is faster than using a method to encode the
|
| 657 |
+
text followed by a call to the `pad` method to get a padded encoding.
|
| 658 |
+
|
| 659 |
+
<Tip>
|
| 660 |
+
|
| 661 |
+
If the `encoded_inputs` passed are dictionary of numpy arrays, PyTorch tensors or TensorFlow tensors, the
|
| 662 |
+
result will use the same type unless you provide a different tensor type with `return_tensors`. In the case of
|
| 663 |
+
PyTorch tensors, you will lose the specific device of your tensors however.
|
| 664 |
+
|
| 665 |
+
</Tip>
|
| 666 |
+
|
| 667 |
+
Args:
|
| 668 |
+
encoded_inputs ([`BatchEncoding`], list of [`BatchEncoding`], `Dict[str, List[int]]`, `Dict[str, List[List[int]]` or `List[Dict[str, List[int]]]`):
|
| 669 |
+
Tokenized inputs. Can represent one input ([`BatchEncoding`] or `Dict[str, List[int]]`) or a batch of
|
| 670 |
+
tokenized inputs (list of [`BatchEncoding`], *Dict[str, List[List[int]]]* or *List[Dict[str,
|
| 671 |
+
List[int]]]*) so you can use this method during preprocessing as well as in a PyTorch Dataloader
|
| 672 |
+
collate function.
|
| 673 |
+
|
| 674 |
+
Instead of `List[int]` you can have tensors (numpy arrays, PyTorch tensors or TensorFlow tensors), see
|
| 675 |
+
the note above for the return type.
|
| 676 |
+
padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True`):
|
| 677 |
+
Select a strategy to pad the returned sequences (according to the model's padding side and padding
|
| 678 |
+
index) among:
|
| 679 |
+
|
| 680 |
+
- `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
|
| 681 |
+
sequence if provided).
|
| 682 |
+
- `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
|
| 683 |
+
acceptable input length for the model if that argument is not provided.
|
| 684 |
+
- `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
|
| 685 |
+
lengths).
|
| 686 |
+
max_length (`int`, *optional*):
|
| 687 |
+
Maximum length of the returned list and optionally padding length (see above).
|
| 688 |
+
pad_to_multiple_of (`int`, *optional*):
|
| 689 |
+
If set will pad the sequence to a multiple of the provided value.
|
| 690 |
+
|
| 691 |
+
This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability
|
| 692 |
+
`>= 7.5` (Volta).
|
| 693 |
+
return_attention_mask (`bool`, *optional*):
|
| 694 |
+
Whether to return the attention mask. If left to the default, will return the attention mask according
|
| 695 |
+
to the specific tokenizer's default, defined by the `return_outputs` attribute.
|
| 696 |
+
|
| 697 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 698 |
+
return_tensors (`str` or [`~utils.TensorType`], *optional*):
|
| 699 |
+
If set, will return tensors instead of list of python integers. Acceptable values are:
|
| 700 |
+
|
| 701 |
+
- `'tf'`: Return TensorFlow `tf.constant` objects.
|
| 702 |
+
- `'pt'`: Return PyTorch `torch.Tensor` objects.
|
| 703 |
+
- `'np'`: Return Numpy `np.ndarray` objects.
|
| 704 |
+
verbose (`bool`, *optional*, defaults to `True`):
|
| 705 |
+
Whether or not to print more information and warnings.
|
| 706 |
+
"""
|
| 707 |
+
|
| 708 |
+
# Problem: The pad function checks if the encoded_inputs is a list or not
|
| 709 |
+
# If it is a list it assumes that we have batches
|
| 710 |
+
# With ngme encoding the input is always a list
|
| 711 |
+
|
| 712 |
+
# If we have a list of dicts, let's convert it in a dict of lists
|
| 713 |
+
# We do this to allow using this method as a collate_fn function in PyTorch Dataloader
|
| 714 |
+
if isinstance(encoded_inputs, (list, tuple)) and isinstance(
|
| 715 |
+
encoded_inputs[0], Mapping
|
| 716 |
+
):
|
| 717 |
+
encoded_inputs = {
|
| 718 |
+
key: [example[key] for example in encoded_inputs]
|
| 719 |
+
for key in encoded_inputs[0].keys()
|
| 720 |
+
}
|
| 721 |
+
|
| 722 |
+
# The model's main input name, usually `input_ids`, has be passed for padding
|
| 723 |
+
if self.model_input_names[0] not in encoded_inputs:
|
| 724 |
+
raise ValueError(
|
| 725 |
+
"You should supply an encoding or a list of encodings to this method "
|
| 726 |
+
f"that includes {self.model_input_names[0]}, but you provided {list(encoded_inputs.keys())}"
|
| 727 |
+
)
|
| 728 |
+
|
| 729 |
+
required_input = encoded_inputs[self.model_input_names[0]]
|
| 730 |
+
|
| 731 |
+
if required_input is None or (
|
| 732 |
+
isinstance(required_input, Sized) and len(required_input) == 0
|
| 733 |
+
):
|
| 734 |
+
if return_attention_mask:
|
| 735 |
+
encoded_inputs["attention_mask"] = []
|
| 736 |
+
return encoded_inputs
|
| 737 |
+
|
| 738 |
+
# If we have PyTorch/TF/NumPy tensors/arrays as inputs, we cast them as python objects
|
| 739 |
+
# and rebuild them afterwards if no return_tensors is specified
|
| 740 |
+
# Note that we lose the specific device the tensor may be on for PyTorch
|
| 741 |
+
|
| 742 |
+
first_element = required_input[0]
|
| 743 |
+
# PHA: First element in ngme is a list of list
|
| 744 |
+
if isinstance(first_element, (list, tuple)):
|
| 745 |
+
# first_element might be an empty list/tuple in some edge cases so we grab the first non empty element.
|
| 746 |
+
for item in required_input:
|
| 747 |
+
if len(item) != 0:
|
| 748 |
+
first_element = item[0]
|
| 749 |
+
break
|
| 750 |
+
# At this state, if `first_element` is still a list/tuple, it's an empty one so there is nothing to do.
|
| 751 |
+
if not isinstance(first_element, (int, list, tuple)):
|
| 752 |
+
if is_tf_tensor(first_element):
|
| 753 |
+
return_tensors = "tf" if return_tensors is None else return_tensors
|
| 754 |
+
elif is_torch_tensor(first_element):
|
| 755 |
+
return_tensors = "pt" if return_tensors is None else return_tensors
|
| 756 |
+
elif isinstance(first_element, np.ndarray):
|
| 757 |
+
return_tensors = "np" if return_tensors is None else return_tensors
|
| 758 |
+
else:
|
| 759 |
+
raise ValueError(
|
| 760 |
+
f"type of {first_element} unknown: {type(first_element)}. "
|
| 761 |
+
"Should be one of a python, numpy, pytorch or tensorflow object."
|
| 762 |
+
)
|
| 763 |
+
|
| 764 |
+
for key, value in encoded_inputs.items():
|
| 765 |
+
encoded_inputs[key] = to_py_obj(value)
|
| 766 |
+
|
| 767 |
+
# Convert padding_strategy in PaddingStrategy
|
| 768 |
+
padding_strategy, _, max_length, _ = self._get_padding_truncation_strategies(
|
| 769 |
+
padding=padding, max_length=max_length, verbose=verbose
|
| 770 |
+
)
|
| 771 |
+
|
| 772 |
+
required_input = encoded_inputs[self.model_input_names[0]]
|
| 773 |
+
|
| 774 |
+
if required_input:
|
| 775 |
+
if isinstance(required_input[0], (list, tuple)):
|
| 776 |
+
if len(required_input[0]) > 0 and not isinstance(
|
| 777 |
+
required_input[0][0], (list, tuple)
|
| 778 |
+
):
|
| 779 |
+
encoded_inputs = self._pad(
|
| 780 |
+
encoded_inputs,
|
| 781 |
+
max_length=max_length,
|
| 782 |
+
padding_strategy=padding_strategy,
|
| 783 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 784 |
+
return_attention_mask=return_attention_mask,
|
| 785 |
+
)
|
| 786 |
+
return BatchEncoding(encoded_inputs, tensor_type=return_tensors)
|
| 787 |
+
|
| 788 |
+
batch_size = len(required_input)
|
| 789 |
+
assert all(
|
| 790 |
+
len(v) == batch_size for v in encoded_inputs.values()
|
| 791 |
+
), "Some items in the output dictionary have a different batch size than others."
|
| 792 |
+
|
| 793 |
+
if padding_strategy == PaddingStrategy.LONGEST:
|
| 794 |
+
max_length = max(len(inputs[0]) for inputs in required_input)
|
| 795 |
+
padding_strategy = PaddingStrategy.MAX_LENGTH
|
| 796 |
+
|
| 797 |
+
batch_outputs = {}
|
| 798 |
+
for i in range(batch_size):
|
| 799 |
+
inputs = dict((k, v[i]) for k, v in encoded_inputs.items())
|
| 800 |
+
outputs = self._pad(
|
| 801 |
+
inputs,
|
| 802 |
+
max_length=max_length,
|
| 803 |
+
padding_strategy=padding_strategy,
|
| 804 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 805 |
+
return_attention_mask=return_attention_mask,
|
| 806 |
+
)
|
| 807 |
+
|
| 808 |
+
for key, value in outputs.items():
|
| 809 |
+
if key not in batch_outputs:
|
| 810 |
+
batch_outputs[key] = []
|
| 811 |
+
batch_outputs[key].append(value)
|
| 812 |
+
|
| 813 |
+
return BatchEncoding(batch_outputs, tensor_type=return_tensors)
|
| 814 |
+
|
| 815 |
+
def prepare_for_model(
|
| 816 |
+
self,
|
| 817 |
+
ids: List[int],
|
| 818 |
+
pair_ids: Optional[List[int]] = None,
|
| 819 |
+
add_special_tokens: bool = True,
|
| 820 |
+
padding: Union[bool, str, PaddingStrategy] = False,
|
| 821 |
+
truncation: Union[bool, str, TruncationStrategy] = None,
|
| 822 |
+
max_length: Optional[int] = None,
|
| 823 |
+
stride: int = 0,
|
| 824 |
+
pad_to_multiple_of: Optional[int] = None,
|
| 825 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 826 |
+
return_token_type_ids: Optional[bool] = None,
|
| 827 |
+
return_attention_mask: Optional[bool] = None,
|
| 828 |
+
return_overflowing_tokens: bool = False,
|
| 829 |
+
return_special_tokens_mask: bool = False,
|
| 830 |
+
return_offsets_mapping: bool = False,
|
| 831 |
+
return_length: bool = False,
|
| 832 |
+
verbose: bool = True,
|
| 833 |
+
prepend_batch_axis: bool = False,
|
| 834 |
+
**kwargs,
|
| 835 |
+
) -> BatchEncoding:
|
| 836 |
+
"""
|
| 837 |
+
Prepares a sequence of input id, or a pair of sequences of inputs ids so that it can be used by the model. It
|
| 838 |
+
adds special tokens, truncates sequences if overflowing while taking into account the special tokens and
|
| 839 |
+
manages a moving window (with user defined stride) for overflowing tokens. Please Note, for *pair_ids*
|
| 840 |
+
different than `None` and *truncation_strategy = longest_first* or `True`, it is not possible to return
|
| 841 |
+
overflowing tokens. Such a combination of arguments will raise an error.
|
| 842 |
+
Args:
|
| 843 |
+
ids (`List[int]`):
|
| 844 |
+
Tokenized input ids of the first sequence. Can be obtained from a string by chaining the `tokenize` and
|
| 845 |
+
`convert_tokens_to_ids` methods.
|
| 846 |
+
pair_ids (`List[int]`, *optional*):
|
| 847 |
+
Tokenized input ids of the second sequence. Can be obtained from a string by chaining the `tokenize`
|
| 848 |
+
and `convert_tokens_to_ids` methods.
|
| 849 |
+
"""
|
| 850 |
+
|
| 851 |
+
# Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
|
| 852 |
+
(
|
| 853 |
+
padding_strategy,
|
| 854 |
+
truncation_strategy,
|
| 855 |
+
max_length,
|
| 856 |
+
kwargs,
|
| 857 |
+
) = self._get_padding_truncation_strategies(
|
| 858 |
+
padding=padding,
|
| 859 |
+
truncation=truncation,
|
| 860 |
+
max_length=max_length,
|
| 861 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 862 |
+
verbose=verbose,
|
| 863 |
+
**kwargs,
|
| 864 |
+
)
|
| 865 |
+
|
| 866 |
+
pair = bool(pair_ids is not None)
|
| 867 |
+
|
| 868 |
+
if len(ids) == 0:
|
| 869 |
+
len_ids = 0
|
| 870 |
+
else:
|
| 871 |
+
len_ids = len(ids[0])
|
| 872 |
+
|
| 873 |
+
if pair and len(pair_ids) == 0:
|
| 874 |
+
len_pair_ids = 0
|
| 875 |
+
elif pair and len(pair_ids) > 0:
|
| 876 |
+
len_pair_ids = len(pair_ids[0])
|
| 877 |
+
else:
|
| 878 |
+
len_pair_ids = 0
|
| 879 |
+
|
| 880 |
+
if return_token_type_ids and not add_special_tokens:
|
| 881 |
+
raise ValueError(
|
| 882 |
+
"Asking to return token_type_ids while setting add_special_tokens to False "
|
| 883 |
+
"results in an undefined behavior. Please set add_special_tokens to True or "
|
| 884 |
+
"set return_token_type_ids to None."
|
| 885 |
+
)
|
| 886 |
+
|
| 887 |
+
if (
|
| 888 |
+
return_overflowing_tokens
|
| 889 |
+
and truncation_strategy == TruncationStrategy.LONGEST_FIRST
|
| 890 |
+
and pair_ids is not None
|
| 891 |
+
):
|
| 892 |
+
raise ValueError(
|
| 893 |
+
"Not possible to return overflowing tokens for pair of sequences with the "
|
| 894 |
+
"`longest_first`. Please select another truncation strategy than `longest_first`, "
|
| 895 |
+
"for instance `only_second` or `only_first`."
|
| 896 |
+
)
|
| 897 |
+
|
| 898 |
+
# Load from model defaults
|
| 899 |
+
if return_token_type_ids is None:
|
| 900 |
+
return_token_type_ids = "token_type_ids" in self.model_input_names
|
| 901 |
+
if return_attention_mask is None:
|
| 902 |
+
return_attention_mask = "attention_mask" in self.model_input_names
|
| 903 |
+
|
| 904 |
+
encoded_inputs = {}
|
| 905 |
+
|
| 906 |
+
# Compute the total size of the returned encodings
|
| 907 |
+
total_len = (
|
| 908 |
+
len_ids
|
| 909 |
+
+ len_pair_ids
|
| 910 |
+
+ (self.num_special_tokens_to_add(pair=pair) if add_special_tokens else 0)
|
| 911 |
+
)
|
| 912 |
+
|
| 913 |
+
# Truncation: Handle max sequence length
|
| 914 |
+
overflowing_tokens = []
|
| 915 |
+
if (
|
| 916 |
+
truncation_strategy != TruncationStrategy.DO_NOT_TRUNCATE
|
| 917 |
+
and max_length
|
| 918 |
+
and total_len > max_length
|
| 919 |
+
):
|
| 920 |
+
ids, pair_ids, overflowing_tokens = self.truncate_sequences(
|
| 921 |
+
ids,
|
| 922 |
+
pair_ids=pair_ids,
|
| 923 |
+
num_tokens_to_remove=total_len - max_length,
|
| 924 |
+
truncation_strategy=truncation_strategy,
|
| 925 |
+
stride=stride,
|
| 926 |
+
)
|
| 927 |
+
|
| 928 |
+
if return_overflowing_tokens:
|
| 929 |
+
encoded_inputs["overflowing_tokens"] = overflowing_tokens
|
| 930 |
+
encoded_inputs["num_truncated_tokens"] = total_len - max_length
|
| 931 |
+
|
| 932 |
+
# Add special tokens
|
| 933 |
+
if add_special_tokens:
|
| 934 |
+
sequence = self.build_inputs_with_special_tokens(ids, pair_ids)
|
| 935 |
+
token_type_ids = self.create_token_type_ids_from_sequences(ids, pair_ids)
|
| 936 |
+
else:
|
| 937 |
+
sequence = self.build_inputs_with_special_tokens(ids, pair_ids)
|
| 938 |
+
token_type_ids = [0] * len(ids) + ([0] * len(pair_ids) if pair else [])
|
| 939 |
+
|
| 940 |
+
# Build output dictionary
|
| 941 |
+
encoded_inputs["input_ids"] = sequence
|
| 942 |
+
if return_token_type_ids:
|
| 943 |
+
encoded_inputs["token_type_ids"] = token_type_ids
|
| 944 |
+
if return_special_tokens_mask:
|
| 945 |
+
if add_special_tokens:
|
| 946 |
+
encoded_inputs["special_tokens_mask"] = self.get_special_tokens_mask(
|
| 947 |
+
ids, pair_ids
|
| 948 |
+
)
|
| 949 |
+
else:
|
| 950 |
+
encoded_inputs["special_tokens_mask"] = [0] * len(sequence)
|
| 951 |
+
|
| 952 |
+
# Check lengths
|
| 953 |
+
self._eventual_warn_about_too_long_sequence(
|
| 954 |
+
encoded_inputs["input_ids"], max_length, verbose
|
| 955 |
+
)
|
| 956 |
+
|
| 957 |
+
# Padding
|
| 958 |
+
if padding_strategy != PaddingStrategy.DO_NOT_PAD or return_attention_mask:
|
| 959 |
+
encoded_inputs = self.pad(
|
| 960 |
+
encoded_inputs,
|
| 961 |
+
max_length=max_length,
|
| 962 |
+
padding=padding_strategy.value,
|
| 963 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 964 |
+
return_attention_mask=return_attention_mask,
|
| 965 |
+
)
|
| 966 |
+
|
| 967 |
+
if return_length:
|
| 968 |
+
encoded_inputs["length"] = len(encoded_inputs["input_ids"])
|
| 969 |
+
|
| 970 |
+
batch_outputs = BatchEncoding(
|
| 971 |
+
encoded_inputs,
|
| 972 |
+
tensor_type=return_tensors,
|
| 973 |
+
prepend_batch_axis=prepend_batch_axis,
|
| 974 |
+
)
|
| 975 |
+
|
| 976 |
+
return batch_outputs
|
| 977 |
+
|
| 978 |
+
def build_inputs_with_special_tokens(
|
| 979 |
+
self,
|
| 980 |
+
token_ids_0: List[List[int]],
|
| 981 |
+
token_ids_1: Optional[List[List[int]]] = None,
|
| 982 |
+
) -> List[List[int]]:
|
| 983 |
+
"""
|
| 984 |
+
Concatenate nested ngram sequences.
|
| 985 |
+
|
| 986 |
+
Args:
|
| 987 |
+
token_ids_0 (`List[List[int]]`): The first tokenized sequence.
|
| 988 |
+
token_ids_1 (`List[List[int]]`, *optional*): The second tokenized sequence.
|
| 989 |
+
|
| 990 |
+
Returns:
|
| 991 |
+
`List[List[int]]`: The model input with special tokens.
|
| 992 |
+
"""
|
| 993 |
+
if token_ids_1 is None or len(token_ids_1) == 0:
|
| 994 |
+
return token_ids_0
|
| 995 |
+
|
| 996 |
+
if len(token_ids_0) == 0:
|
| 997 |
+
return token_ids_1
|
| 998 |
+
|
| 999 |
+
return np.concatenate(
|
| 1000 |
+
(np.array(token_ids_0), np.array(token_ids_1)), axis=1
|
| 1001 |
+
).tolist()
|
| 1002 |
+
|
| 1003 |
+
def truncate_sequences(
|
| 1004 |
+
self,
|
| 1005 |
+
ids: List[int],
|
| 1006 |
+
pair_ids: Optional[List[int]] = None,
|
| 1007 |
+
num_tokens_to_remove: int = 0,
|
| 1008 |
+
truncation_strategy: Union[str, TruncationStrategy] = "longest_first",
|
| 1009 |
+
stride: int = 0,
|
| 1010 |
+
) -> Tuple[List[int], List[int], List[int]]:
|
| 1011 |
+
"""
|
| 1012 |
+
Truncates a sequence pair in-place following the strategy.
|
| 1013 |
+
Args:
|
| 1014 |
+
ids (`List[int]`):
|
| 1015 |
+
Tokenized input ids of the first sequence. Can be obtained from a string by chaining the `tokenize` and
|
| 1016 |
+
`convert_tokens_to_ids` methods.
|
| 1017 |
+
pair_ids (`List[int]`, *optional*):
|
| 1018 |
+
Tokenized input ids of the second sequence. Can be obtained from a string by chaining the `tokenize`
|
| 1019 |
+
and `convert_tokens_to_ids` methods.
|
| 1020 |
+
num_tokens_to_remove (`int`, *optional*, defaults to 0):
|
| 1021 |
+
Number of tokens to remove using the truncation strategy.
|
| 1022 |
+
truncation_strategy (`str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):
|
| 1023 |
+
The strategy to follow for truncation. Can be:
|
| 1024 |
+
- `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to the
|
| 1025 |
+
maximum acceptable input length for the model if that argument is not provided. This will truncate
|
| 1026 |
+
token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a
|
| 1027 |
+
batch of pairs) is provided.
|
| 1028 |
+
- `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the
|
| 1029 |
+
maximum acceptable input length for the model if that argument is not provided. This will only
|
| 1030 |
+
truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
|
| 1031 |
+
- `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the
|
| 1032 |
+
maximum acceptable input length for the model if that argument is not provided. This will only
|
| 1033 |
+
truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
|
| 1034 |
+
- `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths greater
|
| 1035 |
+
than the model maximum admissible input size).
|
| 1036 |
+
stride (`int`, *optional*, defaults to 0):
|
| 1037 |
+
If set to a positive number, the overflowing tokens returned will contain some tokens from the main
|
| 1038 |
+
sequence returned. The value of this argument defines the number of additional tokens.
|
| 1039 |
+
Returns:
|
| 1040 |
+
`Tuple[List[int], List[int], List[int]]`: The truncated `ids`, the truncated `pair_ids` and the list of
|
| 1041 |
+
overflowing tokens. Note: The *longest_first* strategy returns empty list of overflowing tokens if a pair
|
| 1042 |
+
of sequences (or a batch of pairs) is provided.
|
| 1043 |
+
"""
|
| 1044 |
+
if num_tokens_to_remove <= 0:
|
| 1045 |
+
return ids, pair_ids, []
|
| 1046 |
+
|
| 1047 |
+
if not isinstance(truncation_strategy, TruncationStrategy):
|
| 1048 |
+
truncation_strategy = TruncationStrategy(truncation_strategy)
|
| 1049 |
+
|
| 1050 |
+
overflowing_tokens = []
|
| 1051 |
+
if truncation_strategy == TruncationStrategy.ONLY_FIRST or (
|
| 1052 |
+
truncation_strategy == TruncationStrategy.LONGEST_FIRST and pair_ids is None
|
| 1053 |
+
):
|
| 1054 |
+
ids = np.array(ids)
|
| 1055 |
+
|
| 1056 |
+
# PHA: I think we only truncate with longest first
|
| 1057 |
+
if ids.shape[1] > num_tokens_to_remove:
|
| 1058 |
+
window_len = min(ids.shape[1], stride + num_tokens_to_remove)
|
| 1059 |
+
if self.truncation_side == "left":
|
| 1060 |
+
overflowing_tokens = ids[:, :window_len]
|
| 1061 |
+
ids = ids[:, num_tokens_to_remove:]
|
| 1062 |
+
elif self.truncation_side == "right":
|
| 1063 |
+
overflowing_tokens = ids[-window_len:]
|
| 1064 |
+
ids = ids[:, :-num_tokens_to_remove]
|
| 1065 |
+
else:
|
| 1066 |
+
raise ValueError(
|
| 1067 |
+
f"invalid truncation strategy: {self.truncation_side}, use 'left' or 'right'."
|
| 1068 |
+
)
|
| 1069 |
+
|
| 1070 |
+
ids = ids.tolist()
|
| 1071 |
+
|
| 1072 |
+
else:
|
| 1073 |
+
error_msg = (
|
| 1074 |
+
f"We need to remove {num_tokens_to_remove} to truncate the input "
|
| 1075 |
+
f"but the first sequence has a length {len(ids)}. "
|
| 1076 |
+
)
|
| 1077 |
+
if truncation_strategy == TruncationStrategy.ONLY_FIRST:
|
| 1078 |
+
error_msg = (
|
| 1079 |
+
error_msg + "Please select another truncation strategy than "
|
| 1080 |
+
f"{truncation_strategy}, for instance 'longest_first' or 'only_second'."
|
| 1081 |
+
)
|
| 1082 |
+
logger.error(error_msg)
|
| 1083 |
+
elif truncation_strategy == TruncationStrategy.LONGEST_FIRST:
|
| 1084 |
+
logger.warning(
|
| 1085 |
+
"Be aware, overflowing tokens are not returned for the setting you have chosen,"
|
| 1086 |
+
f" i.e. sequence pairs with the '{TruncationStrategy.LONGEST_FIRST.value}' "
|
| 1087 |
+
"truncation strategy. So the returned list will always be empty even if some "
|
| 1088 |
+
"tokens have been removed."
|
| 1089 |
+
)
|
| 1090 |
+
ids = np.array(ids)
|
| 1091 |
+
pair_ids = np.array(pair_ids)
|
| 1092 |
+
|
| 1093 |
+
for _ in range(num_tokens_to_remove):
|
| 1094 |
+
if pair_ids is None or ids.shape[1] > pair_ids.shape[1]:
|
| 1095 |
+
if self.truncation_side == "right":
|
| 1096 |
+
ids = ids[:, :-1]
|
| 1097 |
+
elif self.truncation_side == "left":
|
| 1098 |
+
ids = ids[:, 1:]
|
| 1099 |
+
else:
|
| 1100 |
+
raise ValueError(
|
| 1101 |
+
"invalid truncation strategy:" + str(self.truncation_side)
|
| 1102 |
+
)
|
| 1103 |
+
else:
|
| 1104 |
+
if self.truncation_side == "right":
|
| 1105 |
+
pair_ids = pair_ids[:, :-1]
|
| 1106 |
+
elif self.truncation_side == "left":
|
| 1107 |
+
pair_ids = pair_ids[:, 1:]
|
| 1108 |
+
else:
|
| 1109 |
+
raise ValueError(
|
| 1110 |
+
"invalid truncation strategy:" + str(self.truncation_side)
|
| 1111 |
+
)
|
| 1112 |
+
|
| 1113 |
+
ids = ids.tolist()
|
| 1114 |
+
pair_ids = pair_ids.tolist()
|
| 1115 |
+
|
| 1116 |
+
elif (
|
| 1117 |
+
truncation_strategy == TruncationStrategy.ONLY_SECOND
|
| 1118 |
+
and pair_ids is not None
|
| 1119 |
+
):
|
| 1120 |
+
raise NotImplementedError(
|
| 1121 |
+
"PHA: I think we only truncate with longest first"
|
| 1122 |
+
)
|
| 1123 |
+
if len(pair_ids) > num_tokens_to_remove:
|
| 1124 |
+
window_len = min(len(pair_ids), stride + num_tokens_to_remove)
|
| 1125 |
+
if self.truncation_side == "right":
|
| 1126 |
+
overflowing_tokens = pair_ids[-window_len:]
|
| 1127 |
+
pair_ids = pair_ids[:-num_tokens_to_remove]
|
| 1128 |
+
elif self.truncation_side == "left":
|
| 1129 |
+
overflowing_tokens = pair_ids[:window_len]
|
| 1130 |
+
pair_ids = pair_ids[num_tokens_to_remove:]
|
| 1131 |
+
else:
|
| 1132 |
+
raise ValueError(
|
| 1133 |
+
"invalid truncation strategy:" + str(self.truncation_side)
|
| 1134 |
+
)
|
| 1135 |
+
else:
|
| 1136 |
+
logger.error(
|
| 1137 |
+
f"We need to remove {num_tokens_to_remove} to truncate the input "
|
| 1138 |
+
f"but the second sequence has a length {len(pair_ids)}. "
|
| 1139 |
+
f"Please select another truncation strategy than {truncation_strategy}, "
|
| 1140 |
+
"for instance 'longest_first' or 'only_first'."
|
| 1141 |
+
)
|
| 1142 |
+
|
| 1143 |
+
return (ids, pair_ids, overflowing_tokens)
|
| 1144 |
+
|
| 1145 |
+
def _token_to_n_order(self, token: str) -> int:
|
| 1146 |
+
"""Get N-gram order for a token"""
|
| 1147 |
+
for n_gram, word2idx in self._ngram2word2idx.items():
|
| 1148 |
+
if token in word2idx:
|
| 1149 |
+
return n_gram
|
| 1150 |
+
|
| 1151 |
+
return 0
|
| 1152 |
+
|
| 1153 |
+
def create_weight_tensor(self) -> torch.Tensor:
|
| 1154 |
+
unked_freqs = self._frequencies.most_common()
|
| 1155 |
+
|
| 1156 |
+
t = torch.ones(len(self))
|
| 1157 |
+
|
| 1158 |
+
for token, freq in unked_freqs:
|
| 1159 |
+
t[self._ngram2word2idx[self._token_to_n_order(token)][token]] = freq
|
| 1160 |
+
|
| 1161 |
+
# Ensure the only whitespace character is weighted
|
| 1162 |
+
t[self._ngram2word2idx[1][" "]] = 1.0
|
| 1163 |
+
|
| 1164 |
+
normed_weights = torch.tensor([(1 - (x / (max(t) + 1))).item() for x in t])
|
| 1165 |
+
|
| 1166 |
+
marker_tokens = [self.get_idx("<unk>", n) for n in range(1, self.ngram+1)]
|
| 1167 |
+
marker_tokens.extend([self.get_idx("<start>", n) for n in range(1, self.ngram+1)])
|
| 1168 |
+
# Instead of explicit ignore indexes, we use the weight vector and set target idxs to 0
|
| 1169 |
+
for marker in marker_tokens:
|
| 1170 |
+
normed_weights[marker] = 0
|
| 1171 |
+
|
| 1172 |
+
return normed_weights
|
| 1173 |
+
|
| 1174 |
+
class TestTokenizer(unittest.TestCase):
|
| 1175 |
+
|
| 1176 |
+
def test_one(self):
|
| 1177 |
+
vocab_file = "/home/phmaker/Projects/ngme/vocabs/1-gram-babylm.json"
|
| 1178 |
+
|
| 1179 |
+
t = NGMETokenizer(vocab_file)
|
| 1180 |
+
self.assertEqual(t.get_idx("<unk>", 1), 1)
|
| 1181 |
+
|
| 1182 |
+
result = t("hello world")
|
| 1183 |
+
self.assertEqual(result.input_ids, [16, 3, 11, 11, 8, 2, 21, 8, 9, 11, 12])
|
| 1184 |
+
|
| 1185 |
+
result = t("<unk>")
|
| 1186 |
+
self.assertEqual(result.input_ids, [1, 13, 5, 24, 1])
|
| 1187 |
+
|
| 1188 |
+
result = t(["hello world", "<unk>"])
|
| 1189 |
+
self.assertEqual(result.input_ids, [[16, 3, 11, 11, 8, 2, 21, 8, 9, 11, 12], [1, 13, 5, 24, 1]])
|
| 1190 |
+
|
| 1191 |
+
def test_three(self):
|
| 1192 |
+
vocab_file = "/home/phmaker/Projects/ngme/vocabs/3-gram-babylm.json"
|
| 1193 |
+
|
| 1194 |
+
t = NGMETokenizer(vocab_file)
|
| 1195 |
+
|
| 1196 |
+
result = t("hello world")
|
| 1197 |
+
self.assertEqual(result.input_ids, [16, 3, 11, 11, 8, 2, 21, 8, 9, 11, 12])
|
| 1198 |
+
|
| 1199 |
+
result = t("hello", return_ngram_sequences=True)
|
| 1200 |
+
|
| 1201 |
+
result = t(["hello world"], return_ngram_sequences=True)
|
| 1202 |
+
two_gram_expected = [[16, 208, 229, 230, 231, 1, 1, 312, 257, 499, 306]]
|
| 1203 |
+
|
| 1204 |
+
self.assertEqual(result["gram_2_sequence"], two_gram_expected)
|
| 1205 |
+
self.assertEqual(t._ngram2idx2word[1][16], "h")
|
| 1206 |
+
self.assertEqual(t._ngram2idx2word[2][208], "he")
|
| 1207 |
+
self.assertEqual(t._ngram2idx2word[2][229], "el")
|
| 1208 |
+
|
| 1209 |
+
def test_unks(self):
|
| 1210 |
+
vocab_file = "/home/phmaker/Projects/ngme/vocabs/2-gram-wiki-en.json"
|
| 1211 |
+
t = NGMETokenizer(vocab_file)
|
| 1212 |
+
result = t("OciVDjöShG", return_ngram_sequences=True, return_tensors="pt")
|
| 1213 |
+
|
| 1214 |
+
def test_decode(self):
|
| 1215 |
+
vocab_file = "/home/phmaker/Projects/ngme/vocabs/3-gram-babylm.json"
|
| 1216 |
+
t = NGMETokenizer(vocab_file)
|
| 1217 |
+
decoded = t.decode(208)
|
| 1218 |
+
assert decoded == "he"
|
| 1219 |
+
|
| 1220 |
+
def test_padding(self):
|
| 1221 |
+
vocab_file = "/home/phmaker/Projects/ngme/vocabs/3-gram-babylm.json"
|
| 1222 |
+
t = NGMETokenizer(vocab_file)
|
| 1223 |
+
result = t("hello world", return_tensors="pt", padding="max_length", max_length=20, return_ngram_sequences=True)
|
| 1224 |
+
|
| 1225 |
+
self.assertEqual(result.input_ids.shape, (1, 20))
|
| 1226 |
+
self.assertEqual(result.gram_2_sequence.shape, (1, 20))
|
| 1227 |
+
self.assertEqual(result.gram_3_sequence.shape, (1, 20))
|
| 1228 |
+
|
| 1229 |
+
def test_truncation(self):
|
| 1230 |
+
vocab_file = "/home/phmaker/Projects/ngme/vocabs/3-gram-babylm.json"
|
| 1231 |
+
t = NGMETokenizer(vocab_file)
|
| 1232 |
+
|
| 1233 |
+
result = t("hello world", return_tensors="pt", truncation=True, max_length=5, return_ngram_sequences=True)
|
| 1234 |
+
self.assertEqual(result.input_ids.shape, (1, 5))
|
| 1235 |
+
self.assertEqual(result.gram_2_sequence.shape, (1, 5))
|
| 1236 |
+
|
| 1237 |
+
|
| 1238 |
+
def test_padding_and_truncation(self):
|
| 1239 |
+
vocab_file = "/home/phmaker/Projects/ngme/vocabs/3-gram-babylm.json"
|
| 1240 |
+
t = NGMETokenizer(vocab_file)
|
| 1241 |
+
|
| 1242 |
+
result = t(["four", "something longer"], return_tensors="pt", padding="max_length", truncation=True, max_length=5, return_ngram_sequences=True)
|
| 1243 |
+
self.assertEqual(result.input_ids.shape, (2, 5))
|
| 1244 |
+
self.assertEqual(result.gram_2_sequence.shape, (2, 5))
|
| 1245 |
+
|
| 1246 |
+
|
| 1247 |
+
|
| 1248 |
+
if __name__ == "__main__":
|
| 1249 |
+
unittest.main()
|
| 1250 |
+
|