wantsleep commited on
Commit
d0c3269
·
1 Parent(s): 7a5173a
Files changed (7) hide show
  1. .gitattributes +2 -35
  2. README.md +88 -0
  3. config.json +35 -0
  4. eagle_data.json +3 -0
  5. modeling_olmoe_kv.py +1236 -0
  6. pytorch_model.bin +3 -0
  7. tokenizer_config.json +248 -0
.gitattributes CHANGED
@@ -1,35 +1,2 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
1
+ eagle_data.json filter=lfs diff=lfs merge=lfs -text
2
+ pytorch_model.bin filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
README.md ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # OLMoE-1B-7B-Eagle3 Draft Model
2
+
3
+ 이 저장소는 OLMoE-1B-7B-Eagle3 기반의 EAGLE Draft 모델 가중치와 관련 코드, 학습 데이터를 제공합니다.
4
+
5
+ ---
6
+
7
+ ## 📦 포함 파일
8
+
9
+ - `pytorch_model.bin` : 학습된 EAGLE Draft 모델 가중치
10
+ - `config.json` : 모델 설정 파일 (OLMoE 구조)
11
+ - `tokenizer_config.json` : 토크나이저 설정 파일
12
+ - `modeling_olmoe_kv.py` : OLMoE 전용 모델 코드 (EAGLE 추론 시 필요)
13
+ - `eagle_data.json` : 학습에 사용된 데이터셋 (ShareGPT 질문 + OLMoE 답변)
14
+ - `.gitattributes` : Git LFS 설정 등
15
+
16
+ ---
17
+
18
+ ## 🦅 EAGLE Draft 모델이란?
19
+
20
+ EAGLE은 대규모 언어모델(LLM)의 추론 속도를 획기적으로 높이기 위해,
21
+ **Draft(초안) 디코더 계층**을 별도로 학습시키는 구조입니다.
22
+
23
+ - **OLMoE-1B-7B-0125-Instruct**의 구조와 호환
24
+ - EAGLE Draft 계층은 Main Model의 디코더와 구조적으로 유사하게 설계됨
25
+ - 추론 시, Draft 계층이 여러 토큰을 미리 생성 → Main Model이 검증/accept
26
+
27
+ ---
28
+
29
+ ## 📝 학습 데이터 설명
30
+
31
+ - **eagle_data.json**
32
+ - ShareGPT 데이터셋에서 **질문(프롬프트)만 추출**
33
+ - 각 질문에 대해 **allenai/OLMoE-1B-7B-0125-Instruct** 모델이 직접 답변을 생성
34
+ - 즉, **모델이 스스로 생성한 답변**을 정답으로 사용하여 Draft 계층을 학습
35
+ - 이렇게 하면, Draft 계층이 Main Model의 디코더와 더 가까운 분포를 학습하게 되어
36
+ EAGLE 추론 성능이 극대화됨
37
+
38
+ ---
39
+
40
+ ## 🛠️ 사용법
41
+
42
+ ### 1. 모델 가중치/설정 파일 사용
43
+
44
+ - `pytorch_model.bin`, `config.json`, `tokenizer_config.json`을
45
+ HuggingFace Transformers 또는 EAGLE 코드에서 바로 사용할 수 있습니다.
46
+
47
+ ### 2. EAGLE Inference 코드에 적용
48
+
49
+ - `modeling_olmoe_kv.py` 파일을
50
+ EAGLE 공식 저장소의 `EAGLE/eagle/model/` 디렉토리에 복사/덮어쓰기 하세요.
51
+ - EAGLE 추론 스크립트에서
52
+ `from eagle.model.modeling_olmoe_kv import OlmoeForCausalLM`
53
+ 형태로 import 하여 사용하면 됩니다.
54
+
55
+ ### 3. 예시 코드
56
+
57
+ ```python
58
+ from transformers import AutoTokenizer
59
+ from eagle.model.ea_model import EaModel
60
+
61
+ tokenizer = AutoTokenizer.from_pretrained('allenai/OLMoE-1B-7B-0125-Instruct')
62
+ model = EaModel.from_pretrained(
63
+ base_model_path='allenai/OLMoE-1B-7B-0125-Instruct',
64
+ ea_model_path='이 저장소 경로',
65
+ torch_dtype='bfloat16'
66
+ )
67
+ ```
68
+
69
+ ---
70
+
71
+ ## ⚠️ 참고/유의사항
72
+
73
+ - **eagle_data.json**은 공개된 ShareGPT 질문에 대해 OLMoE가 생성한 답변만 포함합니다.
74
+ - EAGLE Draft 계층은 Main Model의 구조와 최대한 유사하게 설계되어야
75
+ 추론 효율이 극대화됩니다.
76
+ - `modeling_olmoe_kv.py`는 반드시 EAGLE 추론 코드에 포함되어야 정상 동작합니다.
77
+
78
+ ---
79
+
80
+ ## 📚 인용/참고
81
+
82
+ - [EAGLE: Fast Decoding for Large Language Models](https://github.com/SafeAILab/EAGLE)
83
+ - [allenai/OLMoE-1B-7B-0125-Instruct](https://huggingface.co/allenai/OLMoE-1B-7B-0125-Instruct)
84
+ - [ShareGPT Dataset](https://huggingface.co/datasets/sharegpt)
85
+
86
+ ---
87
+
88
+ 문의/피드백은 이슈로 남겨주세요!
config.json ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "allenai/open_instruct_dev",
3
+ "architectures": [
4
+ "OlmoeForCausalLM"
5
+ ],
6
+ "attention_bias": false,
7
+ "attention_dropout": 0.0,
8
+ "clip_qkv": null,
9
+ "eos_token_id": 50279,
10
+ "hidden_act": "silu",
11
+ "hidden_size": 2048,
12
+ "initializer_range": 0.02,
13
+ "intermediate_size": 1024,
14
+ "max_position_embeddings": 4096,
15
+ "model_type": "olmoe",
16
+ "norm_topk_prob": false,
17
+ "num_attention_heads": 16,
18
+ "num_experts": 64,
19
+ "num_experts_per_tok": 8,
20
+ "num_hidden_layers": 16,
21
+ "num_key_value_heads": 16,
22
+ "output_router_logits": false,
23
+ "pad_token_id": 1,
24
+ "rms_norm_eps": 1e-05,
25
+ "rope_scaling": null,
26
+ "rope_theta": 10000.0,
27
+ "router_aux_loss_coef": 0.01,
28
+ "tie_word_embeddings": false,
29
+ "torch_dtype": "bfloat16",
30
+ "transformers_version": "4.47.1",
31
+ "use_cache": false,
32
+ "vocab_size": 50304,
33
+ "draft_vocab_size": 32637,
34
+ "pretraining_tp": 1
35
+ }
eagle_data.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:933e2916264d639ee76aacda4c9b6c4fdd1ed5c936b0768101ec87506f9e74ad
3
+ size 609673546
modeling_olmoe_kv.py ADDED
@@ -0,0 +1,1236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Source: Based on transformers OLMoE implementation
2
+ # Modifications are denoted by the symbol: [MODIFIED]
3
+
4
+ """ PyTorch OLMoE model with KV Cache support."""
5
+ import math
6
+ from typing import List, Optional, Tuple, Union
7
+
8
+ import torch
9
+ import torch.nn.functional as F
10
+ import torch.utils.checkpoint
11
+ from torch import nn
12
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
13
+
14
+ # [MODIFIED] Import from transformer library
15
+ from transformers.activations import ACT2FN
16
+ from transformers.modeling_outputs import (
17
+ BaseModelOutputWithPast,
18
+ CausalLMOutputWithPast,
19
+ SequenceClassifierOutputWithPast,
20
+ MoeModelOutputWithPast,
21
+ MoeCausalLMOutputWithPast,
22
+ )
23
+ from transformers.modeling_utils import PreTrainedModel
24
+ from transformers.utils import (
25
+ add_start_docstrings,
26
+ add_start_docstrings_to_model_forward,
27
+ logging,
28
+ replace_return_docstrings,
29
+ )
30
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
31
+ from transformers.models.olmoe.configuration_olmoe import OlmoeConfig
32
+ from transformers.generation.utils import GenerationMixin
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+ _CONFIG_FOR_DOC = "OlmoeConfig"
37
+
38
+
39
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
40
+ def _make_causal_mask(
41
+ input_ids_shape: torch.Size,
42
+ dtype: torch.dtype,
43
+ device: torch.device,
44
+ past_key_values_length: int = 0,
45
+ ):
46
+ """
47
+ Create a causal mask for bi-directional self-attention.
48
+
49
+ Args:
50
+ input_ids_shape (torch.Size): The shape of input_ids tensor, typically (batch_size, tgt_len).
51
+ dtype (torch.dtype): The data type of the mask.
52
+ device (torch.device): The device on which the mask will be placed.
53
+ past_key_values_length (int, optional): The length of past key values. Default is 0.
54
+
55
+ Returns:
56
+ torch.Tensor: The causal mask tensor.
57
+ """
58
+ bsz, tgt_len = input_ids_shape
59
+ mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
60
+ mask_cond = torch.arange(mask.size(-1), device=device)
61
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
62
+ mask = mask.to(dtype)
63
+
64
+ if past_key_values_length > 0:
65
+ mask = torch.cat(
66
+ [
67
+ torch.zeros(
68
+ tgt_len, past_key_values_length, dtype=dtype, device=device
69
+ ),
70
+ mask,
71
+ ],
72
+ dim=-1,
73
+ )
74
+ return mask[None, None, :, :].expand(
75
+ bsz, 1, tgt_len, tgt_len + past_key_values_length
76
+ )
77
+
78
+
79
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
80
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
81
+ """
82
+ Expand attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
83
+
84
+ Args:
85
+ mask (torch.Tensor): The attention mask tensor of shape `[bsz, seq_len]`.
86
+ dtype (torch.dtype): The data type of the mask.
87
+ tgt_len (Optional[int], optional): The target sequence length. If None, it defaults to the source sequence length.
88
+
89
+ Returns:
90
+ torch.Tensor: The expanded mask tensor.
91
+ """
92
+ bsz, src_len = mask.size()
93
+ tgt_len = tgt_len if tgt_len is not None else src_len
94
+
95
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
96
+
97
+ inverted_mask = 1.0 - expanded_mask
98
+
99
+ return inverted_mask.masked_fill(
100
+ inverted_mask.to(torch.bool), torch.finfo(dtype).min
101
+ )
102
+
103
+
104
+ # Copied from transformers.models.mixtral.modeling_mixtral.load_balancing_loss_func
105
+ def load_balancing_loss_func(
106
+ gate_logits: Union[torch.Tensor, Tuple[torch.Tensor], None],
107
+ num_experts: Optional[int] = None,
108
+ top_k=2,
109
+ attention_mask: Optional[torch.Tensor] = None,
110
+ ) -> Union[torch.Tensor, int]:
111
+ r"""
112
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
113
+
114
+ See Switch Transformer (https://arxiv.org/abs/2101.03961) for more details. This function implements the loss
115
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
116
+ experts is too unbalanced.
117
+
118
+ Args:
119
+ gate_logits:
120
+ Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
121
+ shape [batch_size X sequence_length, num_experts].
122
+ num_experts:
123
+ Number of experts
124
+ top_k:
125
+ The number of experts to route per-token, can be also interpreted as the `top-k` routing
126
+ parameter.
127
+ attention_mask (`torch.Tensor`, *optional*):
128
+ The attention_mask used in forward function
129
+ shape [batch_size X sequence_length] if not None.
130
+
131
+ Returns:
132
+ The auxiliary loss.
133
+ """
134
+ if gate_logits is None or not isinstance(gate_logits, tuple):
135
+ return 0
136
+
137
+ if isinstance(gate_logits, tuple):
138
+ compute_device = gate_logits[0].device
139
+ concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
140
+
141
+ routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
142
+
143
+ _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
144
+
145
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
146
+
147
+ if attention_mask is None:
148
+ # Compute the percentage of tokens routed to each experts
149
+ tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
150
+
151
+ # Compute the average probability of routing to these experts
152
+ router_prob_per_expert = torch.mean(routing_weights, dim=0)
153
+ else:
154
+ batch_size, sequence_length = attention_mask.shape
155
+ num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
156
+
157
+ # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
158
+ expert_attention_mask = (
159
+ attention_mask[None, :, :, None, None]
160
+ .expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
161
+ .reshape(-1, top_k, num_experts)
162
+ .to(compute_device)
163
+ )
164
+
165
+ # Compute the percentage of tokens routed to each experts
166
+ tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
167
+ expert_attention_mask, dim=0
168
+ )
169
+
170
+ # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
171
+ router_per_expert_attention_mask = (
172
+ attention_mask[None, :, :, None]
173
+ .expand((num_hidden_layers, batch_size, sequence_length, num_experts))
174
+ .reshape(-1, num_experts)
175
+ .to(compute_device)
176
+ )
177
+
178
+ # Compute the average probability of routing to these experts
179
+ router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
180
+ router_per_expert_attention_mask, dim=0
181
+ )
182
+
183
+ overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
184
+ return overall_loss * num_experts
185
+
186
+
187
+ class OlmoeRMSNorm(nn.Module):
188
+ def __init__(self, hidden_size, eps=1e-5):
189
+ """
190
+ OlmoeRMSNorm is equivalent to T5LayerNorm
191
+ """
192
+ super().__init__()
193
+ self.weight = nn.Parameter(torch.ones(hidden_size))
194
+ self.variance_epsilon = eps
195
+
196
+ def forward(self, hidden_states):
197
+ input_dtype = hidden_states.dtype
198
+ hidden_states = hidden_states.to(torch.float32)
199
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
200
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
201
+ return self.weight * hidden_states.to(input_dtype)
202
+
203
+ def extra_repr(self):
204
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
205
+
206
+
207
+ # Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->Olmoe
208
+ class OlmoeRotaryEmbedding(nn.Module):
209
+ def __init__(self, config: OlmoeConfig, device=None):
210
+ super().__init__()
211
+ # BC: "rope_type" was originally "type"
212
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
213
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
214
+ else:
215
+ self.rope_type = "default"
216
+ self.max_seq_len_cached = config.max_position_embeddings
217
+ self.original_max_seq_len = config.max_position_embeddings
218
+
219
+ self.config = config
220
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
221
+
222
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
223
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
224
+ self.original_inv_freq = self.inv_freq
225
+
226
+ @torch.no_grad()
227
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
228
+ def forward(self, x, position_ids):
229
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
230
+ position_ids_expanded = position_ids[:, None, :].float()
231
+
232
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
233
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
234
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
235
+ emb = torch.cat((freqs, freqs), dim=-1)
236
+ cos = emb.cos() * self.attention_scaling
237
+ sin = emb.sin() * self.attention_scaling
238
+
239
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
240
+
241
+
242
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
243
+ def rotate_half(x):
244
+ """Rotates half the hidden dims of the input."""
245
+ x1 = x[..., : x.shape[-1] // 2]
246
+ x2 = x[..., x.shape[-1] // 2 :]
247
+ return torch.cat((-x2, x1), dim=-1)
248
+
249
+
250
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
251
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
252
+ """Applies Rotary Position Embedding to the query and key tensors.
253
+
254
+ Args:
255
+ q (`torch.Tensor`): The query tensor.
256
+ k (`torch.Tensor`): The key tensor.
257
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
258
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
259
+ position_ids (`torch.Tensor`, *optional*):
260
+ Deprecated and unused.
261
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
262
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
263
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
264
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
265
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
266
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
267
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
268
+ Returns:
269
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
270
+ """
271
+ cos = cos.unsqueeze(unsqueeze_dim)
272
+ sin = sin.unsqueeze(unsqueeze_dim)
273
+ q_embed = (q * cos) + (rotate_half(q) * sin)
274
+ k_embed = (k * cos) + (rotate_half(k) * sin)
275
+ return q_embed, k_embed
276
+
277
+
278
+ # Copied from transformers.models.olmo.modeling_olmo.OlmoMLP with Olmo->Olmoe
279
+ class OlmoeMLP(nn.Module):
280
+ def __init__(self, config):
281
+ super().__init__()
282
+ self.config = config
283
+ self.hidden_size = config.hidden_size
284
+ self.intermediate_size = config.intermediate_size
285
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
286
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
287
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
288
+ self.act_fn = ACT2FN[config.hidden_act]
289
+
290
+ def forward(self, x):
291
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
292
+ return down_proj
293
+
294
+
295
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
296
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
297
+ """
298
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
299
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
300
+ """
301
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
302
+ if n_rep == 1:
303
+ return hidden_states
304
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
305
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
306
+
307
+
308
+ class OlmoeAttention(nn.Module):
309
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
310
+
311
+ def __init__(self, config: OlmoeConfig, rotary_emb, layer_idx: Optional[int] = None):
312
+ super().__init__()
313
+ self.config = config
314
+ self.layer_idx = layer_idx
315
+ if layer_idx is None:
316
+ logger.warning_once(
317
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
318
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
319
+ "when creating this class."
320
+ )
321
+
322
+ self.attention_dropout = config.attention_dropout
323
+ self.hidden_size = config.hidden_size
324
+ self.num_heads = config.num_attention_heads
325
+ self.head_dim = self.hidden_size // self.num_heads
326
+ self.num_key_value_heads = config.num_key_value_heads
327
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
328
+ self.max_position_embeddings = config.max_position_embeddings
329
+ self.rope_theta = config.rope_theta
330
+ self.is_causal = True
331
+
332
+ if (self.head_dim * self.num_heads) != self.hidden_size:
333
+ raise ValueError(
334
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
335
+ f" and `num_heads`: {self.num_heads})."
336
+ )
337
+
338
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
339
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
340
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
341
+ self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=config.attention_bias)
342
+ self.q_norm = OlmoeRMSNorm(self.hidden_size, eps=config.rms_norm_eps)
343
+ self.k_norm = OlmoeRMSNorm(
344
+ (self.hidden_size // self.num_heads) * self.num_key_value_heads, eps=config.rms_norm_eps
345
+ )
346
+ self.rotary_emb = rotary_emb
347
+
348
+ def forward(
349
+ self,
350
+ hidden_states: torch.Tensor,
351
+ attention_mask: Optional[torch.Tensor] = None,
352
+ position_ids: Optional[torch.LongTensor] = None,
353
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
354
+ output_attentions: bool = False,
355
+ use_cache: bool = False,
356
+ **kwargs,
357
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
358
+ bsz, q_len, _ = hidden_states.size()
359
+
360
+ query_states = self.q_norm(self.q_proj(hidden_states))
361
+ key_states = self.k_norm(self.k_proj(hidden_states))
362
+ value_states = self.v_proj(hidden_states)
363
+
364
+ if self.config.clip_qkv is not None:
365
+ query_states.clamp_(min=-self.config.clip_qkv, max=self.config.clip_qkv)
366
+ key_states.clamp_(min=-self.config.clip_qkv, max=self.config.clip_qkv)
367
+ value_states.clamp_(min=-self.config.clip_qkv, max=self.config.clip_qkv)
368
+
369
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
370
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
371
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
372
+
373
+ kv_seq_len = key_states.shape[-2]
374
+ if past_key_value is not None:
375
+ kv_seq_len += past_key_value[0].shape[-2]
376
+
377
+ # Prepare position embeddings
378
+ cos, sin = self.rotary_emb(query_states, position_ids)
379
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
380
+
381
+ # [MODIFIED] Using KVCache mechanism for preallocated GPU memory optimization
382
+ # past_key_value is utilized to leverage previously computed key and value states.
383
+ # If past_key_value is available, reuse the states for k, v, and self_attention.
384
+ if past_key_value is not None:
385
+ key_states = past_key_value[0].cat(key_states, dim=2)
386
+ value_states = past_key_value[1].cat(value_states, dim=2)
387
+ # Reset past_key_value to avoid return past_key_value.
388
+ past_key_value = None
389
+
390
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
391
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
392
+
393
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
394
+
395
+ if attention_mask is not None: # no matter the length, we just slice it
396
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
397
+ attn_weights = attn_weights + causal_mask
398
+
399
+ # upcast attention to fp32
400
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
401
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
402
+ attn_output = torch.matmul(attn_weights, value_states)
403
+
404
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
405
+ raise ValueError(
406
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
407
+ f" {attn_output.size()}"
408
+ )
409
+
410
+ attn_output = attn_output.transpose(1, 2).contiguous()
411
+
412
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
413
+
414
+ attn_output = self.o_proj(attn_output)
415
+
416
+ if not output_attentions:
417
+ attn_weights = None
418
+
419
+ return attn_output, attn_weights, past_key_value
420
+
421
+
422
+ class OlmoeSparseMoeBlock(nn.Module):
423
+ def __init__(self, config):
424
+ super().__init__()
425
+ self.num_experts = config.num_experts
426
+ self.top_k = config.num_experts_per_tok
427
+ self.norm_topk_prob = config.norm_topk_prob
428
+ self.gate = nn.Linear(config.hidden_size, self.num_experts, bias=False)
429
+ self.experts = nn.ModuleList([OlmoeMLP(config) for _ in range(self.num_experts)])
430
+
431
+ def forward(self, hidden_states: torch.Tensor, expert_counter_list= None) -> torch.Tensor: #modified-shw
432
+ batch_size, sequence_length, hidden_dim = hidden_states.shape
433
+ hidden_states = hidden_states.view(-1, hidden_dim)
434
+ # router_logits: (batch * sequence_length, n_experts)
435
+ router_logits = self.gate(hidden_states)
436
+
437
+ routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float)
438
+ routing_weights, selected_experts = torch.topk(routing_weights, self.top_k, dim=-1)
439
+ if self.norm_topk_prob:
440
+ routing_weights /= routing_weights.sum(dim=-1, keepdim=True)
441
+ # we cast back to the input dtype
442
+ routing_weights = routing_weights.to(hidden_states.dtype)
443
+
444
+ unique_experts = torch.unique(selected_experts) #modified-shw
445
+ num_experts = len(unique_experts) #modified-shw
446
+ if expert_counter_list is not None: #modified-shw
447
+ expert_counter_list.append(num_experts) #modified-shw
448
+
449
+ final_hidden_states = torch.zeros(
450
+ (batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device
451
+ )
452
+
453
+ # One hot encode the selected experts to create an expert mask
454
+ # this will be used to easily index which expert is going to be selected
455
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_classes=self.num_experts).permute(2, 1, 0)
456
+
457
+ # Loop over all available experts in the model and perform the computation on each expert
458
+ for expert_idx in range(self.num_experts):
459
+ expert_layer = self.experts[expert_idx]
460
+ idx, top_x = torch.where(expert_mask[expert_idx])
461
+
462
+ # Index the correct hidden states and compute the expert hidden state for
463
+ # the current expert. We need to make sure to multiply the output hidden
464
+ # states by `routing_weights` on the corresponding tokens (top-1 and top-2)
465
+ current_state = hidden_states[None, top_x].reshape(-1, hidden_dim)
466
+ current_hidden_states = expert_layer(current_state) * routing_weights[top_x, idx, None]
467
+
468
+ # However `index_add_` only support torch tensors for indexing so we'll use
469
+ # the `top_x` tensor here.
470
+ final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
471
+ final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)
472
+ return final_hidden_states, router_logits
473
+
474
+
475
+ class OlmoeDecoderLayer(nn.Module):
476
+ def __init__(self, config: OlmoeConfig, rotary_emb, layer_idx: int):
477
+ super().__init__()
478
+ self.hidden_size = config.hidden_size
479
+
480
+ self.self_attn = OlmoeAttention(config=config, rotary_emb=rotary_emb, layer_idx=layer_idx)
481
+
482
+ self.mlp = OlmoeSparseMoeBlock(config)
483
+ self.input_layernorm = OlmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
484
+ self.post_attention_layernorm = OlmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
485
+
486
+ def forward(
487
+ self,
488
+ hidden_states: torch.Tensor,
489
+ attention_mask: Optional[torch.Tensor] = None,
490
+ position_ids: Optional[torch.LongTensor] = None,
491
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
492
+ output_attentions: Optional[bool] = False,
493
+ output_router_logits: Optional[bool] = False,
494
+ use_cache: Optional[bool] = False,
495
+ expert_counter_list= None, #modified-shw
496
+ **kwargs,
497
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
498
+ """
499
+ Args:
500
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
501
+ attention_mask (`torch.FloatTensor`, *optional*):
502
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
503
+ query_sequence_length, key_sequence_length)` if default attention is used.
504
+ output_attentions (`bool`, *optional*):
505
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
506
+ returned tensors for more detail.
507
+ output_router_logits (`bool`, *optional*):
508
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss,
509
+ and should not be returned during inference.
510
+ use_cache (`bool`, *optional*):
511
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
512
+ (see `past_key_values`).
513
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
514
+ """
515
+ residual = hidden_states
516
+
517
+ hidden_states = self.input_layernorm(hidden_states)
518
+
519
+ # Self Attention
520
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
521
+ hidden_states=hidden_states,
522
+ attention_mask=attention_mask,
523
+ position_ids=position_ids,
524
+ past_key_value=past_key_value,
525
+ output_attentions=output_attentions,
526
+ use_cache=use_cache,
527
+ )
528
+ hidden_states = residual + hidden_states
529
+
530
+ # Fully Connected
531
+ residual = hidden_states
532
+ hidden_states = self.post_attention_layernorm(hidden_states)
533
+ hidden_states, router_logits = self.mlp(hidden_states, expert_counter_list=expert_counter_list)
534
+ hidden_states = residual + hidden_states
535
+
536
+ outputs = (hidden_states,)
537
+
538
+ if output_attentions:
539
+ outputs += (self_attn_weights,)
540
+
541
+ if use_cache:
542
+ outputs += (present_key_value,)
543
+
544
+ if output_router_logits:
545
+ outputs += (router_logits,)
546
+
547
+ return outputs
548
+
549
+
550
+ OLMOE_START_DOCSTRING = r"""
551
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
552
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
553
+ etc.)
554
+
555
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
556
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
557
+ and behavior.
558
+
559
+ Parameters:
560
+ config ([`OlmoeConfig`]):
561
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
562
+ load the weights associated with the model, only the configuration. Check out the
563
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
564
+ """
565
+
566
+
567
+ @add_start_docstrings(
568
+ "The bare OLMoE Model outputting raw hidden-states without any specific head on top.",
569
+ OLMOE_START_DOCSTRING,
570
+ )
571
+ class OlmoePreTrainedModel(PreTrainedModel):
572
+ config_class = OlmoeConfig
573
+ base_model_prefix = "model"
574
+ supports_gradient_checkpointing = True
575
+ _no_split_modules = ["OlmoeDecoderLayer"]
576
+ _skip_keys_device_placement = "past_key_values"
577
+
578
+ def _init_weights(self, module):
579
+ std = self.config.initializer_range
580
+ if isinstance(module, nn.Linear):
581
+ module.weight.data.normal_(mean=0.0, std=std)
582
+ if module.bias is not None:
583
+ module.bias.data.zero_()
584
+ elif isinstance(module, OlmoeRMSNorm):
585
+ module.weight.data.fill_(1.0)
586
+ elif isinstance(module, nn.Embedding):
587
+ module.weight.data.normal_(mean=0.0, std=std)
588
+ if module.padding_idx is not None:
589
+ module.weight.data[module.padding_idx].zero_()
590
+
591
+ def _set_gradient_checkpointing(self, module, value=False):
592
+ if isinstance(module, OlmoeModel):
593
+ module.gradient_checkpointing = value
594
+
595
+
596
+ OLMOE_INPUTS_DOCSTRING = r"""
597
+ Args:
598
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
599
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
600
+ it.
601
+
602
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
603
+ [`PreTrainedTokenizer.__call__`] for details.
604
+
605
+ [What are input IDs?](../glossary#input-ids)
606
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
607
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
608
+
609
+ - 1 for tokens that are **not masked**,
610
+ - 0 for tokens that are **masked**.
611
+
612
+ [What are attention masks?](../glossary#attention-mask)
613
+
614
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
615
+ [`PreTrainedTokenizer.__call__`] for details.
616
+
617
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
618
+ `past_key_values`).
619
+
620
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
621
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
622
+ information on the default strategy.
623
+
624
+ - 1 indicates the head is **not masked**,
625
+ - 0 indicates the head is **masked**.
626
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
627
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
628
+ config.n_positions - 1]`.
629
+
630
+ [What are position IDs?](../glossary#position-ids)
631
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
632
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
633
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
634
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
635
+
636
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
637
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
638
+
639
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
640
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
641
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
642
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
643
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
644
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
645
+ model's internal embedding lookup matrix.
646
+ use_cache (`bool`, *optional*):
647
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
648
+ `past_key_values`).
649
+ output_attentions (`bool`, *optional*):
650
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
651
+ tensors for more detail.
652
+ output_hidden_states (`bool`, *optional*):
653
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
654
+ more detail.
655
+ return_dict (`bool`, *optional*):
656
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
657
+ """
658
+
659
+
660
+ @add_start_docstrings(
661
+ "The bare OLMoE Model outputting raw hidden-states without any specific head on top.",
662
+ OLMOE_START_DOCSTRING,
663
+ )
664
+ class OlmoeModel(OlmoePreTrainedModel):
665
+ """
666
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`OlmoeDecoderLayer`]
667
+
668
+ Args:
669
+ config: OlmoeConfig
670
+ """
671
+
672
+ def __init__(self, config: OlmoeConfig):
673
+ super().__init__(config)
674
+ self.padding_idx = config.pad_token_id
675
+ self.vocab_size = config.vocab_size
676
+
677
+ self.embed_tokens = nn.Embedding(
678
+ config.vocab_size, config.hidden_size, self.padding_idx
679
+ )
680
+ self.rotary_emb = OlmoeRotaryEmbedding(config=config)
681
+ self.layers = nn.ModuleList(
682
+ [OlmoeDecoderLayer(config, self.rotary_emb, layer_idx) for layer_idx in range(config.num_hidden_layers)]
683
+ )
684
+ self.norm = OlmoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
685
+
686
+ self.gradient_checkpointing = False
687
+ # Initialize weights and apply final processing
688
+ self.post_init()
689
+
690
+ def get_input_embeddings(self):
691
+ return self.embed_tokens
692
+
693
+ def set_input_embeddings(self, value):
694
+ self.embed_tokens = value
695
+
696
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
697
+ def _prepare_decoder_attention_mask(
698
+ self, attention_mask, input_shape, inputs_embeds, past_key_values_length
699
+ ):
700
+ # create causal mask
701
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
702
+ combined_attention_mask = None
703
+ if input_shape[-1] > 1:
704
+ combined_attention_mask = _make_causal_mask(
705
+ input_shape,
706
+ # inputs_embeds.dtype,
707
+ torch.float32, # [MODIFIED] force to cast to float32
708
+ device=inputs_embeds.device,
709
+ past_key_values_length=past_key_values_length,
710
+ )
711
+
712
+ if attention_mask is not None:
713
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
714
+ expanded_attn_mask = _expand_mask(
715
+ attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
716
+ ).to(inputs_embeds.device)
717
+ combined_attention_mask = (
718
+ expanded_attn_mask
719
+ if combined_attention_mask is None
720
+ else expanded_attn_mask + combined_attention_mask
721
+ )
722
+
723
+ if hasattr(self, "tree_mask") and self.tree_mask is not None:
724
+ tree_mask = self.tree_mask
725
+ tree_len = tree_mask.size(-1)
726
+ combined_attention_mask[:, :, -tree_len:, -tree_len:][
727
+ tree_mask == 0
728
+ ] = combined_attention_mask.min()
729
+
730
+ return combined_attention_mask
731
+
732
+ @add_start_docstrings_to_model_forward(OLMOE_INPUTS_DOCSTRING)
733
+ def forward(
734
+ self,
735
+ input_ids: torch.LongTensor = None,
736
+ attention_mask: Optional[torch.Tensor] = None,
737
+ position_ids: Optional[torch.LongTensor] = None,
738
+ past_key_values=None, # [MODIFIED] past_key_value is KVCache class
739
+ inputs_embeds: Optional[torch.FloatTensor] = None,
740
+ use_cache: Optional[bool] = None,
741
+ output_attentions: Optional[bool] = None,
742
+ output_hidden_states: Optional[bool] = None,
743
+ output_router_logits: Optional[bool] = None,
744
+ return_dict: Optional[bool] = None,
745
+ ) -> Union[Tuple, MoeModelOutputWithPast]:
746
+ output_attentions = (
747
+ output_attentions
748
+ if output_attentions is not None
749
+ else self.config.output_attentions
750
+ )
751
+ output_router_logits = (
752
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
753
+ )
754
+ output_hidden_states = (
755
+ output_hidden_states
756
+ if output_hidden_states is not None
757
+ else self.config.output_hidden_states
758
+ )
759
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
760
+
761
+ return_dict = (
762
+ return_dict if return_dict is not None else self.config.use_return_dict
763
+ )
764
+
765
+ # retrieve input_ids and inputs_embeds
766
+ if input_ids is not None and inputs_embeds is not None:
767
+ raise ValueError(
768
+ "You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time"
769
+ )
770
+ elif input_ids is not None:
771
+ batch_size, seq_length = input_ids.shape
772
+ elif inputs_embeds is not None:
773
+ batch_size, seq_length, _ = inputs_embeds.shape
774
+ else:
775
+ raise ValueError(
776
+ "You have to specify either decoder_input_ids or decoder_inputs_embeds"
777
+ )
778
+
779
+ seq_length_with_past = seq_length
780
+ past_key_values_length = 0
781
+
782
+ if past_key_values is not None:
783
+ past_key_values_length = past_key_values[0][0].shape[2]
784
+ seq_length_with_past = seq_length_with_past + past_key_values_length
785
+
786
+ if position_ids is None:
787
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
788
+ position_ids = torch.arange(
789
+ past_key_values_length,
790
+ seq_length + past_key_values_length,
791
+ dtype=torch.long,
792
+ device=device,
793
+ )
794
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
795
+ else:
796
+ position_ids = position_ids.view(-1, seq_length).long()
797
+
798
+ if inputs_embeds is None:
799
+ inputs_embeds = self.embed_tokens(input_ids)
800
+ # embed positions
801
+ if attention_mask is None:
802
+ attention_mask = torch.ones(
803
+ (batch_size, seq_length_with_past),
804
+ dtype=torch.bool,
805
+ device=inputs_embeds.device,
806
+ )
807
+ attention_mask = self._prepare_decoder_attention_mask(
808
+ attention_mask,
809
+ (batch_size, seq_length),
810
+ inputs_embeds,
811
+ past_key_values_length,
812
+ )
813
+
814
+ hidden_states = inputs_embeds
815
+
816
+ if self.gradient_checkpointing and self.training:
817
+ if use_cache:
818
+ logger.warning_once(
819
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
820
+ )
821
+ use_cache = False
822
+
823
+ # decoder layers
824
+ all_hidden_states = () if 1 else None
825
+ all_self_attns = () if output_attentions else None
826
+ all_router_logits = () if output_router_logits else None
827
+ next_decoder_cache = () if use_cache else None
828
+ expert_counter_list = [] #modified-shw
829
+ for idx, decoder_layer in enumerate(self.layers):
830
+ if idx==len(self.layers)-1 or idx==len(self.layers)//2 or idx==2: #modified-shw
831
+ all_hidden_states += (hidden_states,)
832
+
833
+ past_key_value = (
834
+ past_key_values[idx] if past_key_values is not None else None
835
+ )
836
+
837
+ if self.gradient_checkpointing and self.training:
838
+
839
+ def create_custom_forward(module):
840
+ def custom_forward(*inputs):
841
+ # None for past_key_value
842
+ return module(*inputs, output_attentions, output_router_logits, None)
843
+
844
+ return custom_forward
845
+
846
+ layer_outputs = torch.utils.checkpoint.checkpoint(
847
+ create_custom_forward(decoder_layer),
848
+ hidden_states,
849
+ attention_mask,
850
+ position_ids,
851
+ None,
852
+ )
853
+ else:
854
+ layer_outputs = decoder_layer(
855
+ hidden_states,
856
+ attention_mask=attention_mask,
857
+ position_ids=position_ids,
858
+ past_key_value=past_key_value,
859
+ output_attentions=output_attentions,
860
+ output_router_logits=output_router_logits,
861
+ use_cache=use_cache,
862
+ expert_counter_list=expert_counter_list, #modified-shw
863
+ )
864
+
865
+ hidden_states = layer_outputs[0]
866
+
867
+ if use_cache:
868
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
869
+
870
+ if output_attentions:
871
+ all_self_attns += (layer_outputs[1],)
872
+
873
+ if output_router_logits and layer_outputs[-1] is not None:
874
+ all_router_logits += (layer_outputs[-1],)
875
+
876
+ hidden_states = self.norm(hidden_states)
877
+
878
+ # add hidden states from the last decoder layer
879
+ if output_hidden_states:
880
+ all_hidden_states += (hidden_states,)
881
+
882
+ # !!!
883
+ # all_hidden_states += (hidden_states,)
884
+
885
+ next_cache = next_decoder_cache if use_cache else None
886
+ if not return_dict:
887
+ return tuple(
888
+ v
889
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_router_logits]
890
+ if v is not None
891
+ )
892
+ if len(expert_counter_list) > 0: #modified-shw
893
+ avg_expert = sum(expert_counter_list) / len(expert_counter_list) #modified-shw
894
+ print(f"[MoE] 이번 main forward에서 layer별 unique expert 개수 평균: {avg_expert:.2f}") #modified-shw
895
+ with open("expert_counter_list.txt", "a") as f: #modified-shw
896
+ f.write(f"{avg_expert}\n") #modified-shw
897
+ return MoeModelOutputWithPast(
898
+ last_hidden_state=hidden_states,
899
+ past_key_values=next_cache,
900
+ hidden_states=all_hidden_states,
901
+ attentions=all_self_attns,
902
+ router_logits=all_router_logits,
903
+ )
904
+
905
+
906
+ class OlmoeForCausalLM(OlmoePreTrainedModel, GenerationMixin):
907
+ _tied_weights_keys = ["lm_head.weight"]
908
+
909
+ def __init__(self, config):
910
+ super().__init__(config)
911
+ self.model = OlmoeModel(config)
912
+ self.vocab_size = config.vocab_size
913
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
914
+
915
+ self.router_aux_loss_coef = config.router_aux_loss_coef
916
+ self.num_experts = config.num_experts
917
+ self.num_experts_per_tok = config.num_experts_per_tok
918
+ # Initialize weights and apply final processing
919
+ self.post_init()
920
+
921
+ def get_input_embeddings(self):
922
+ return self.model.embed_tokens
923
+
924
+ def set_input_embeddings(self, value):
925
+ self.model.embed_tokens = value
926
+
927
+ def get_output_embeddings(self):
928
+ return self.lm_head
929
+
930
+ def set_output_embeddings(self, new_embeddings):
931
+ self.lm_head = new_embeddings
932
+
933
+ def set_decoder(self, decoder):
934
+ self.model = decoder
935
+
936
+ def get_decoder(self):
937
+ return self.model
938
+
939
+ @add_start_docstrings_to_model_forward(OLMOE_INPUTS_DOCSTRING)
940
+ @replace_return_docstrings(
941
+ output_type=MoeCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
942
+ )
943
+ def forward(
944
+ self,
945
+ input_ids: torch.LongTensor = None,
946
+ attention_mask: Optional[torch.Tensor] = None,
947
+ position_ids: Optional[torch.LongTensor] = None,
948
+ past_key_values=None, # [MODIFIED] past_key_value is KVCache class
949
+ inputs_embeds: Optional[torch.FloatTensor] = None,
950
+ labels: Optional[torch.LongTensor] = None,
951
+ use_cache: Optional[bool] = None,
952
+ output_attentions: Optional[bool] = None,
953
+ output_hidden_states: Optional[bool] = None,
954
+ output_router_logits: Optional[bool] = None,
955
+ return_dict: Optional[bool] = None,
956
+ ) -> Union[Tuple, MoeCausalLMOutputWithPast]:
957
+ r"""
958
+ Args:
959
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
960
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
961
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
962
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
963
+
964
+ Returns:
965
+
966
+ Example:
967
+
968
+ ```python
969
+ >>> from transformers import AutoTokenizer, OlmoeForCausalLM
970
+
971
+ >>> model = OlmoeForCausalLM.from_pretrained("allenai/OLMoE-1B-7B-0924")
972
+ >>> tokenizer = AutoTokenizer.from_pretrained("allenai/OLMoE-1B-7B-0924")
973
+
974
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
975
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
976
+
977
+ >>> # Generate
978
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
979
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
980
+ 'Hey, are you conscious? Can you talk to me?\nI'm not sure if you're conscious of this, but I'm'
981
+ ```"""
982
+
983
+ output_attentions = (
984
+ output_attentions
985
+ if output_attentions is not None
986
+ else self.config.output_attentions
987
+ )
988
+ output_router_logits = (
989
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
990
+ )
991
+ output_hidden_states = (
992
+ output_hidden_states
993
+ if output_hidden_states is not None
994
+ else self.config.output_hidden_states
995
+ )
996
+ return_dict = (
997
+ return_dict if return_dict is not None else self.config.use_return_dict
998
+ )
999
+
1000
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1001
+ outputs = self.model(
1002
+ input_ids=input_ids,
1003
+ attention_mask=attention_mask,
1004
+ position_ids=position_ids,
1005
+ past_key_values=past_key_values,
1006
+ inputs_embeds=inputs_embeds,
1007
+ use_cache=use_cache,
1008
+ output_attentions=output_attentions,
1009
+ output_hidden_states=output_hidden_states,
1010
+ output_router_logits=output_router_logits,
1011
+ return_dict=return_dict,
1012
+ )
1013
+
1014
+ hidden_states = outputs[0]
1015
+ logits = self.lm_head(hidden_states)
1016
+
1017
+ loss = None
1018
+ if labels is not None:
1019
+ # Shift so that tokens < n predict n
1020
+ shift_logits = logits[..., :-1, :].contiguous()
1021
+ shift_labels = labels[..., 1:].contiguous()
1022
+ # Flatten the tokens
1023
+ loss_fct = CrossEntropyLoss()
1024
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1025
+ shift_labels = shift_labels.view(-1)
1026
+ # Enable model parallelism
1027
+ shift_labels = shift_labels.to(shift_logits.device)
1028
+ loss = loss_fct(shift_logits, shift_labels)
1029
+
1030
+ aux_loss = None
1031
+ if output_router_logits:
1032
+ aux_loss = load_balancing_loss_func(
1033
+ outputs.router_logits if return_dict else outputs[-1],
1034
+ self.num_experts,
1035
+ self.num_experts_per_tok,
1036
+ attention_mask,
1037
+ )
1038
+ if labels is not None:
1039
+ loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
1040
+
1041
+ if not return_dict:
1042
+ output = (logits,) + outputs[1:]
1043
+ if output_router_logits:
1044
+ output = (aux_loss,) + output
1045
+ return (loss,) + output if loss is not None else output
1046
+
1047
+ return MoeCausalLMOutputWithPast(
1048
+ loss=loss,
1049
+ aux_loss=aux_loss,
1050
+ logits=logits,
1051
+ past_key_values=outputs.past_key_values,
1052
+ hidden_states=outputs.hidden_states,
1053
+ attentions=outputs.attentions,
1054
+ router_logits=outputs.router_logits,
1055
+ )
1056
+
1057
+ def prepare_inputs_for_generation(
1058
+ self,
1059
+ input_ids,
1060
+ past_key_values=None,
1061
+ attention_mask=None,
1062
+ inputs_embeds=None,
1063
+ **kwargs,
1064
+ ):
1065
+ if past_key_values:
1066
+ input_ids = input_ids[:, -1:]
1067
+
1068
+ position_ids = kwargs.get("position_ids", None)
1069
+ if attention_mask is not None and position_ids is None:
1070
+ # create position_ids on the fly for batch generation
1071
+ position_ids = attention_mask.long().cumsum(-1) - 1
1072
+ position_ids.masked_fill_(attention_mask == 0, 1)
1073
+ if past_key_values:
1074
+ position_ids = position_ids[:, -1].unsqueeze(-1)
1075
+
1076
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1077
+ if inputs_embeds is not None and past_key_values is None:
1078
+ model_inputs = {"inputs_embeds": inputs_embeds}
1079
+ else:
1080
+ model_inputs = {"input_ids": input_ids}
1081
+
1082
+ model_inputs.update(
1083
+ {
1084
+ "position_ids": position_ids,
1085
+ "past_key_values": past_key_values,
1086
+ "use_cache": kwargs.get("use_cache"),
1087
+ "attention_mask": attention_mask,
1088
+ }
1089
+ )
1090
+ return model_inputs
1091
+
1092
+ @staticmethod
1093
+ def _reorder_cache(past_key_values, beam_idx):
1094
+ reordered_past = ()
1095
+ for layer_past in past_key_values:
1096
+ reordered_past += (
1097
+ tuple(
1098
+ past_state.index_select(0, beam_idx.to(past_state.device))
1099
+ for past_state in layer_past
1100
+ ),
1101
+ )
1102
+ return reordered_past
1103
+
1104
+
1105
+ @add_start_docstrings(
1106
+ """
1107
+ The OLMoE Model transformer with a sequence classification head on top (linear layer).
1108
+
1109
+ [`OlmoeForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1110
+ (e.g. GPT-2) do.
1111
+
1112
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1113
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1114
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1115
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1116
+ each row of the batch).
1117
+ """,
1118
+ OLMOE_START_DOCSTRING,
1119
+ )
1120
+ class OlmoeForSequenceClassification(OlmoePreTrainedModel):
1121
+ def __init__(self, config):
1122
+ super().__init__(config)
1123
+ self.num_labels = config.num_labels
1124
+ self.model = OlmoeModel(config)
1125
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1126
+
1127
+ # Initialize weights and apply final processing
1128
+ self.post_init()
1129
+
1130
+ def get_input_embeddings(self):
1131
+ return self.model.embed_tokens
1132
+
1133
+ def set_input_embeddings(self, value):
1134
+ self.model.embed_tokens = value
1135
+
1136
+ @add_start_docstrings_to_model_forward(OLMOE_INPUTS_DOCSTRING)
1137
+ def forward(
1138
+ self,
1139
+ input_ids: torch.LongTensor = None,
1140
+ attention_mask: Optional[torch.Tensor] = None,
1141
+ position_ids: Optional[torch.LongTensor] = None,
1142
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1143
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1144
+ labels: Optional[torch.LongTensor] = None,
1145
+ use_cache: Optional[bool] = None,
1146
+ output_attentions: Optional[bool] = None,
1147
+ output_hidden_states: Optional[bool] = None,
1148
+ output_router_logits: Optional[bool] = None,
1149
+ return_dict: Optional[bool] = None,
1150
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1151
+ r"""
1152
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1153
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1154
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1155
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1156
+ """
1157
+ return_dict = (
1158
+ return_dict if return_dict is not None else self.config.use_return_dict
1159
+ )
1160
+
1161
+ transformer_outputs = self.model(
1162
+ input_ids,
1163
+ attention_mask=attention_mask,
1164
+ position_ids=position_ids,
1165
+ past_key_values=past_key_values,
1166
+ inputs_embeds=inputs_embeds,
1167
+ use_cache=use_cache,
1168
+ output_attentions=output_attentions,
1169
+ output_hidden_states=output_hidden_states,
1170
+ output_router_logits=output_router_logits,
1171
+ return_dict=return_dict,
1172
+ )
1173
+ hidden_states = transformer_outputs[0]
1174
+ logits = self.score(hidden_states)
1175
+
1176
+ if input_ids is not None:
1177
+ batch_size = input_ids.shape[0]
1178
+ else:
1179
+ batch_size = inputs_embeds.shape[0]
1180
+
1181
+ if self.config.pad_token_id is None and batch_size != 1:
1182
+ raise ValueError(
1183
+ "Cannot handle batch sizes > 1 if no padding token is defined."
1184
+ )
1185
+ if self.config.pad_token_id is None:
1186
+ sequence_lengths = -1
1187
+ else:
1188
+ if input_ids is not None:
1189
+ sequence_lengths = (
1190
+ torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1
1191
+ ).to(logits.device)
1192
+ else:
1193
+ sequence_lengths = -1
1194
+
1195
+ pooled_logits = logits[
1196
+ torch.arange(batch_size, device=logits.device), sequence_lengths
1197
+ ]
1198
+
1199
+ loss = None
1200
+ if labels is not None:
1201
+ labels = labels.to(logits.device)
1202
+ if self.config.problem_type is None:
1203
+ if self.num_labels == 1:
1204
+ self.config.problem_type = "regression"
1205
+ elif self.num_labels > 1 and (
1206
+ labels.dtype == torch.long or labels.dtype == torch.int
1207
+ ):
1208
+ self.config.problem_type = "single_label_classification"
1209
+ else:
1210
+ self.config.problem_type = "multi_label_classification"
1211
+
1212
+ if self.config.problem_type == "regression":
1213
+ loss_fct = MSELoss()
1214
+ if self.num_labels == 1:
1215
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1216
+ else:
1217
+ loss = loss_fct(pooled_logits, labels)
1218
+ elif self.config.problem_type == "single_label_classification":
1219
+ loss_fct = CrossEntropyLoss()
1220
+ loss = loss_fct(
1221
+ pooled_logits.view(-1, self.num_labels), labels.view(-1)
1222
+ )
1223
+ elif self.config.problem_type == "multi_label_classification":
1224
+ loss_fct = BCEWithLogitsLoss()
1225
+ loss = loss_fct(pooled_logits, labels)
1226
+ if not return_dict:
1227
+ output = (pooled_logits,) + transformer_outputs[1:]
1228
+ return ((loss,) + output) if loss is not None else output
1229
+
1230
+ return SequenceClassifierOutputWithPast(
1231
+ loss=loss,
1232
+ logits=pooled_logits,
1233
+ past_key_values=transformer_outputs.past_key_values,
1234
+ hidden_states=transformer_outputs.hidden_states,
1235
+ attentions=transformer_outputs.attentions,
1236
+ )
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:540666aba8a18ea0b26e7a71f31b07cba694c1f6e90cac5c1b81e17f9396f1f5
3
+ size 230854142
tokenizer_config.json ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_eos_token": false,
4
+ "add_prefix_space": false,
5
+ "added_tokens_decoder": {
6
+ "0": {
7
+ "content": "<|endoftext|>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false,
12
+ "special": true
13
+ },
14
+ "1": {
15
+ "content": "<|padding|>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false,
20
+ "special": true
21
+ },
22
+ "50254": {
23
+ "content": " ",
24
+ "lstrip": false,
25
+ "normalized": true,
26
+ "rstrip": false,
27
+ "single_word": false,
28
+ "special": false
29
+ },
30
+ "50255": {
31
+ "content": " ",
32
+ "lstrip": false,
33
+ "normalized": true,
34
+ "rstrip": false,
35
+ "single_word": false,
36
+ "special": false
37
+ },
38
+ "50256": {
39
+ "content": " ",
40
+ "lstrip": false,
41
+ "normalized": true,
42
+ "rstrip": false,
43
+ "single_word": false,
44
+ "special": false
45
+ },
46
+ "50257": {
47
+ "content": " ",
48
+ "lstrip": false,
49
+ "normalized": true,
50
+ "rstrip": false,
51
+ "single_word": false,
52
+ "special": false
53
+ },
54
+ "50258": {
55
+ "content": " ",
56
+ "lstrip": false,
57
+ "normalized": true,
58
+ "rstrip": false,
59
+ "single_word": false,
60
+ "special": false
61
+ },
62
+ "50259": {
63
+ "content": " ",
64
+ "lstrip": false,
65
+ "normalized": true,
66
+ "rstrip": false,
67
+ "single_word": false,
68
+ "special": false
69
+ },
70
+ "50260": {
71
+ "content": " ",
72
+ "lstrip": false,
73
+ "normalized": true,
74
+ "rstrip": false,
75
+ "single_word": false,
76
+ "special": false
77
+ },
78
+ "50261": {
79
+ "content": " ",
80
+ "lstrip": false,
81
+ "normalized": true,
82
+ "rstrip": false,
83
+ "single_word": false,
84
+ "special": false
85
+ },
86
+ "50262": {
87
+ "content": " ",
88
+ "lstrip": false,
89
+ "normalized": true,
90
+ "rstrip": false,
91
+ "single_word": false,
92
+ "special": false
93
+ },
94
+ "50263": {
95
+ "content": " ",
96
+ "lstrip": false,
97
+ "normalized": true,
98
+ "rstrip": false,
99
+ "single_word": false,
100
+ "special": false
101
+ },
102
+ "50264": {
103
+ "content": " ",
104
+ "lstrip": false,
105
+ "normalized": true,
106
+ "rstrip": false,
107
+ "single_word": false,
108
+ "special": false
109
+ },
110
+ "50265": {
111
+ "content": " ",
112
+ "lstrip": false,
113
+ "normalized": true,
114
+ "rstrip": false,
115
+ "single_word": false,
116
+ "special": false
117
+ },
118
+ "50266": {
119
+ "content": " ",
120
+ "lstrip": false,
121
+ "normalized": true,
122
+ "rstrip": false,
123
+ "single_word": false,
124
+ "special": false
125
+ },
126
+ "50267": {
127
+ "content": " ",
128
+ "lstrip": false,
129
+ "normalized": true,
130
+ "rstrip": false,
131
+ "single_word": false,
132
+ "special": false
133
+ },
134
+ "50268": {
135
+ "content": " ",
136
+ "lstrip": false,
137
+ "normalized": true,
138
+ "rstrip": false,
139
+ "single_word": false,
140
+ "special": false
141
+ },
142
+ "50269": {
143
+ "content": " ",
144
+ "lstrip": false,
145
+ "normalized": true,
146
+ "rstrip": false,
147
+ "single_word": false,
148
+ "special": false
149
+ },
150
+ "50270": {
151
+ "content": " ",
152
+ "lstrip": false,
153
+ "normalized": true,
154
+ "rstrip": false,
155
+ "single_word": false,
156
+ "special": false
157
+ },
158
+ "50271": {
159
+ "content": " ",
160
+ "lstrip": false,
161
+ "normalized": true,
162
+ "rstrip": false,
163
+ "single_word": false,
164
+ "special": false
165
+ },
166
+ "50272": {
167
+ "content": " ",
168
+ "lstrip": false,
169
+ "normalized": true,
170
+ "rstrip": false,
171
+ "single_word": false,
172
+ "special": false
173
+ },
174
+ "50273": {
175
+ "content": " ",
176
+ "lstrip": false,
177
+ "normalized": true,
178
+ "rstrip": false,
179
+ "single_word": false,
180
+ "special": false
181
+ },
182
+ "50274": {
183
+ "content": " ",
184
+ "lstrip": false,
185
+ "normalized": true,
186
+ "rstrip": false,
187
+ "single_word": false,
188
+ "special": false
189
+ },
190
+ "50275": {
191
+ "content": " ",
192
+ "lstrip": false,
193
+ "normalized": true,
194
+ "rstrip": false,
195
+ "single_word": false,
196
+ "special": false
197
+ },
198
+ "50276": {
199
+ "content": " ",
200
+ "lstrip": false,
201
+ "normalized": true,
202
+ "rstrip": false,
203
+ "single_word": false,
204
+ "special": false
205
+ },
206
+ "50277": {
207
+ "content": "|||EMAIL_ADDRESS|||",
208
+ "lstrip": false,
209
+ "normalized": true,
210
+ "rstrip": false,
211
+ "single_word": false,
212
+ "special": false
213
+ },
214
+ "50278": {
215
+ "content": "|||PHONE_NUMBER|||",
216
+ "lstrip": false,
217
+ "normalized": true,
218
+ "rstrip": false,
219
+ "single_word": false,
220
+ "special": false
221
+ },
222
+ "50279": {
223
+ "content": "|||IP_ADDRESS|||",
224
+ "lstrip": false,
225
+ "normalized": true,
226
+ "rstrip": false,
227
+ "single_word": false,
228
+ "special": true
229
+ },
230
+ "50280": {
231
+ "content": "<pad>",
232
+ "lstrip": false,
233
+ "normalized": false,
234
+ "rstrip": false,
235
+ "single_word": false,
236
+ "special": true
237
+ }
238
+ },
239
+ "bos_token": "|||IP_ADDRESS|||",
240
+ "chat_template": "{{ bos_token }}{% for message in messages %}{% if message['role'] == 'system' %}{{ '<|system|>\n' + message['content'] + '\n' }}{% elif message['role'] == 'user' %}{{ '<|user|>\n' + message['content'] + '\n' }}{% elif message['role'] == 'assistant' %}{% if not loop.last %}{{ '<|assistant|>\n' + message['content'] + eos_token + '\n' }}{% else %}{{ '<|assistant|>\n' + message['content'] + eos_token }}{% endif %}{% endif %}{% if loop.last and add_generation_prompt %}{{ '<|assistant|>\n' }}{% endif %}{% endfor %}",
241
+ "clean_up_tokenization_spaces": false,
242
+ "eos_token": "|||IP_ADDRESS|||",
243
+ "extra_special_tokens": {},
244
+ "model_max_length": 1000000000000000019884624838656,
245
+ "pad_token": "<pad>",
246
+ "tokenizer_class": "GPTNeoXTokenizer",
247
+ "unk_token": null
248
+ }