Text Generation
Transformers
PyTorch
Safetensors
longllama
text-generation-inference
custom_code
Szymon Tworkowski commited on
Commit
b65129a
1 Parent(s): a1db7a8

colab test

Browse files
config.json ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "LongLlamaForCausalLM"
4
+ ],
5
+ "bos_token_id": 1,
6
+ "eos_token_id": 2,
7
+ "hidden_act": "silu",
8
+ "hidden_size": 3200,
9
+ "initializer_range": 0.02,
10
+ "intermediate_size": 8640,
11
+ "max_position_embeddings": 2048,
12
+ "model_type": "longllama",
13
+ "num_attention_heads": 32,
14
+ "num_hidden_layers": 26,
15
+ "pad_token_id": 0,
16
+ "rms_norm_eps": 1e-06,
17
+ "tie_word_embeddings": false,
18
+ "torch_dtype": "bfloat16",
19
+ "transformers_version": "4.30.0",
20
+ "use_cache": true,
21
+ "vocab_size": 32000,
22
+ "auto_map": {
23
+ "AutoConfig": "configuration_longllama.LongLlamaConfig",
24
+ "AutoModel": "modeling_longllama.LongLlamaModel",
25
+ "AutoModelForCausalLM": "modeling_longllama.LongLlamaForCausalLM",
26
+ "AutoModelForSequenceClassification": "modeling_longllama.LongLlamaForSequenceClassification"
27
+ },
28
+ "mem_dtype": "bfloat16",
29
+ "mem_positionals": true,
30
+ "mem_layers": [
31
+ 6,
32
+ 12,
33
+ 18
34
+ ]
35
+ }
configuration_longllama.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 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
+ """ LongLLaMA model configuration"""
21
+
22
+ from transformers.configuration_utils import PretrainedConfig
23
+ from transformers.utils import logging
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+ LONGLLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP = {
29
+ "syzymon/long_llama_3b": "https://huggingface.co/syzymon/long_llama_3b/resolve/main/config.json",
30
+ }
31
+
32
+
33
+ class LongLlamaConfig(PretrainedConfig):
34
+ r"""
35
+ This is the configuration class to store the configuration of a [`LongLlamaModel`]. It is used to instantiate an LongLLaMA
36
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
37
+ defaults will yield a similar configuration to that of the LongLLaMA-7B.
38
+
39
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
40
+ documentation from [`PretrainedConfig`] for more information.
41
+
42
+
43
+ Args:
44
+ vocab_size (`int`, *optional*, defaults to 32000):
45
+ Vocabulary size of the LongLLaMA model. Defines the number of different tokens that can be represented by the
46
+ `inputs_ids` passed when calling [`LongLlamaModel`]
47
+ hidden_size (`int`, *optional*, defaults to 4096):
48
+ Dimension of the hidden representations.
49
+ intermediate_size (`int`, *optional*, defaults to 11008):
50
+ Dimension of the MLP representations.
51
+ num_hidden_layers (`int`, *optional*, defaults to 32):
52
+ Number of hidden layers in the Transformer encoder.
53
+ num_attention_heads (`int`, *optional*, defaults to 32):
54
+ Number of attention heads for each attention layer in the Transformer encoder.
55
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
56
+ The non-linear activation function (function or string) in the decoder.
57
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
58
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
59
+ just in case (e.g., 512 or 1024 or 2048).
60
+ initializer_range (`float`, *optional*, defaults to 0.02):
61
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
62
+ rms_norm_eps (`float`, *optional*, defaults to 1e-12):
63
+ The epsilon used by the rms normalization layers.
64
+ use_cache (`bool`, *optional*, defaults to `True`):
65
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
66
+ relevant if `config.is_decoder=True`.
67
+ tie_word_embeddings(`bool`, *optional*, defaults to `False`):
68
+ Whether to tie weight embeddings
69
+ mem_layers (`List[int]`, defaults to `[]`):
70
+ Layers with memory
71
+ mem_positionals (`bool`, *optional*, defaults to `True`):
72
+ Whether to use positional embeddings in memory layers
73
+ mem_dtype (`str`, *optional*, defaults to `"bfloat16"`):
74
+ Type for keys and values stored in memory
75
+ mem_attention_grouping (`Tuple[int, int]`, *optional*, defaults to `None`):
76
+ One can trade speed for memory by performing attention
77
+ in memory layers sequentially.
78
+ When equal to `(4, 2048)` the memory layers will process at most 4 heads and 2048 queries from each head at once.
79
+ That is at most 4*2048 queries at once.
80
+
81
+ Example:
82
+
83
+ ```python
84
+ >>> from transformers import LongLlamaModel, LongLlamaConfig
85
+
86
+ >>> # Initializing a LongLLaMA longllama-7b style configuration
87
+ >>> configuration = LongLlamaConfig()
88
+
89
+ >>> # Initializing a model from the longllama-7b style configuration
90
+ >>> model = LongLlamaModel(configuration)
91
+
92
+ >>> # Accessing the model configuration
93
+ >>> configuration = model.config
94
+ ```"""
95
+ model_type = "longllama"
96
+ keys_to_ignore_at_inference = ["past_key_values"]
97
+
98
+ def __init__(
99
+ self,
100
+ vocab_size=32000,
101
+ hidden_size=4096,
102
+ intermediate_size=11008,
103
+ num_hidden_layers=32,
104
+ num_attention_heads=32,
105
+ hidden_act="silu",
106
+ max_position_embeddings=2048,
107
+ initializer_range=0.02,
108
+ rms_norm_eps=1e-6,
109
+ use_cache=True,
110
+ pad_token_id=0,
111
+ bos_token_id=1,
112
+ eos_token_id=2,
113
+ tie_word_embeddings=False,
114
+ last_context_length=1024,
115
+ mem_layers=[],
116
+ mem_positionals=True,
117
+ mem_dtype="bfloat16",
118
+ mem_attention_grouping=None,
119
+ **kwargs,
120
+ ):
121
+ self.vocab_size = vocab_size
122
+ self.max_position_embeddings = max_position_embeddings
123
+ self.hidden_size = hidden_size
124
+ self.intermediate_size = intermediate_size
125
+ self.num_hidden_layers = num_hidden_layers
126
+ self.num_attention_heads = num_attention_heads
127
+ self.hidden_act = hidden_act
128
+ self.initializer_range = initializer_range
129
+ self.rms_norm_eps = rms_norm_eps
130
+ self.use_cache = use_cache
131
+ self.last_context_length = last_context_length
132
+ self.mem_layers = mem_layers
133
+ self.mem_positionals = mem_positionals
134
+ self.mem_dtype = mem_dtype
135
+ self.mem_attention_grouping = mem_attention_grouping
136
+ super().__init__(
137
+ pad_token_id=pad_token_id,
138
+ bos_token_id=bos_token_id,
139
+ eos_token_id=eos_token_id,
140
+ tie_word_embeddings=tie_word_embeddings,
141
+ **kwargs,
142
+ )
generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 2,
5
+ "pad_token_id": 0,
6
+ "transformers_version": "4.30.0"
7
+ }
longllama_utils.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import namedtuple
2
+ from dataclasses import dataclass
3
+ import torch
4
+ from typing import Tuple, Optional
5
+
6
+ @dataclass
7
+ class LongLlamaMemConfig:
8
+ """
9
+ Class for configuring memory caches for LongLlama model.
10
+
11
+ Args:
12
+ positionals (`boolean`)
13
+ Whether to use positional embeddings in memory layer
14
+ cache_dtype (`torch.dtype`)
15
+ Specifies storing type for keys and values
16
+ attention_grouping (`Tuple[int, int]`, *optional*)
17
+ One can trade speed for memory by performing attention
18
+ in memory layers sequentially.
19
+ When equal to `(4, 128)` the memory layers will process at most 4 heads and 128 queries
20
+ from each head at once. That is at most 512 queries at once.
21
+ """
22
+
23
+ positionals: bool = True
24
+ cache_dtype: torch.dtype = torch.bfloat16
25
+ attention_grouping: Optional[Tuple[int, int]] = None
26
+
27
+
28
+ @dataclass
29
+ class LongLlamaMemCache:
30
+ """
31
+ Class with LongLlama's memory cache
32
+
33
+ Args:
34
+ keys (`torch.FloatTensor` of shape `(batch_size, num_heads, mem_length, embed_size_per_head)`)
35
+ values (`torch.FloatTensor` of shape `(batch_size, num_heads, mem_length, embed_size_per_head)`)
36
+ masks (`torch.FloatTensor` of shape `(batch_size, 1, mem_length, 1)`)
37
+ For masking out parts of memory
38
+ """
39
+
40
+ keys: torch.FloatTensor
41
+ values: torch.FloatTensor
42
+ masks: torch.FloatTensor
43
+
44
+
45
+ def mem_apply_update(prev_mem_cache: LongLlamaMemCache, new_mem_content: LongLlamaMemCache, mem_config: LongLlamaMemConfig):
46
+ def update_one(prev, new):
47
+ if len(prev.shape) != 4 or len(new.shape) != 4:
48
+ raise ValueError(f"Memory cache content should be consistent in shape got {prev.shape} {new.shape}")
49
+
50
+ return torch.concat([prev, new], dim=-2)
51
+
52
+ insert_size = new_mem_content.keys.shape[-2]
53
+
54
+ if new_mem_content.values.shape[-2] != insert_size or new_mem_content.masks.shape[-2] != insert_size:
55
+ raise ValueError(f"Inconsistent mem_length in new_mem_content")
56
+
57
+ return LongLlamaMemCache(
58
+ keys=update_one(prev_mem_cache.keys, new_mem_content.keys),
59
+ values=update_one(prev_mem_cache.values, new_mem_content.values),
60
+ masks=update_one(prev_mem_cache.masks, new_mem_content.masks),
61
+ )
modeling_longllama.py ADDED
@@ -0,0 +1,1378 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 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 LongLLaMA model."""
21
+ from dataclasses import dataclass
22
+ import math
23
+ from typing import List, Optional, Tuple, Union
24
+
25
+ import torch
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 add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
34
+ from .configuration_longllama import LongLlamaConfig
35
+ from .longllama_utils import mem_apply_update, LongLlamaMemCache, LongLlamaMemConfig
36
+
37
+
38
+ logger = logging.get_logger(__name__)
39
+
40
+ _CONFIG_FOR_DOC = "LongLlamaConfig"
41
+
42
+
43
+ @dataclass
44
+ class LongLlamaModelOutputWithPast(BaseModelOutputWithPast):
45
+ """
46
+ Based on BaseModelOutputWithPast
47
+
48
+ Args:
49
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
50
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
51
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
52
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
53
+ mem_caches (`tuple(LongLlamaMemCache))`, *optional*, returned for layers with memory cache enabled):
54
+ For the layers without memory None is returned
55
+ """
56
+
57
+ mem_caches: Optional[LongLlamaMemCache] = None
58
+
59
+
60
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
61
+ def _make_causal_mask(
62
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
63
+ ):
64
+ """
65
+ Make causal mask used for bi-directional self-attention.
66
+ """
67
+ bsz, tgt_len = input_ids_shape
68
+ mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device)
69
+ mask_cond = torch.arange(mask.size(-1), device=device)
70
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
71
+ mask = mask.to(dtype)
72
+
73
+ if past_key_values_length > 0:
74
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
75
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
76
+
77
+
78
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
79
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
80
+ """
81
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
82
+ """
83
+ bsz, src_len = mask.size()
84
+ tgt_len = tgt_len if tgt_len is not None else src_len
85
+
86
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
87
+
88
+ inverted_mask = 1.0 - expanded_mask
89
+
90
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
91
+
92
+
93
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->LongLlama
94
+ class LongLlamaRMSNorm(nn.Module):
95
+ def __init__(self, hidden_size, eps=1e-6):
96
+ """
97
+ LongLlamaRMSNorm is equivalent to T5LayerNorm
98
+ """
99
+ super().__init__()
100
+ self.weight = nn.Parameter(torch.ones(hidden_size))
101
+ self.variance_epsilon = eps
102
+
103
+ def forward(self, hidden_states):
104
+ input_dtype = hidden_states.dtype
105
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
106
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
107
+
108
+ return (self.weight * hidden_states).to(input_dtype)
109
+
110
+
111
+ # Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->LongLlama
112
+ class LongLlamaRotaryEmbedding(torch.nn.Module):
113
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
114
+ super().__init__()
115
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
116
+ self.register_buffer("inv_freq", inv_freq)
117
+
118
+ # Build here to make `torch.jit.trace` work.
119
+ self.max_seq_len_cached = max_position_embeddings
120
+ t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
121
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
122
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
123
+ emb = torch.cat((freqs, freqs), dim=-1)
124
+ dtype = torch.get_default_dtype()
125
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)
126
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)
127
+
128
+ def forward(self, x, seq_len=None):
129
+ # x: [bs, num_attention_heads, seq_len, head_size]
130
+ # This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
131
+ if seq_len > self.max_seq_len_cached:
132
+ self.max_seq_len_cached = seq_len
133
+ t = torch.arange(self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype)
134
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
135
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
136
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
137
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(x.dtype), persistent=False)
138
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(x.dtype), persistent=False)
139
+ return (
140
+ self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
141
+ self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
142
+ )
143
+
144
+
145
+ def rotate_half(x):
146
+ """Rotates half the hidden dims of the input."""
147
+ x1 = x[..., : x.shape[-1] // 2]
148
+ x2 = x[..., x.shape[-1] // 2 :]
149
+ return torch.cat((-x2, x1), dim=-1)
150
+
151
+
152
+ # Based on transformers.models.llama.modeling_llama.apply_rotary_pos_emb
153
+ def rotate_one(x, cos, sin, position_ids):
154
+ if len(position_ids.shape) != 2 or x.shape[0] != position_ids.shape[0] or x.shape[-2] != position_ids.shape[1]:
155
+ raise ValueError(f"Position ids shoud have shape [bsz, seq_len] got {position_ids.shape}")
156
+ # The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
157
+ cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
158
+ sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
159
+ cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
160
+ sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
161
+ x_embed = (x * cos) + (rotate_half(x) * sin)
162
+ return x_embed
163
+
164
+
165
+ def rotate_as_if_first(x, rotary_emb):
166
+ # x: [bs, num_attention_heads, seq_len, head_size]
167
+ # apply rotary as if all elements were first in the sequence
168
+ cos, sin = rotary_emb(x, x.shape[-2])
169
+ return rotate_one(x, cos, sin, torch.zeros(x.shape[0], x.shape[-2], dtype=torch.long, device=cos.device))
170
+
171
+
172
+ # Copied from transformers.models.llama.modeling_llama.LlamaMLP with Llama->LongLlama
173
+ class LongLlamaMLP(nn.Module):
174
+ def __init__(
175
+ self,
176
+ hidden_size: int,
177
+ intermediate_size: int,
178
+ hidden_act: str,
179
+ ):
180
+ super().__init__()
181
+ self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
182
+ self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
183
+ self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
184
+ self.act_fn = ACT2FN[hidden_act]
185
+
186
+ def forward(self, x):
187
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
188
+
189
+
190
+ # Modified transformers.models.llama.modeling_llama.LlamaAttention
191
+ class LongLlamaAttention(nn.Module):
192
+ """Multi-headed attention from 'Attention Is All You Need' paper with FoT modifications"""
193
+
194
+ def __init__(self, config: LongLlamaConfig, mem_config: Optional[LongLlamaMemConfig] = None):
195
+ super().__init__()
196
+ self.config = config
197
+ self.hidden_size = config.hidden_size
198
+ self.num_heads = config.num_attention_heads
199
+ self.head_dim = self.hidden_size // self.num_heads
200
+ self.max_position_embeddings = config.max_position_embeddings
201
+ self.max_cache = self.max_position_embeddings
202
+
203
+ if (self.head_dim * self.num_heads) != self.hidden_size:
204
+ raise ValueError(
205
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
206
+ f" and `num_heads`: {self.num_heads})."
207
+ )
208
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
209
+ self.k_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
210
+ self.v_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
211
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
212
+ self.rotary_emb = LongLlamaRotaryEmbedding(self.head_dim, max_position_embeddings=self.max_position_embeddings)
213
+ self.mem_config = mem_config
214
+
215
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
216
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
217
+
218
+ def forward(
219
+ self,
220
+ hidden_states: torch.Tensor,
221
+ attention_mask: Optional[torch.Tensor] = None,
222
+ position_ids: Optional[torch.LongTensor] = None,
223
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
224
+ output_attentions: bool = False,
225
+ use_cache: bool = False,
226
+ mem_cache: Optional[LongLlamaMemCache] = None,
227
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
228
+ if attention_mask is None:
229
+ tgt_seq_len = hidden_states.shape[-2]
230
+ if past_key_value is not None:
231
+ src_seq_len = past_key_value[0].shape[-2] + tgt_seq_len
232
+ else:
233
+ src_seq_len = tgt_seq_len
234
+
235
+ attention_mask = torch.zeros(
236
+ hidden_states.shape[0],
237
+ 1,
238
+ tgt_seq_len,
239
+ src_seq_len,
240
+ device=hidden_states.device,
241
+ dtype=hidden_states.dtype,
242
+ )
243
+ bsz, q_len, _ = hidden_states.size()
244
+
245
+ query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
246
+ key_states = self.k_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
247
+ value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
248
+ position_ids = position_ids[:, None, :, None]
249
+
250
+ if position_ids.shape != (key_states.shape[0], 1, key_states.shape[-2], 1):
251
+ raise ValueError("position_ids should match batch and seq_len of the input")
252
+
253
+ mem_no_local_cache = self.mem_config is not None and past_key_value is None and (not use_cache)
254
+ mem_and_local_cache = self.mem_config is not None and use_cache
255
+ # positonal embeddings can be disabled for memory layers
256
+ use_positionals = self.mem_config is None or self.mem_config.positionals
257
+
258
+ if mem_no_local_cache:
259
+ # the whole context window will be moved to memory cache after the attention
260
+ if use_positionals:
261
+ # positionally embedd memory content as first token in the sequence
262
+ rfst_key_states = rotate_as_if_first(key_states, self.rotary_emb)
263
+ else:
264
+ rfst_key_states = key_states
265
+ # attention_mask [bsz, 1, tgt_seq_len, src_seq_len]
266
+ # we base the mask on the last token in the context window
267
+ mem_update = LongLlamaMemCache(
268
+ keys=rfst_key_states.to(self.mem_config.cache_dtype),
269
+ values=value_states.to(self.mem_config.cache_dtype),
270
+ masks=attention_mask[..., -1, :, None],
271
+ )
272
+
273
+ if past_key_value is not None:
274
+ past_local_cache_size = past_key_value[0].shape[-2]
275
+ key_states = torch.cat([past_key_value[0], key_states], dim=-2)
276
+ value_states = torch.cat([past_key_value[1], value_states], dim=-2)
277
+ # FoT additionally stores position_ids to support long inputs
278
+ position_ids = torch.cat([past_key_value[2], position_ids], dim=-2)
279
+
280
+ if attention_mask.shape[-1] != key_states.shape[-2] and attention_mask.shape[-2] != query_states.shape[-2]:
281
+ raise ValueError("attention_mask should be provided for all key_states in local context")
282
+
283
+ # local cache is maintained so that it is <= self.max_cache
284
+ # remaining elements are either dropped or go to memory cache
285
+ if key_states.shape[-2] > self.max_cache:
286
+ num_elems_to_drop = past_local_cache_size
287
+
288
+ if mem_and_local_cache:
289
+ drop_keys = key_states[:, :, :num_elems_to_drop, :]
290
+ drop_values = value_states[:, :, :num_elems_to_drop, :]
291
+ # as memory mask use the masking of the last key in context
292
+ # attention_mask [bsz, 1, tgt_seq_len, src_seq_len]
293
+ drop_masks = attention_mask[..., -1, :, None]
294
+ drop_masks = drop_masks[:, :, :num_elems_to_drop, :]
295
+
296
+ if use_positionals:
297
+ rfst_drop_keys = rotate_as_if_first(drop_keys, self.rotary_emb)
298
+ else:
299
+ rfst_drop_keys = drop_keys
300
+ mem_update = LongLlamaMemCache(
301
+ keys=rfst_drop_keys.to(self.mem_config.cache_dtype),
302
+ values=drop_values.to(self.mem_config.cache_dtype),
303
+ masks=drop_masks,
304
+ )
305
+ if mem_cache is None:
306
+ mem_cache = mem_update
307
+ else:
308
+ mem_cache = mem_apply_update(
309
+ prev_mem_cache=mem_cache, new_mem_content=mem_update, mem_config=self.mem_config
310
+ )
311
+
312
+ key_states = key_states[:, :, num_elems_to_drop:, :]
313
+ value_states = value_states[:, :, num_elems_to_drop:, :]
314
+ position_ids = position_ids[:, :, num_elems_to_drop:, :]
315
+ attention_mask = attention_mask[..., num_elems_to_drop:]
316
+
317
+
318
+ # FoT additionally stores position_ids to support long inputs
319
+ past_key_value = (key_states, value_states, position_ids) if use_cache else None
320
+
321
+ kv_seq_len = key_states.shape[-2]
322
+
323
+ if use_positionals:
324
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
325
+ rel_pos_ids = position_ids - torch.min(position_ids, dim=-2, keepdim=True)[0]
326
+ rel_pos_ids = rel_pos_ids.squeeze(3).squeeze(1)
327
+
328
+ query_states = rotate_one(query_states, cos, sin, rel_pos_ids[:, -query_states.shape[-2] :])
329
+ key_states = rotate_one(key_states, cos, sin, rel_pos_ids)
330
+
331
+
332
+ if self.mem_config is not None and self.mem_config.attention_grouping is not None:
333
+ attn_grouping_h, attn_grouping_q = self.mem_config.attention_grouping
334
+ if attn_grouping_h <= 0 or attn_grouping_q <= 0:
335
+ raise ValueError("Attention grouping should be positive")
336
+ else:
337
+ attn_grouping_h, attn_grouping_q = self.num_heads, q_len
338
+
339
+
340
+ attn_output_h = []
341
+ for beg_h in range(0, self.num_heads, attn_grouping_h):
342
+ end_h = min(beg_h + attn_grouping_h, self.num_heads)
343
+
344
+ attn_output_q = []
345
+ for beg_q in range(0, q_len, attn_grouping_q):
346
+ end_q = min(beg_q + attn_grouping_q, q_len)
347
+
348
+ attn_weights = torch.matmul(query_states[:, beg_h:end_h, beg_q:end_q], key_states[:, beg_h:end_h].transpose(2, 3)) / math.sqrt(self.head_dim)
349
+
350
+ if attn_weights.size() != (bsz, end_h - beg_h, end_q - beg_q, kv_seq_len):
351
+ raise ValueError(
352
+ f"Attention weights should be of size {(bsz, end_h - beg_h, end_q - beg_q, kv_seq_len)}, but is"
353
+ f" {attn_weights.size()}"
354
+ )
355
+
356
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
357
+ raise ValueError(
358
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
359
+ )
360
+ attn_weights = attn_weights + attention_mask[:, :, beg_q:end_q]
361
+ min_value = torch.finfo(attn_weights.dtype).min if -1000000.0 < torch.finfo(attn_weights.dtype).min else -1000000.0
362
+ attn_weights = torch.max(attn_weights, torch.tensor(min_value, device=attn_weights.device, dtype=attn_weights.dtype))
363
+
364
+ if mem_cache is not None:
365
+ mem_mask = mem_cache.masks.squeeze(-1).unsqueeze(-2)
366
+ mem_attn_weights = torch.matmul(
367
+ query_states[:, beg_h:end_h, beg_q:end_q], mem_cache.keys[:, beg_h:end_h].transpose(2, 3).to(key_states.dtype)
368
+ ) / math.sqrt(self.head_dim)
369
+
370
+ assert mem_mask.shape[2] == 1
371
+ mem_attn_weights = mem_attn_weights + mem_mask
372
+ min_value = torch.finfo(mem_attn_weights.dtype).min if -1000000.0 < torch.finfo(mem_attn_weights.dtype).min else -1000000.0
373
+ mem_attn_weights = torch.max(mem_attn_weights, torch.tensor(min_value, device=mem_attn_weights.device, dtype=mem_attn_weights.dtype))
374
+
375
+ attn_weights = torch.concat([attn_weights, mem_attn_weights], dim=-1)
376
+ combined_value_states = torch.concat([value_states[:, beg_h:end_h], mem_cache.values[:, beg_h:end_h].to(value_states.dtype)], dim=-2)
377
+ else:
378
+ combined_value_states = value_states[:, beg_h:end_h]
379
+ # upcast attention to fp32
380
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
381
+ attn_output = torch.matmul(attn_weights, combined_value_states)
382
+ assert attn_output.shape[-2] == end_q - beg_q
383
+ attn_output_q.append(attn_output)
384
+ attn_output_h.append(torch.concat(attn_output_q, dim=-2))
385
+
386
+ attn_output = torch.concat(attn_output_h, dim=-3)
387
+
388
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
389
+ raise ValueError(
390
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
391
+ f" {attn_output.size()}"
392
+ )
393
+
394
+ attn_output = attn_output.transpose(1, 2)
395
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
396
+
397
+ attn_output = self.o_proj(attn_output)
398
+
399
+ if not output_attentions:
400
+ attn_weights = None
401
+
402
+ if mem_no_local_cache:
403
+ if mem_cache is not None:
404
+ mem_cache = mem_apply_update(prev_mem_cache=mem_cache, new_mem_content=mem_update, mem_config=self.mem_config)
405
+ else:
406
+ mem_cache = mem_update
407
+
408
+ return attn_output, attn_weights, past_key_value, mem_cache
409
+
410
+
411
+ # Modified transformers.models.llama.modeling_llama.LlamaDecoderLayer
412
+ class LongLlamaDecoderLayer(nn.Module):
413
+ def __init__(self, config: LongLlamaConfig, mem_config: Optional[LongLlamaMemConfig] = None):
414
+ super().__init__()
415
+ self.hidden_size = config.hidden_size
416
+ self.self_attn = LongLlamaAttention(config=config, mem_config=mem_config)
417
+ self.mlp = LongLlamaMLP(
418
+ hidden_size=self.hidden_size,
419
+ intermediate_size=config.intermediate_size,
420
+ hidden_act=config.hidden_act,
421
+ )
422
+ self.input_layernorm = LongLlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
423
+ self.post_attention_layernorm = LongLlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
424
+
425
+ def forward(
426
+ self,
427
+ hidden_states: torch.Tensor,
428
+ attention_mask: Optional[torch.Tensor] = None,
429
+ position_ids: Optional[torch.LongTensor] = None,
430
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
431
+ output_attentions: Optional[bool] = False,
432
+ use_cache: Optional[bool] = False,
433
+ mem_cache: Optional[LongLlamaMemCache] = None,
434
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
435
+ """
436
+ Args:
437
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
438
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
439
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
440
+ output_attentions (`bool`, *optional*):
441
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
442
+ returned tensors for more detail.
443
+ use_cache (`bool`, *optional*):
444
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
445
+ (see `past_key_values`).
446
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
447
+ along with information about positions
448
+ mem_cache (`LongLlamaMemCache`, *optional*): memory cache for specific layers
449
+ """
450
+
451
+ residual = hidden_states
452
+
453
+ hidden_states = self.input_layernorm(hidden_states)
454
+
455
+ # Self Attention
456
+ hidden_states, self_attn_weights, present_key_value, mem_cache = self.self_attn(
457
+ hidden_states=hidden_states,
458
+ attention_mask=attention_mask,
459
+ position_ids=position_ids,
460
+ past_key_value=past_key_value,
461
+ output_attentions=output_attentions,
462
+ use_cache=use_cache,
463
+ mem_cache=mem_cache,
464
+ )
465
+ hidden_states = residual + hidden_states
466
+
467
+ # Fully Connected
468
+ residual = hidden_states
469
+ hidden_states = self.post_attention_layernorm(hidden_states)
470
+ hidden_states = self.mlp(hidden_states)
471
+ hidden_states = residual + hidden_states
472
+
473
+ outputs = (hidden_states,)
474
+
475
+ if output_attentions:
476
+ outputs += (self_attn_weights,)
477
+
478
+ if use_cache:
479
+ outputs += (present_key_value,)
480
+
481
+ return outputs, mem_cache
482
+
483
+
484
+ LONGLLAMA_START_DOCSTRING = r"""
485
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
486
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
487
+ etc.)
488
+
489
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
490
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
491
+ and behavior.
492
+
493
+ Parameters:
494
+ config ([`LongLlamaConfig`]):
495
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
496
+ load the weights associated with the model, only the configuration. Check out the
497
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
498
+ """
499
+ LONGLLAMA_MEML_DOCSTRING = r"""
500
+ mem_layers ([`int`], *optional*):
501
+ Indices of layers to be augmented with memory, if None then parameters from config will be used
502
+ mem_dtype (`str`, *optional*):
503
+ Keys and values will be casted to this type for storage.
504
+
505
+ """
506
+
507
+
508
+ @add_start_docstrings(
509
+ "The bare LongLLaMA Model outputting raw hidden-states without any specific head on top.",
510
+ LONGLLAMA_START_DOCSTRING,
511
+ )
512
+ # Copied from transformers.models.llama.modeling_llama.LlamaPreTrainedModel with Llama->LongLlama
513
+ class LongLlamaPreTrainedModel(PreTrainedModel):
514
+ config_class = LongLlamaConfig
515
+ base_model_prefix = "model"
516
+ supports_gradient_checkpointing = True
517
+ _no_split_modules = ["LongLlamaDecoderLayer"]
518
+ _skip_keys_device_placement = "past_key_values"
519
+ _keys_to_ignore_on_load_unexpected = [r"decoder\.version"]
520
+
521
+ def _init_weights(self, module):
522
+ std = self.config.initializer_range
523
+ if isinstance(module, nn.Linear):
524
+ module.weight.data.normal_(mean=0.0, std=std)
525
+ if module.bias is not None:
526
+ module.bias.data.zero_()
527
+ elif isinstance(module, nn.Embedding):
528
+ module.weight.data.normal_(mean=0.0, std=std)
529
+ if module.padding_idx is not None:
530
+ module.weight.data[module.padding_idx].zero_()
531
+
532
+ def _set_gradient_checkpointing(self, module, value=False):
533
+ if isinstance(module, LongLlamaModel):
534
+ module.gradient_checkpointing = value
535
+
536
+
537
+ LONGLLAMA_COMMON_INPUTS_DOCSTRING = r"""
538
+ Args:
539
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
540
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
541
+ it.
542
+
543
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
544
+ [`PreTrainedTokenizer.__call__`] for details.
545
+
546
+ [What are input IDs?](../glossary#input-ids)
547
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
548
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
549
+
550
+ - 1 for tokens that are **not masked**,
551
+ - 0 for tokens that are **masked**.
552
+
553
+ [What are attention masks?](../glossary#attention-mask)
554
+
555
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
556
+ [`PreTrainedTokenizer.__call__`] for details.
557
+
558
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
559
+ `past_key_values`).
560
+
561
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
562
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
563
+ information on the default strategy.
564
+
565
+ - 1 indicates the head is **not masked**,
566
+ - 0 indicates the head is **masked**.
567
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
568
+ Indices of positions of each input sequence tokens in the position embeddings.
569
+
570
+ [What are position IDs?](../glossary#position-ids)
571
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`
572
+ or memory cache is enabled):
573
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
574
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 1 additional tensor of shape
575
+ `(batch_size, 1, sequence_length, 1)`. For memory enriched layers it also contains content of memory cache.
576
+ It is padded with empty tensors so when returned it alwyas has 6 elements.
577
+
578
+ Contains pre-computed hidden-states (key and values in the self-attention blocks)
579
+ that can be used (see `past_key_values` input) to speed up sequential decoding.
580
+
581
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
582
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
583
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
584
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
585
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
586
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
587
+ model's internal embedding lookup matrix.
588
+ use_cache (`bool`, *optional*):
589
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
590
+ `past_key_values`).
591
+ output_attentions (`bool`, *optional*):
592
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
593
+ tensors for more detail. This is NOT supported in LongLlamaForCausalLM and LongLlamaForSequenceClassification
594
+ due to the specific input processing.
595
+ output_hidden_states (`bool`, *optional*):
596
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
597
+ more detail.
598
+ return_dict (`bool`, *optional*):
599
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
600
+ """
601
+ LONGLLAMA_MODEL_INPUTS_DOCSTRING = r"""
602
+ mem_caches (`tuple(LongLlamaMemCache)`, *optional*)
603
+ Memory caches for specified layers, None for others
604
+ """
605
+
606
+ LONGLLAMA_ADD_INPUTS_DOCSTRING = r"""
607
+ last_context_length (`int`, *optional*)
608
+ Useful for generation, specifies number of tokens that won't be loaded to memory and
609
+ will be left for generation cache
610
+ """
611
+
612
+
613
+ def _prepare_pos_ids(past_key_values, batch_size, input_length, device):
614
+ if past_key_values is not None:
615
+ # take previous max pos_id + 1
616
+ if past_key_values[0][2].shape[0] != batch_size:
617
+ raise ValueError(f"first dimension of past_key_values should match batch size: {batch_size}"
618
+ f"but got {past_key_values[0][2].shape[0]}")
619
+ next_pos = torch.max(past_key_values[0][2].view(batch_size, -1), dim=-1)[0] + 1
620
+ next_pos = next_pos.view(batch_size, 1)
621
+ else:
622
+ next_pos = torch.zeros(batch_size, 1, device=device, dtype=torch.long)
623
+
624
+ position_ids = torch.arange(0, input_length, dtype=torch.long, device=device).view(1, input_length)
625
+ position_ids = position_ids + next_pos
626
+ return position_ids
627
+
628
+
629
+ @add_start_docstrings(
630
+ "The bare LongLLaMA Model outputting raw hidden-states without any specific head on top.",
631
+ LONGLLAMA_START_DOCSTRING,
632
+ LONGLLAMA_MEML_DOCSTRING,
633
+ )
634
+ # Modified transformers.models.llama.modeling_llama.LlamaModel
635
+ class LongLlamaModel(LongLlamaPreTrainedModel):
636
+ """
637
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LongLlamaDecoderLayer`]
638
+
639
+ Args:
640
+ config: LlamaConfig
641
+ """
642
+
643
+ def __init__(self, config: LongLlamaConfig):
644
+ super().__init__(config)
645
+ self.mem_layers = config.mem_layers
646
+ self.mem_config = LongLlamaMemConfig(positionals=config.mem_positionals, cache_dtype=getattr(torch, config.mem_dtype), attention_grouping=config.mem_attention_grouping)
647
+ self.padding_idx = config.pad_token_id
648
+ self.vocab_size = config.vocab_size
649
+
650
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
651
+
652
+
653
+
654
+ for mem_layer_id in self.mem_layers :
655
+ if mem_layer_id < 0 or mem_layer_id >= config.num_hidden_layers:
656
+ raise ValueError(f"Memory layer ids should be between 0 and {config.num_hidden_layers}, got {mem_layer_id}")
657
+
658
+ layers = []
659
+ for layer_id in range(config.num_hidden_layers):
660
+ if layer_id in self.mem_layers:
661
+ layer = LongLlamaDecoderLayer(config, mem_config=self.mem_config)
662
+ else:
663
+ layer = LongLlamaDecoderLayer(config, mem_config=None)
664
+ layers.append(layer)
665
+
666
+ self.layers = nn.ModuleList(layers)
667
+ self.norm = LongLlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
668
+
669
+ self.gradient_checkpointing = False
670
+
671
+ # Initialize weights and apply final processing
672
+ self.post_init()
673
+
674
+ def get_input_embeddings(self):
675
+ return self.embed_tokens
676
+
677
+ def set_input_embeddings(self, value):
678
+ self.embed_tokens = value
679
+
680
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
681
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
682
+ # create causal mask
683
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
684
+ combined_attention_mask = None
685
+ if input_shape[-1] > 1:
686
+ combined_attention_mask = _make_causal_mask(
687
+ input_shape,
688
+ inputs_embeds.dtype,
689
+ device=inputs_embeds.device,
690
+ past_key_values_length=past_key_values_length,
691
+ )
692
+
693
+ if attention_mask is not None:
694
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
695
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
696
+ inputs_embeds.device
697
+ )
698
+ combined_attention_mask = (
699
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
700
+ )
701
+
702
+ return combined_attention_mask
703
+
704
+ @add_start_docstrings_to_model_forward(LONGLLAMA_COMMON_INPUTS_DOCSTRING, LONGLLAMA_MODEL_INPUTS_DOCSTRING)
705
+ def forward(
706
+ self,
707
+ input_ids: torch.LongTensor = None,
708
+ attention_mask: Optional[torch.Tensor] = None,
709
+ position_ids: Optional[torch.LongTensor] = None,
710
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
711
+ inputs_embeds: Optional[torch.FloatTensor] = None,
712
+ use_cache: Optional[bool] = None,
713
+ output_attentions: Optional[bool] = None,
714
+ output_hidden_states: Optional[bool] = None,
715
+ return_dict: Optional[bool] = None,
716
+ mem_caches: Optional[Tuple[Optional[LongLlamaMemCache]]] = None,
717
+ ) -> Union[Tuple, LongLlamaModelOutputWithPast]:
718
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
719
+ output_hidden_states = (
720
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
721
+ )
722
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
723
+
724
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
725
+
726
+ # retrieve input_ids and inputs_embeds
727
+ if input_ids is not None and inputs_embeds is not None:
728
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
729
+ elif input_ids is not None:
730
+ batch_size, seq_length = input_ids.shape
731
+ elif inputs_embeds is not None:
732
+ batch_size, seq_length, _ = inputs_embeds.shape
733
+ else:
734
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
735
+
736
+ seq_length_with_past = seq_length
737
+ past_key_values_length = 0
738
+
739
+ if past_key_values is not None:
740
+ past_key_values_length = past_key_values[0][0].shape[-2]
741
+ seq_length_with_past = seq_length_with_past + past_key_values_length
742
+
743
+ if position_ids is None:
744
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
745
+ position_ids = _prepare_pos_ids(past_key_values, batch_size, seq_length, device)
746
+ else:
747
+ position_ids = position_ids.view(-1, seq_length).long()
748
+
749
+ if inputs_embeds is None:
750
+ inputs_embeds = self.embed_tokens(input_ids)
751
+ # embed positions
752
+ if attention_mask is None:
753
+ attention_mask = torch.ones(
754
+ (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
755
+ )
756
+ attention_mask = self._prepare_decoder_attention_mask(
757
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
758
+ )
759
+
760
+ hidden_states = inputs_embeds
761
+
762
+ if self.gradient_checkpointing and self.training:
763
+ if use_cache:
764
+ logger.warning_once(
765
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
766
+ )
767
+ use_cache = False
768
+
769
+ # decoder layers
770
+ all_hidden_states = () if output_hidden_states else None
771
+ all_self_attns = () if output_attentions else None
772
+ next_decoder_cache = ()
773
+ next_mem_caches = ()
774
+ for idx, decoder_layer in enumerate(self.layers):
775
+ if output_hidden_states:
776
+ all_hidden_states += (hidden_states,)
777
+
778
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
779
+ mem_cache = mem_caches[idx] if mem_caches else None
780
+
781
+ if self.gradient_checkpointing and self.training:
782
+
783
+ if mem_cache is not None:
784
+ raise ValueError("Gradient checkpointing is not supported on memory layers")
785
+
786
+ def create_custom_forward(module):
787
+ def custom_forward(*inputs):
788
+ # None for past_key_value
789
+ return module(*inputs, output_attentions, None, mem_cache=None)
790
+
791
+ return custom_forward
792
+
793
+ layer_outputs = torch.utils.checkpoint.checkpoint(
794
+ create_custom_forward(decoder_layer),
795
+ hidden_states,
796
+ attention_mask,
797
+ position_ids,
798
+ None,
799
+ )
800
+ else:
801
+ layer_outputs = decoder_layer(
802
+ hidden_states,
803
+ attention_mask=attention_mask,
804
+ position_ids=position_ids,
805
+ past_key_value=past_key_value,
806
+ output_attentions=output_attentions,
807
+ use_cache=use_cache,
808
+ mem_cache=mem_cache,
809
+ )
810
+
811
+ layer_outputs, new_mem_cache = layer_outputs
812
+ next_mem_caches += (new_mem_cache,)
813
+
814
+ hidden_states = layer_outputs[0]
815
+
816
+ if use_cache:
817
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
818
+ else:
819
+ next_decoder_cache += (None,)
820
+
821
+ if output_attentions:
822
+ all_self_attns += (layer_outputs[1],)
823
+
824
+ hidden_states = self.norm(hidden_states)
825
+
826
+ # add hidden states from the last decoder layer
827
+ if output_hidden_states:
828
+ all_hidden_states += (hidden_states,)
829
+
830
+ next_cache = next_decoder_cache if use_cache else None
831
+
832
+ mem_cache_returned = False
833
+ for mem_cache in next_mem_caches:
834
+ if mem_cache is not None:
835
+ mem_cache_returned = True
836
+ next_mem_caches = next_mem_caches if mem_cache_returned else None
837
+
838
+ if not return_dict:
839
+ return tuple(
840
+ v
841
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, next_mem_caches]
842
+ if v is not None
843
+ )
844
+ return LongLlamaModelOutputWithPast(
845
+ last_hidden_state=hidden_states,
846
+ past_key_values=next_cache,
847
+ hidden_states=all_hidden_states,
848
+ attentions=all_self_attns,
849
+ mem_caches=next_mem_caches,
850
+ )
851
+
852
+
853
+ def _handle_output_of_past_key_values(outputs):
854
+ # merges local caches and memory caches into one single tuple of past_key_values
855
+ # in order to support generation
856
+ batch_size = outputs.last_hidden_state.shape[0]
857
+ if outputs.past_key_values is None and outputs.mem_caches is None:
858
+ return None
859
+
860
+ if outputs.past_key_values is None:
861
+ out_past_key_values = (None,) * len(outputs.mem_caches)
862
+ else:
863
+ out_past_key_values = outputs.past_key_values
864
+
865
+ if outputs.mem_caches is None:
866
+ out_mem_caches = (None,) * len(outputs.past_key_values)
867
+ else:
868
+ out_mem_caches = outputs.mem_caches
869
+
870
+ device = outputs.last_hidden_state.device
871
+ past_key_values = ()
872
+ for local_cache, mem_cache in zip(out_past_key_values, out_mem_caches):
873
+ layer = ()
874
+ if local_cache is not None:
875
+ assert len(local_cache) == 3
876
+ layer += local_cache
877
+ else:
878
+ layer += (torch.empty(batch_size, 0, 0, 0, device=device),) * 3
879
+
880
+ if mem_cache is not None:
881
+ layer += (mem_cache.keys, mem_cache.values, mem_cache.masks)
882
+ else:
883
+ layer += (torch.empty(batch_size, 0, 0, 0, device=device),) * 3
884
+
885
+ assert len(layer) == 6
886
+
887
+ past_key_values += (layer,)
888
+
889
+ return past_key_values
890
+
891
+
892
+ def _split_past_key_values(past_key_values):
893
+ # splits past_key_values to local cache and memory cache
894
+ local_cache_preset = False
895
+ mem_caches_present = False
896
+ if past_key_values is not None:
897
+ local_caches = ()
898
+ mem_caches = ()
899
+ for layer in past_key_values:
900
+ if len(layer) != 6:
901
+ raise ValueError(
902
+ "Expected elements of past_key_values to contain 6 elements."
903
+ "First 3 describing local cache and last 3 describing memory cache."
904
+ f"Instead got {len(layer)} elements"
905
+ )
906
+ else:
907
+ lk, lv, li, memk, memv, memm = layer
908
+ if lk.shape[-2] != 0:
909
+ local_cache_preset = True
910
+ local_caches += ((lk, lv, li),)
911
+ else:
912
+ local_caches += (None,)
913
+
914
+ if memk.shape[-2] != 0:
915
+ mem_caches_present = True
916
+ mem_caches += (LongLlamaMemCache(keys=memk, values=memv, masks=memm),)
917
+ else:
918
+ mem_caches += (None,)
919
+
920
+ local_caches = local_caches if local_cache_preset else None
921
+ mem_caches = mem_caches if mem_caches_present else None
922
+
923
+ return local_caches, mem_caches
924
+
925
+
926
+ def _handle_long_input(
927
+ model,
928
+ input_ids,
929
+ attention_mask,
930
+ position_ids,
931
+ past_key_values,
932
+ inputs_embeds,
933
+ use_cache,
934
+ output_attentions,
935
+ output_hidden_states,
936
+ return_dict,
937
+ context_window_length,
938
+ last_context_length,
939
+ ):
940
+ if output_attentions:
941
+ logger.warning(f"Outputing attentions is not supported in LongLlamaForCausalLM and LongLlamaForSequenceClassification. "
942
+ f"Attention of the last window will be returned")
943
+
944
+ past_key_values, mem_caches = _split_past_key_values(past_key_values)
945
+
946
+ if past_key_values is not None and use_cache is False:
947
+ raise ValueError("past_key_values it not None should imply use_cache == True")
948
+
949
+ if past_key_values is not None:
950
+ initial_past_key_values_length = past_key_values[0][0].shape[-2]
951
+ else:
952
+ initial_past_key_values_length = 0
953
+
954
+ if input_ids is not None:
955
+ batch_size, input_length = input_ids.shape
956
+ else:
957
+ batch_size, input_length, _ = inputs_embeds.shape
958
+
959
+ if position_ids is None:
960
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
961
+ position_ids = _prepare_pos_ids(past_key_values, batch_size, input_length, device)
962
+
963
+ if position_ids.shape != (batch_size, input_length):
964
+ raise ValueError(f"Shape of position_ids [{position_ids}] should match [{batch_size, input_length}]")
965
+
966
+ if attention_mask is not None:
967
+ attention_mask = attention_mask[..., -(initial_past_key_values_length + input_length) :]
968
+ if attention_mask is not None and (
969
+ attention_mask.shape != (batch_size, initial_past_key_values_length + input_length)
970
+ ):
971
+ raise ValueError(
972
+ "Attention mask should be provided for both the local cache and the input",
973
+ f"Expected shape {(batch_size, initial_past_key_values_length + input_length)},"
974
+ f"got {attention_mask.shape}.",
975
+ )
976
+
977
+ # First we load prefix to memory cache
978
+ mem_input_length = max(input_length - last_context_length, 0)
979
+ outputs_list = []
980
+ attn_offset = initial_past_key_values_length
981
+ if mem_input_length > 0:
982
+ for i in range(0, mem_input_length, context_window_length):
983
+ beg, end = i, min(mem_input_length, i + context_window_length)
984
+
985
+ if attention_mask is not None:
986
+ if past_key_values is not None:
987
+ local_cache_size = past_key_values[0][0].shape[-2]
988
+ else:
989
+ local_cache_size = 0
990
+ attn_length = attention_mask.shape[-1]
991
+ attn_beg = beg + attn_offset - local_cache_size
992
+ attn_end = end + attn_offset
993
+ assert attn_end <= attn_length
994
+ assert attn_beg >= 0 and attn_end > attn_beg
995
+
996
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn, mem_caches)
997
+ outputs = model(
998
+ input_ids=input_ids[..., beg:end] if input_ids is not None else None,
999
+ attention_mask=attention_mask[..., attn_beg:attn_end] if attention_mask is not None else None,
1000
+ position_ids=position_ids[..., beg:end],
1001
+ past_key_values=past_key_values,
1002
+ inputs_embeds=inputs_embeds[..., beg:end, :] if inputs_embeds is not None else None,
1003
+ use_cache=False if past_key_values is None else use_cache,
1004
+ output_attentions=output_attentions,
1005
+ output_hidden_states=output_hidden_states,
1006
+ return_dict=True,
1007
+ mem_caches=mem_caches,
1008
+ )
1009
+ if i > 0:
1010
+ if mem_caches is not None and past_key_values is None:
1011
+ for mc_layer in mem_caches:
1012
+ if mc_layer is not None:
1013
+ del mc_layer.keys
1014
+ del mc_layer.values
1015
+ del mc_layer.masks
1016
+
1017
+ mem_caches = outputs.mem_caches
1018
+ outputs.mem_caches = None
1019
+ past_key_values = outputs.past_key_values
1020
+ outputs.past_key_values = None
1021
+ outputs_list.append(outputs)
1022
+
1023
+ remaining_input_length = input_length - mem_input_length
1024
+ beg = mem_input_length
1025
+ attn_length = remaining_input_length
1026
+ if past_key_values is not None:
1027
+ attn_length += past_key_values[0][0].shape[-2]
1028
+ attention_mask = attention_mask[..., -attn_length:] if attention_mask is not None else None
1029
+
1030
+ if past_key_values is not None and past_key_values[0][0].shape[-2] + remaining_input_length > context_window_length:
1031
+ logger.warning("Currently, the code is not optimized for generating long outputs. "
1032
+ "You see this warning as parts of the local (generation) cache are going to be moved to the memory cache.")
1033
+ outputs = model(
1034
+ input_ids=input_ids[..., beg:] if input_ids is not None else None,
1035
+ attention_mask=attention_mask,
1036
+ position_ids=position_ids[..., beg:],
1037
+ past_key_values=past_key_values,
1038
+ inputs_embeds=inputs_embeds[..., beg:, :] if inputs_embeds is not None else None,
1039
+ use_cache=use_cache,
1040
+ output_attentions=output_attentions,
1041
+ output_hidden_states=output_hidden_states,
1042
+ return_dict=True,
1043
+ mem_caches=mem_caches,
1044
+ )
1045
+
1046
+ outputs_list.append(outputs)
1047
+
1048
+ past_key_values = _handle_output_of_past_key_values(outputs_list[-1])
1049
+
1050
+ if output_hidden_states:
1051
+ hidden_states = ()
1052
+ for hd in zip(*[x.hidden_states for x in outputs_list]):
1053
+ hidden_states += (torch.cat(hd, dim=-2),)
1054
+ else:
1055
+ hidden_states = None
1056
+
1057
+ outputs = BaseModelOutputWithPast(
1058
+ last_hidden_state=torch.concat([x.last_hidden_state for x in outputs_list], dim=-2),
1059
+ past_key_values=past_key_values,
1060
+ hidden_states=hidden_states,
1061
+ attentions=outputs_list[-1].attentions,
1062
+ )
1063
+
1064
+ if not return_dict:
1065
+ outputs =tuple(
1066
+ v for v in [outputs.last_hidden_state, outputs.past_key_values, outputs.hidden_states, outputs.attentions]
1067
+ if v is not None
1068
+ )
1069
+ return outputs
1070
+
1071
+
1072
+ # Modified transformers.models.llama.modeling_llama.LlamaForCausalLM
1073
+ class LongLlamaForCausalLM(LongLlamaPreTrainedModel):
1074
+ _tied_weights_keys = ["lm_head.weight"]
1075
+
1076
+ def __init__(
1077
+ self, config
1078
+ ):
1079
+ super().__init__(config)
1080
+ self.context_window_length = config.max_position_embeddings
1081
+
1082
+ self.model = LongLlamaModel(config)
1083
+
1084
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1085
+
1086
+ # Initialize weights and apply final processing
1087
+ self.post_init()
1088
+
1089
+ def get_input_embeddings(self):
1090
+ return self.model.embed_tokens
1091
+
1092
+ def set_input_embeddings(self, value):
1093
+ self.model.embed_tokens = value
1094
+
1095
+ def get_output_embeddings(self):
1096
+ return self.lm_head
1097
+
1098
+ def set_output_embeddings(self, new_embeddings):
1099
+ self.lm_head = new_embeddings
1100
+
1101
+ def set_decoder(self, decoder):
1102
+ self.model = decoder
1103
+
1104
+ def get_decoder(self):
1105
+ return self.model
1106
+
1107
+ def _has_generation_cache(self, past_key_values):
1108
+ if past_key_values is not None:
1109
+ assert len(past_key_values[0]) == 6
1110
+ return past_key_values[0][0].shape[-2] != 0
1111
+
1112
+ return False
1113
+
1114
+ @add_start_docstrings_to_model_forward(LONGLLAMA_COMMON_INPUTS_DOCSTRING, LONGLLAMA_ADD_INPUTS_DOCSTRING)
1115
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1116
+ def forward(
1117
+ self,
1118
+ input_ids: torch.LongTensor = None,
1119
+ attention_mask: Optional[torch.Tensor] = None,
1120
+ position_ids: Optional[torch.LongTensor] = None,
1121
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1122
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1123
+ labels: Optional[torch.LongTensor] = None,
1124
+ use_cache: Optional[bool] = None,
1125
+ output_attentions: Optional[bool] = None,
1126
+ output_hidden_states: Optional[bool] = None,
1127
+ return_dict: Optional[bool] = None,
1128
+ last_context_length: Optional[int] = None,
1129
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1130
+ r"""
1131
+ Args:
1132
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1133
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1134
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1135
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1136
+
1137
+ Returns:
1138
+
1139
+ Example:
1140
+
1141
+ ```python
1142
+ >>> from transformers import AutoTokenizer, LlamaForCausalLM
1143
+
1144
+ >>> model = LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1145
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1146
+
1147
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1148
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1149
+
1150
+ >>> # Generate
1151
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1152
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1153
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1154
+ ```"""
1155
+ last_context_length = last_context_length if last_context_length is not None else self.config.last_context_length
1156
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1157
+ output_hidden_states = (
1158
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1159
+ )
1160
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1161
+
1162
+ outputs = _handle_long_input(
1163
+ model=self.model,
1164
+ input_ids=input_ids,
1165
+ attention_mask=attention_mask,
1166
+ position_ids=position_ids,
1167
+ past_key_values=past_key_values,
1168
+ inputs_embeds=inputs_embeds,
1169
+ use_cache=use_cache,
1170
+ output_attentions=output_attentions,
1171
+ output_hidden_states=output_hidden_states,
1172
+ return_dict=return_dict,
1173
+ context_window_length=self.context_window_length,
1174
+ last_context_length=last_context_length,
1175
+ )
1176
+
1177
+ hidden_states = outputs[0]
1178
+ logits = self.lm_head(hidden_states)
1179
+
1180
+ loss = None
1181
+ if labels is not None:
1182
+ # Shift so that tokens < n predict n
1183
+ shift_logits = logits[..., :-1, :].contiguous()
1184
+ shift_labels = labels[..., 1:].contiguous()
1185
+ # Flatten the tokens
1186
+ loss_fct = CrossEntropyLoss()
1187
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1188
+ shift_labels = shift_labels.view(-1)
1189
+ # Enable model parallelism
1190
+ shift_labels = shift_labels.to(shift_logits.device)
1191
+ loss = loss_fct(shift_logits, shift_labels)
1192
+
1193
+ if not return_dict:
1194
+ output = (logits,) + outputs[1:]
1195
+ return (loss,) + output if loss is not None else output
1196
+
1197
+ return CausalLMOutputWithPast(
1198
+ loss=loss,
1199
+ logits=logits,
1200
+ past_key_values=outputs.past_key_values,
1201
+ hidden_states=outputs.hidden_states,
1202
+ attentions=outputs.attentions,
1203
+ )
1204
+
1205
+ def prepare_inputs_for_generation(
1206
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, last_context_length=None, **kwargs
1207
+ ):
1208
+ if self._has_generation_cache(past_key_values):
1209
+ input_ids = input_ids[:, -1:]
1210
+
1211
+ position_ids = kwargs.get("position_ids", None)
1212
+ if attention_mask is not None and position_ids is None:
1213
+ # create position_ids on the fly for batch generation
1214
+ position_ids = attention_mask.long().cumsum(-1) - 1
1215
+ position_ids.masked_fill(position_ids < 0, 0)
1216
+ if self._has_generation_cache(past_key_values):
1217
+ position_ids = position_ids[:, -1].unsqueeze(-1)
1218
+
1219
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1220
+ if inputs_embeds is not None and past_key_values is None:
1221
+ model_inputs = {"inputs_embeds": inputs_embeds}
1222
+ else:
1223
+ model_inputs = {"input_ids": input_ids}
1224
+
1225
+ model_inputs.update(
1226
+ {
1227
+ "position_ids": position_ids,
1228
+ "past_key_values": past_key_values,
1229
+ "use_cache": kwargs.get("use_cache"),
1230
+ "attention_mask": attention_mask,
1231
+ "last_context_length": last_context_length,
1232
+ }
1233
+ )
1234
+ return model_inputs
1235
+
1236
+ @staticmethod
1237
+ def _reorder_cache(past_key_values, beam_idx):
1238
+ reordered_past = ()
1239
+ for layer_past in past_key_values:
1240
+ reordered_past += (
1241
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1242
+ )
1243
+ return reordered_past
1244
+
1245
+
1246
+ @add_start_docstrings(
1247
+ """
1248
+ The LongLLaMA Model transformer with a sequence classification head on top (linear layer).
1249
+
1250
+ [`LongLlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1251
+ (e.g. GPT-2) do.
1252
+
1253
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1254
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1255
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1256
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1257
+ each row of the batch).
1258
+ """,
1259
+ LONGLLAMA_START_DOCSTRING,
1260
+ LONGLLAMA_MEML_DOCSTRING
1261
+ )
1262
+ # Modified from transformers.models.llama.modeling_llama.LlamaForSequenceClassification
1263
+ class LongLlamaForSequenceClassification(LongLlamaPreTrainedModel):
1264
+ _keys_to_ignore_on_load_missing = [r"lm_head.weight"]
1265
+
1266
+ def __init__(
1267
+ self, config
1268
+ ):
1269
+ super().__init__(config)
1270
+ self.num_labels = config.num_labels
1271
+ self.context_window_length = config.max_position_embeddings
1272
+ self.model = LongLlamaModel(config)
1273
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1274
+
1275
+ # Initialize weights and apply final processing
1276
+ self.post_init()
1277
+
1278
+ def get_input_embeddings(self):
1279
+ return self.model.embed_tokens
1280
+
1281
+ def set_input_embeddings(self, value):
1282
+ self.model.embed_tokens = value
1283
+
1284
+ @add_start_docstrings_to_model_forward(LONGLLAMA_COMMON_INPUTS_DOCSTRING, LONGLLAMA_ADD_INPUTS_DOCSTRING)
1285
+ def forward(
1286
+ self,
1287
+ input_ids: torch.LongTensor = None,
1288
+ attention_mask: Optional[torch.Tensor] = None,
1289
+ position_ids: Optional[torch.LongTensor] = None,
1290
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1291
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1292
+ labels: Optional[torch.LongTensor] = None,
1293
+ use_cache: Optional[bool] = None,
1294
+ output_attentions: Optional[bool] = None,
1295
+ output_hidden_states: Optional[bool] = None,
1296
+ return_dict: Optional[bool] = None,
1297
+ last_context_length: Optional[int] = None,
1298
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1299
+ r"""
1300
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1301
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1302
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1303
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1304
+ """
1305
+ last_context_length = last_context_length if last_context_length is not None else self.config.last_context_length
1306
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1307
+ output_hidden_states = (
1308
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1309
+ )
1310
+ transformer_outputs = _handle_long_input(
1311
+ model=self.model,
1312
+ input_ids=input_ids,
1313
+ attention_mask=attention_mask,
1314
+ position_ids=position_ids,
1315
+ past_key_values=past_key_values,
1316
+ inputs_embeds=inputs_embeds,
1317
+ use_cache=use_cache,
1318
+ output_attentions=output_attentions,
1319
+ output_hidden_states=output_hidden_states,
1320
+ return_dict=return_dict,
1321
+ context_window_length=self.context_window_length,
1322
+ last_context_length=last_context_length,
1323
+ )
1324
+
1325
+ hidden_states = transformer_outputs[0]
1326
+ logits = self.score(hidden_states)
1327
+
1328
+ if input_ids is not None:
1329
+ batch_size = input_ids.shape[0]
1330
+ else:
1331
+ batch_size = inputs_embeds.shape[0]
1332
+
1333
+ if self.config.pad_token_id is None and batch_size != 1:
1334
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1335
+ if self.config.pad_token_id is None:
1336
+ sequence_lengths = -1
1337
+ else:
1338
+ if input_ids is not None:
1339
+ sequence_lengths = (torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1).to(logits.device)
1340
+ else:
1341
+ sequence_lengths = -1
1342
+
1343
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1344
+
1345
+ loss = None
1346
+ if labels is not None:
1347
+ labels = labels.to(logits.device)
1348
+ if self.config.problem_type is None:
1349
+ if self.num_labels == 1:
1350
+ self.config.problem_type = "regression"
1351
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1352
+ self.config.problem_type = "single_label_classification"
1353
+ else:
1354
+ self.config.problem_type = "multi_label_classification"
1355
+
1356
+ if self.config.problem_type == "regression":
1357
+ loss_fct = MSELoss()
1358
+ if self.num_labels == 1:
1359
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1360
+ else:
1361
+ loss = loss_fct(pooled_logits, labels)
1362
+ elif self.config.problem_type == "single_label_classification":
1363
+ loss_fct = CrossEntropyLoss()
1364
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1365
+ elif self.config.problem_type == "multi_label_classification":
1366
+ loss_fct = BCEWithLogitsLoss()
1367
+ loss = loss_fct(pooled_logits, labels)
1368
+ if not return_dict:
1369
+ output = (pooled_logits,) + transformer_outputs[1:]
1370
+ return ((loss,) + output) if loss is not None else output
1371
+
1372
+ return SequenceClassifierOutputWithPast(
1373
+ loss=loss,
1374
+ logits=pooled_logits,
1375
+ past_key_values=transformer_outputs.past_key_values,
1376
+ hidden_states=transformer_outputs.hidden_states,
1377
+ attentions=transformer_outputs.attentions,
1378
+ )
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:84471d08104ab6707825312c3227fc9d3b16351c86396eeedd3d6df7754b82a8
3
+ size 6853038093
special_tokens_map.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"bos_token": {"content": "<s>", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false}, "eos_token": {"content": "</s>", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false}, "unk_token": {"content": "<unk>", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false}}
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ab1b681ec7fc02fed5edd3026687d7a692a918c4dd8e150ca2e3994a6229843b
3
+ size 534194
tokenizer_config.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"bos_token": "", "eos_token": {"__type": "AddedToken", "content": "</s>", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false}, "model_max_length": 1000000000000000019884624838656, "tokenizer_class": "LlamaTokenizer", "unk_token": {"__type": "AddedToken", "content": "<unk>", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false}, "add_bos_token": true, "add_eos_token": false, "pad_token": null, "sp_model_kwargs": {}, "clean_up_tokenization_spaces": {"__type": "AddedToken", "content": "<s>", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false}}