Text Generation
Transformers
PyTorch
English
crystalcoder
llm
code
custom_code
Eval Results
yukiontheiceberg commited on
Commit
bd4b02d
1 Parent(s): c5386f2

Upload folder using huggingface_hub

Browse files
config.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "CrystalCoder",
3
+ "activation_function": "swiglu",
4
+ "architectures": [
5
+ "CrystalCoderLMHeadModel"
6
+ ],
7
+ "attn_pdrop": 0.0,
8
+ "auto_map": {
9
+ "AutoConfig": "configuration_crystalcoder.CrystalCoderConfig",
10
+ "AutoModel": "modeling_crystalcoder.CrystalCoderModel",
11
+ "AutoModelForCausalLM": "modeling_crystalcoder.CrystalCoderLMHeadModel"
12
+ },
13
+ "bos_token_id": 1,
14
+ "embd_pdrop": 0.0,
15
+ "eos_token_id": 2,
16
+ "initializer_range": 0.02,
17
+ "layer_norm_epsilon": 1e-05,
18
+ "model_type": "crystalcoder",
19
+ "mup_embeddings_scale": 14.6,
20
+ "mup_output_alpha": 2.22,
21
+ "mup_scale_qk_dot_by_d": true,
22
+ "mup_width_scale": 0.0625,
23
+ "n_embd": 4096,
24
+ "n_head": 32,
25
+ "n_inner": 10922,
26
+ "n_layer": 32,
27
+ "n_positions": 2048,
28
+ "position_embedding_type": "rotary",
29
+ "reorder_and_upcast_attn": false,
30
+ "resid_pdrop": 0.0,
31
+ "rotary_dim": 32,
32
+ "scale_attn_by_inverse_layer_idx": false,
33
+ "scale_attn_weights": true,
34
+ "torch_dtype": "float32",
35
+ "transformers_version": "4.35.2",
36
+ "use_cache": true,
37
+ "vocab_size": 32032
38
+ }
configuration_crystalcoder.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ CrystalCoder configuration"""
2
+
3
+ from transformers.configuration_utils import PretrainedConfig
4
+ from transformers.utils import logging
5
+
6
+
7
+ logger = logging.get_logger(__name__)
8
+
9
+
10
+ class CrystalCoderConfig(PretrainedConfig):
11
+ """
12
+ This is the configuration class to store the configuration of a [`CrystalCoderModel`]. It is used to instantiate a CrystalCoder
13
+ model according to the specified arguments, defining the model architecture.
14
+
15
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
16
+ documentation from [`PretrainedConfig`] for more information.
17
+
18
+
19
+ Args:
20
+ vocab_size (`int`, *optional*, defaults to 50257):
21
+ Vocabulary size of the CrystalCoder model. Defines the number of different tokens that can be represented by the
22
+ `inputs_ids` passed when calling [`CrystalCoderModel`].
23
+ n_positions (`int`, *optional*, defaults to 1024):
24
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
25
+ just in case (e.g., 512 or 1024 or 2048).
26
+ n_embd (`int`, *optional*, defaults to 768):
27
+ Dimensionality of the embeddings and hidden states.
28
+ n_layer (`int`, *optional*, defaults to 12):
29
+ Number of hidden layers in the Transformer encoder.
30
+ n_head (`int`, *optional*, defaults to 12):
31
+ Number of attention heads for each attention layer in the Transformer encoder.
32
+ n_inner (`int`, *optional*, defaults to None):
33
+ Dimensionality of the inner feed-forward layers. `None` will set it to 4 times n_embd
34
+ activation_function (`str`, *optional*, defaults to `"gelu"`):
35
+ Activation function, to be selected in the list `["relu", "silu", "gelu", "tanh", "gelu_new", "swiglu"]`.
36
+ resid_pdrop (`float`, *optional*, defaults to 0.1):
37
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
38
+ embd_pdrop (`float`, *optional*, defaults to 0.1):
39
+ The dropout ratio for the embeddings.
40
+ attn_pdrop (`float`, *optional*, defaults to 0.1):
41
+ The dropout ratio for the attention.
42
+ layer_norm_epsilon (`float`, *optional*, defaults to 1e-5):
43
+ The epsilon to use in the layer normalization layers.
44
+ initializer_range (`float`, *optional*, defaults to 0.02):
45
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
46
+ scale_attn_weights (`bool`, *optional*, defaults to `True`):
47
+ Scale attention weights by dividing by sqrt(hidden_size)..
48
+ use_cache (`bool`, *optional*, defaults to `True`):
49
+ Whether or not the model should return the last key/values attentions (not used by all models).
50
+ scale_attn_by_inverse_layer_idx (`bool`, *optional*, defaults to `False`):
51
+ Whether to additionally scale attention weights by `1 / layer_idx + 1`.
52
+ reorder_and_upcast_attn (`bool`, *optional*, defaults to `False`):
53
+ Whether to scale keys (K) prior to computing attention (dot-product) and upcast attention
54
+ dot-product/softmax to float() when training with mixed precision.
55
+ position_embedding_type (`str`, *optional*, defaults to `"learned"`):
56
+ Positional embedding can be either `"alibi"`, `"learned"`, or `"learned"`.
57
+ rotary_dim (`int`, *optional*, defaults to `n_embd / n_head`):
58
+ The dimension along which to apply rope.
59
+ mup_width_scale (`float`, *optional*, defaults to 1.0):
60
+ muP parameter to scale learning rate and initializers. Calculated as (`d_model,0 / d_model`), where
61
+ `d_model` is the model's width and `d_model,0` is the proxy model's width.
62
+ mup_embeddings_scale (`float`, *optional*, defaults to 1.0):
63
+ muP parameter to scale token and position embeddings.
64
+ mup_output_alpha (`float`, *optional*, defaults to 1.0):
65
+ muP parameter to scale output logits (`output_logits_scale = mup_output_alpha * mup_width_scale`).
66
+ mup_scale_qk_dot_by_d (`bool`, *optional*, defaults to `False`):
67
+ Scale attention weights by dividing by hidden_size instead of sqrt(hidden_size). Need to set
68
+ scale_attn_weights to `True` as well.
69
+
70
+ Example:
71
+
72
+ ```python
73
+ >>> from transformers import CrystalCoderConfig, CrystalCoderModel
74
+
75
+ >>> # Initializing a CrystalCoder configuration
76
+ >>> configuration = CrystalCoderConfig()
77
+
78
+ >>> # Initializing a model (with random weights) from the configuration
79
+ >>> model = CrystalCoderModel(configuration)
80
+
81
+ >>> # Accessing the model configuration
82
+ >>> configuration = model.config
83
+ ```"""
84
+
85
+ model_type = "crystalcoder"
86
+ keys_to_ignore_at_inference = ["past_key_values"]
87
+ attribute_map = {
88
+ "hidden_size": "n_embd",
89
+ "max_position_embeddings": "n_positions",
90
+ "num_attention_heads": "n_head",
91
+ "num_hidden_layers": "n_layer",
92
+ }
93
+
94
+ def __init__(
95
+ self,
96
+ vocab_size=32032,
97
+ n_positions=2048,
98
+ n_embd=4096,
99
+ n_layer=32,
100
+ n_head=32,
101
+ n_inner=None,
102
+ activation_function="swiglu",
103
+ resid_pdrop=0.1,
104
+ embd_pdrop=0.1,
105
+ attn_pdrop=0.1,
106
+ layer_norm_epsilon=1e-5,
107
+ initializer_range=0.02,
108
+ scale_attn_weights=True,
109
+ use_cache=True,
110
+ bos_token_id=1,
111
+ eos_token_id=2,
112
+ scale_attn_by_inverse_layer_idx=False,
113
+ reorder_and_upcast_attn=False,
114
+ position_embedding_type="rotary",
115
+ rotary_dim=None,
116
+ mup_width_scale=1.0,
117
+ mup_embeddings_scale=1.0,
118
+ mup_output_alpha=1.0,
119
+ mup_scale_qk_dot_by_d=False,
120
+ **kwargs,
121
+ ):
122
+ self.vocab_size = vocab_size
123
+ self.n_positions = n_positions
124
+ self.n_embd = n_embd
125
+ self.n_layer = n_layer
126
+ self.n_head = n_head
127
+ self.n_inner = n_inner
128
+ self.activation_function = activation_function
129
+ self.resid_pdrop = resid_pdrop
130
+ self.embd_pdrop = embd_pdrop
131
+ self.attn_pdrop = attn_pdrop
132
+ self.layer_norm_epsilon = layer_norm_epsilon
133
+ self.initializer_range = initializer_range
134
+ self.scale_attn_weights = scale_attn_weights
135
+ self.use_cache = use_cache
136
+ self.scale_attn_by_inverse_layer_idx = scale_attn_by_inverse_layer_idx
137
+ self.reorder_and_upcast_attn = reorder_and_upcast_attn
138
+
139
+ self.bos_token_id = bos_token_id
140
+ self.eos_token_id = eos_token_id
141
+
142
+ self.position_embedding_type = position_embedding_type
143
+ self.rotary_dim = rotary_dim
144
+ self.mup_width_scale = mup_width_scale
145
+ self.mup_embeddings_scale = mup_embeddings_scale
146
+ self.mup_output_alpha = mup_output_alpha
147
+ self.mup_scale_qk_dot_by_d = mup_scale_qk_dot_by_d
148
+
149
+ super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 2,
5
+ "transformers_version": "4.35.2"
6
+ }
model-00001-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:db76f3a5c43b6db84b99bf51eb26aa78b073d5eacb753c685964e458b5f48643
3
+ size 4999919232
model-00002-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cc7f082cea2f13085254ce20df6f30c4843747dcc24ff61eeedc42297dd188a2
3
+ size 4833059472
model-00003-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4da4c820cdf3473aad2cca5576b5f752e8ab3c7ec668854fee686f8f1d38c4a3
3
+ size 4833059528
model-00004-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8f9fb963d2848fdd86858ad6c58f8753cf899a0b95572da8e1d5f7e2661cc12e
3
+ size 4833059528
model-00005-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:785e921c7231f021e7ddf9231536a2ed39177552dadd84cf0e1c71f45a2468e0
3
+ size 4833059528
model-00006-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1158060ce24556971b7f13c3eecb42fc3ff9f2818cb08dbb7c71ad2e19069e97
3
+ size 1969005400
model.safetensors.index.json ADDED
@@ -0,0 +1,458 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 26301114880
4
+ },
5
+ "weight_map": {
6
+ "transformer.h.0.attn.c_attn.bias": "model-00001-of-00006.safetensors",
7
+ "transformer.h.0.attn.c_attn.weight": "model-00001-of-00006.safetensors",
8
+ "transformer.h.0.attn.c_proj.bias": "model-00001-of-00006.safetensors",
9
+ "transformer.h.0.attn.c_proj.weight": "model-00001-of-00006.safetensors",
10
+ "transformer.h.0.ln_1.bias": "model-00001-of-00006.safetensors",
11
+ "transformer.h.0.ln_1.weight": "model-00001-of-00006.safetensors",
12
+ "transformer.h.0.ln_2.bias": "model-00001-of-00006.safetensors",
13
+ "transformer.h.0.ln_2.weight": "model-00001-of-00006.safetensors",
14
+ "transformer.h.0.mlp.c_fc.bias": "model-00001-of-00006.safetensors",
15
+ "transformer.h.0.mlp.c_fc.weight": "model-00001-of-00006.safetensors",
16
+ "transformer.h.0.mlp.c_fc2.bias": "model-00001-of-00006.safetensors",
17
+ "transformer.h.0.mlp.c_fc2.weight": "model-00001-of-00006.safetensors",
18
+ "transformer.h.0.mlp.c_proj.bias": "model-00001-of-00006.safetensors",
19
+ "transformer.h.0.mlp.c_proj.weight": "model-00001-of-00006.safetensors",
20
+ "transformer.h.1.attn.c_attn.bias": "model-00001-of-00006.safetensors",
21
+ "transformer.h.1.attn.c_attn.weight": "model-00001-of-00006.safetensors",
22
+ "transformer.h.1.attn.c_proj.bias": "model-00001-of-00006.safetensors",
23
+ "transformer.h.1.attn.c_proj.weight": "model-00001-of-00006.safetensors",
24
+ "transformer.h.1.ln_1.bias": "model-00001-of-00006.safetensors",
25
+ "transformer.h.1.ln_1.weight": "model-00001-of-00006.safetensors",
26
+ "transformer.h.1.ln_2.bias": "model-00001-of-00006.safetensors",
27
+ "transformer.h.1.ln_2.weight": "model-00001-of-00006.safetensors",
28
+ "transformer.h.1.mlp.c_fc.bias": "model-00001-of-00006.safetensors",
29
+ "transformer.h.1.mlp.c_fc.weight": "model-00001-of-00006.safetensors",
30
+ "transformer.h.1.mlp.c_fc2.bias": "model-00001-of-00006.safetensors",
31
+ "transformer.h.1.mlp.c_fc2.weight": "model-00001-of-00006.safetensors",
32
+ "transformer.h.1.mlp.c_proj.bias": "model-00001-of-00006.safetensors",
33
+ "transformer.h.1.mlp.c_proj.weight": "model-00001-of-00006.safetensors",
34
+ "transformer.h.10.attn.c_attn.bias": "model-00002-of-00006.safetensors",
35
+ "transformer.h.10.attn.c_attn.weight": "model-00002-of-00006.safetensors",
36
+ "transformer.h.10.attn.c_proj.bias": "model-00002-of-00006.safetensors",
37
+ "transformer.h.10.attn.c_proj.weight": "model-00002-of-00006.safetensors",
38
+ "transformer.h.10.ln_1.bias": "model-00002-of-00006.safetensors",
39
+ "transformer.h.10.ln_1.weight": "model-00002-of-00006.safetensors",
40
+ "transformer.h.10.ln_2.bias": "model-00002-of-00006.safetensors",
41
+ "transformer.h.10.ln_2.weight": "model-00002-of-00006.safetensors",
42
+ "transformer.h.10.mlp.c_fc.bias": "model-00002-of-00006.safetensors",
43
+ "transformer.h.10.mlp.c_fc.weight": "model-00002-of-00006.safetensors",
44
+ "transformer.h.10.mlp.c_fc2.bias": "model-00002-of-00006.safetensors",
45
+ "transformer.h.10.mlp.c_fc2.weight": "model-00002-of-00006.safetensors",
46
+ "transformer.h.10.mlp.c_proj.bias": "model-00002-of-00006.safetensors",
47
+ "transformer.h.10.mlp.c_proj.weight": "model-00002-of-00006.safetensors",
48
+ "transformer.h.11.attn.c_attn.bias": "model-00002-of-00006.safetensors",
49
+ "transformer.h.11.attn.c_attn.weight": "model-00002-of-00006.safetensors",
50
+ "transformer.h.11.attn.c_proj.bias": "model-00002-of-00006.safetensors",
51
+ "transformer.h.11.attn.c_proj.weight": "model-00002-of-00006.safetensors",
52
+ "transformer.h.11.ln_1.bias": "model-00002-of-00006.safetensors",
53
+ "transformer.h.11.ln_1.weight": "model-00002-of-00006.safetensors",
54
+ "transformer.h.11.ln_2.bias": "model-00002-of-00006.safetensors",
55
+ "transformer.h.11.ln_2.weight": "model-00002-of-00006.safetensors",
56
+ "transformer.h.11.mlp.c_fc.bias": "model-00002-of-00006.safetensors",
57
+ "transformer.h.11.mlp.c_fc.weight": "model-00002-of-00006.safetensors",
58
+ "transformer.h.11.mlp.c_fc2.bias": "model-00003-of-00006.safetensors",
59
+ "transformer.h.11.mlp.c_fc2.weight": "model-00003-of-00006.safetensors",
60
+ "transformer.h.11.mlp.c_proj.bias": "model-00003-of-00006.safetensors",
61
+ "transformer.h.11.mlp.c_proj.weight": "model-00003-of-00006.safetensors",
62
+ "transformer.h.12.attn.c_attn.bias": "model-00003-of-00006.safetensors",
63
+ "transformer.h.12.attn.c_attn.weight": "model-00003-of-00006.safetensors",
64
+ "transformer.h.12.attn.c_proj.bias": "model-00003-of-00006.safetensors",
65
+ "transformer.h.12.attn.c_proj.weight": "model-00003-of-00006.safetensors",
66
+ "transformer.h.12.ln_1.bias": "model-00003-of-00006.safetensors",
67
+ "transformer.h.12.ln_1.weight": "model-00003-of-00006.safetensors",
68
+ "transformer.h.12.ln_2.bias": "model-00003-of-00006.safetensors",
69
+ "transformer.h.12.ln_2.weight": "model-00003-of-00006.safetensors",
70
+ "transformer.h.12.mlp.c_fc.bias": "model-00003-of-00006.safetensors",
71
+ "transformer.h.12.mlp.c_fc.weight": "model-00003-of-00006.safetensors",
72
+ "transformer.h.12.mlp.c_fc2.bias": "model-00003-of-00006.safetensors",
73
+ "transformer.h.12.mlp.c_fc2.weight": "model-00003-of-00006.safetensors",
74
+ "transformer.h.12.mlp.c_proj.bias": "model-00003-of-00006.safetensors",
75
+ "transformer.h.12.mlp.c_proj.weight": "model-00003-of-00006.safetensors",
76
+ "transformer.h.13.attn.c_attn.bias": "model-00003-of-00006.safetensors",
77
+ "transformer.h.13.attn.c_attn.weight": "model-00003-of-00006.safetensors",
78
+ "transformer.h.13.attn.c_proj.bias": "model-00003-of-00006.safetensors",
79
+ "transformer.h.13.attn.c_proj.weight": "model-00003-of-00006.safetensors",
80
+ "transformer.h.13.ln_1.bias": "model-00003-of-00006.safetensors",
81
+ "transformer.h.13.ln_1.weight": "model-00003-of-00006.safetensors",
82
+ "transformer.h.13.ln_2.bias": "model-00003-of-00006.safetensors",
83
+ "transformer.h.13.ln_2.weight": "model-00003-of-00006.safetensors",
84
+ "transformer.h.13.mlp.c_fc.bias": "model-00003-of-00006.safetensors",
85
+ "transformer.h.13.mlp.c_fc.weight": "model-00003-of-00006.safetensors",
86
+ "transformer.h.13.mlp.c_fc2.bias": "model-00003-of-00006.safetensors",
87
+ "transformer.h.13.mlp.c_fc2.weight": "model-00003-of-00006.safetensors",
88
+ "transformer.h.13.mlp.c_proj.bias": "model-00003-of-00006.safetensors",
89
+ "transformer.h.13.mlp.c_proj.weight": "model-00003-of-00006.safetensors",
90
+ "transformer.h.14.attn.c_attn.bias": "model-00003-of-00006.safetensors",
91
+ "transformer.h.14.attn.c_attn.weight": "model-00003-of-00006.safetensors",
92
+ "transformer.h.14.attn.c_proj.bias": "model-00003-of-00006.safetensors",
93
+ "transformer.h.14.attn.c_proj.weight": "model-00003-of-00006.safetensors",
94
+ "transformer.h.14.ln_1.bias": "model-00003-of-00006.safetensors",
95
+ "transformer.h.14.ln_1.weight": "model-00003-of-00006.safetensors",
96
+ "transformer.h.14.ln_2.bias": "model-00003-of-00006.safetensors",
97
+ "transformer.h.14.ln_2.weight": "model-00003-of-00006.safetensors",
98
+ "transformer.h.14.mlp.c_fc.bias": "model-00003-of-00006.safetensors",
99
+ "transformer.h.14.mlp.c_fc.weight": "model-00003-of-00006.safetensors",
100
+ "transformer.h.14.mlp.c_fc2.bias": "model-00003-of-00006.safetensors",
101
+ "transformer.h.14.mlp.c_fc2.weight": "model-00003-of-00006.safetensors",
102
+ "transformer.h.14.mlp.c_proj.bias": "model-00003-of-00006.safetensors",
103
+ "transformer.h.14.mlp.c_proj.weight": "model-00003-of-00006.safetensors",
104
+ "transformer.h.15.attn.c_attn.bias": "model-00003-of-00006.safetensors",
105
+ "transformer.h.15.attn.c_attn.weight": "model-00003-of-00006.safetensors",
106
+ "transformer.h.15.attn.c_proj.bias": "model-00003-of-00006.safetensors",
107
+ "transformer.h.15.attn.c_proj.weight": "model-00003-of-00006.safetensors",
108
+ "transformer.h.15.ln_1.bias": "model-00003-of-00006.safetensors",
109
+ "transformer.h.15.ln_1.weight": "model-00003-of-00006.safetensors",
110
+ "transformer.h.15.ln_2.bias": "model-00003-of-00006.safetensors",
111
+ "transformer.h.15.ln_2.weight": "model-00003-of-00006.safetensors",
112
+ "transformer.h.15.mlp.c_fc.bias": "model-00003-of-00006.safetensors",
113
+ "transformer.h.15.mlp.c_fc.weight": "model-00003-of-00006.safetensors",
114
+ "transformer.h.15.mlp.c_fc2.bias": "model-00003-of-00006.safetensors",
115
+ "transformer.h.15.mlp.c_fc2.weight": "model-00003-of-00006.safetensors",
116
+ "transformer.h.15.mlp.c_proj.bias": "model-00003-of-00006.safetensors",
117
+ "transformer.h.15.mlp.c_proj.weight": "model-00003-of-00006.safetensors",
118
+ "transformer.h.16.attn.c_attn.bias": "model-00003-of-00006.safetensors",
119
+ "transformer.h.16.attn.c_attn.weight": "model-00003-of-00006.safetensors",
120
+ "transformer.h.16.attn.c_proj.bias": "model-00003-of-00006.safetensors",
121
+ "transformer.h.16.attn.c_proj.weight": "model-00003-of-00006.safetensors",
122
+ "transformer.h.16.ln_1.bias": "model-00003-of-00006.safetensors",
123
+ "transformer.h.16.ln_1.weight": "model-00003-of-00006.safetensors",
124
+ "transformer.h.16.ln_2.bias": "model-00003-of-00006.safetensors",
125
+ "transformer.h.16.ln_2.weight": "model-00003-of-00006.safetensors",
126
+ "transformer.h.16.mlp.c_fc.bias": "model-00003-of-00006.safetensors",
127
+ "transformer.h.16.mlp.c_fc.weight": "model-00003-of-00006.safetensors",
128
+ "transformer.h.16.mlp.c_fc2.bias": "model-00003-of-00006.safetensors",
129
+ "transformer.h.16.mlp.c_fc2.weight": "model-00003-of-00006.safetensors",
130
+ "transformer.h.16.mlp.c_proj.bias": "model-00003-of-00006.safetensors",
131
+ "transformer.h.16.mlp.c_proj.weight": "model-00003-of-00006.safetensors",
132
+ "transformer.h.17.attn.c_attn.bias": "model-00003-of-00006.safetensors",
133
+ "transformer.h.17.attn.c_attn.weight": "model-00003-of-00006.safetensors",
134
+ "transformer.h.17.attn.c_proj.bias": "model-00003-of-00006.safetensors",
135
+ "transformer.h.17.attn.c_proj.weight": "model-00003-of-00006.safetensors",
136
+ "transformer.h.17.ln_1.bias": "model-00003-of-00006.safetensors",
137
+ "transformer.h.17.ln_1.weight": "model-00003-of-00006.safetensors",
138
+ "transformer.h.17.ln_2.bias": "model-00003-of-00006.safetensors",
139
+ "transformer.h.17.ln_2.weight": "model-00003-of-00006.safetensors",
140
+ "transformer.h.17.mlp.c_fc.bias": "model-00003-of-00006.safetensors",
141
+ "transformer.h.17.mlp.c_fc.weight": "model-00003-of-00006.safetensors",
142
+ "transformer.h.17.mlp.c_fc2.bias": "model-00004-of-00006.safetensors",
143
+ "transformer.h.17.mlp.c_fc2.weight": "model-00004-of-00006.safetensors",
144
+ "transformer.h.17.mlp.c_proj.bias": "model-00004-of-00006.safetensors",
145
+ "transformer.h.17.mlp.c_proj.weight": "model-00004-of-00006.safetensors",
146
+ "transformer.h.18.attn.c_attn.bias": "model-00004-of-00006.safetensors",
147
+ "transformer.h.18.attn.c_attn.weight": "model-00004-of-00006.safetensors",
148
+ "transformer.h.18.attn.c_proj.bias": "model-00004-of-00006.safetensors",
149
+ "transformer.h.18.attn.c_proj.weight": "model-00004-of-00006.safetensors",
150
+ "transformer.h.18.ln_1.bias": "model-00004-of-00006.safetensors",
151
+ "transformer.h.18.ln_1.weight": "model-00004-of-00006.safetensors",
152
+ "transformer.h.18.ln_2.bias": "model-00004-of-00006.safetensors",
153
+ "transformer.h.18.ln_2.weight": "model-00004-of-00006.safetensors",
154
+ "transformer.h.18.mlp.c_fc.bias": "model-00004-of-00006.safetensors",
155
+ "transformer.h.18.mlp.c_fc.weight": "model-00004-of-00006.safetensors",
156
+ "transformer.h.18.mlp.c_fc2.bias": "model-00004-of-00006.safetensors",
157
+ "transformer.h.18.mlp.c_fc2.weight": "model-00004-of-00006.safetensors",
158
+ "transformer.h.18.mlp.c_proj.bias": "model-00004-of-00006.safetensors",
159
+ "transformer.h.18.mlp.c_proj.weight": "model-00004-of-00006.safetensors",
160
+ "transformer.h.19.attn.c_attn.bias": "model-00004-of-00006.safetensors",
161
+ "transformer.h.19.attn.c_attn.weight": "model-00004-of-00006.safetensors",
162
+ "transformer.h.19.attn.c_proj.bias": "model-00004-of-00006.safetensors",
163
+ "transformer.h.19.attn.c_proj.weight": "model-00004-of-00006.safetensors",
164
+ "transformer.h.19.ln_1.bias": "model-00004-of-00006.safetensors",
165
+ "transformer.h.19.ln_1.weight": "model-00004-of-00006.safetensors",
166
+ "transformer.h.19.ln_2.bias": "model-00004-of-00006.safetensors",
167
+ "transformer.h.19.ln_2.weight": "model-00004-of-00006.safetensors",
168
+ "transformer.h.19.mlp.c_fc.bias": "model-00004-of-00006.safetensors",
169
+ "transformer.h.19.mlp.c_fc.weight": "model-00004-of-00006.safetensors",
170
+ "transformer.h.19.mlp.c_fc2.bias": "model-00004-of-00006.safetensors",
171
+ "transformer.h.19.mlp.c_fc2.weight": "model-00004-of-00006.safetensors",
172
+ "transformer.h.19.mlp.c_proj.bias": "model-00004-of-00006.safetensors",
173
+ "transformer.h.19.mlp.c_proj.weight": "model-00004-of-00006.safetensors",
174
+ "transformer.h.2.attn.c_attn.bias": "model-00001-of-00006.safetensors",
175
+ "transformer.h.2.attn.c_attn.weight": "model-00001-of-00006.safetensors",
176
+ "transformer.h.2.attn.c_proj.bias": "model-00001-of-00006.safetensors",
177
+ "transformer.h.2.attn.c_proj.weight": "model-00001-of-00006.safetensors",
178
+ "transformer.h.2.ln_1.bias": "model-00001-of-00006.safetensors",
179
+ "transformer.h.2.ln_1.weight": "model-00001-of-00006.safetensors",
180
+ "transformer.h.2.ln_2.bias": "model-00001-of-00006.safetensors",
181
+ "transformer.h.2.ln_2.weight": "model-00001-of-00006.safetensors",
182
+ "transformer.h.2.mlp.c_fc.bias": "model-00001-of-00006.safetensors",
183
+ "transformer.h.2.mlp.c_fc.weight": "model-00001-of-00006.safetensors",
184
+ "transformer.h.2.mlp.c_fc2.bias": "model-00001-of-00006.safetensors",
185
+ "transformer.h.2.mlp.c_fc2.weight": "model-00001-of-00006.safetensors",
186
+ "transformer.h.2.mlp.c_proj.bias": "model-00001-of-00006.safetensors",
187
+ "transformer.h.2.mlp.c_proj.weight": "model-00001-of-00006.safetensors",
188
+ "transformer.h.20.attn.c_attn.bias": "model-00004-of-00006.safetensors",
189
+ "transformer.h.20.attn.c_attn.weight": "model-00004-of-00006.safetensors",
190
+ "transformer.h.20.attn.c_proj.bias": "model-00004-of-00006.safetensors",
191
+ "transformer.h.20.attn.c_proj.weight": "model-00004-of-00006.safetensors",
192
+ "transformer.h.20.ln_1.bias": "model-00004-of-00006.safetensors",
193
+ "transformer.h.20.ln_1.weight": "model-00004-of-00006.safetensors",
194
+ "transformer.h.20.ln_2.bias": "model-00004-of-00006.safetensors",
195
+ "transformer.h.20.ln_2.weight": "model-00004-of-00006.safetensors",
196
+ "transformer.h.20.mlp.c_fc.bias": "model-00004-of-00006.safetensors",
197
+ "transformer.h.20.mlp.c_fc.weight": "model-00004-of-00006.safetensors",
198
+ "transformer.h.20.mlp.c_fc2.bias": "model-00004-of-00006.safetensors",
199
+ "transformer.h.20.mlp.c_fc2.weight": "model-00004-of-00006.safetensors",
200
+ "transformer.h.20.mlp.c_proj.bias": "model-00004-of-00006.safetensors",
201
+ "transformer.h.20.mlp.c_proj.weight": "model-00004-of-00006.safetensors",
202
+ "transformer.h.21.attn.c_attn.bias": "model-00004-of-00006.safetensors",
203
+ "transformer.h.21.attn.c_attn.weight": "model-00004-of-00006.safetensors",
204
+ "transformer.h.21.attn.c_proj.bias": "model-00004-of-00006.safetensors",
205
+ "transformer.h.21.attn.c_proj.weight": "model-00004-of-00006.safetensors",
206
+ "transformer.h.21.ln_1.bias": "model-00004-of-00006.safetensors",
207
+ "transformer.h.21.ln_1.weight": "model-00004-of-00006.safetensors",
208
+ "transformer.h.21.ln_2.bias": "model-00004-of-00006.safetensors",
209
+ "transformer.h.21.ln_2.weight": "model-00004-of-00006.safetensors",
210
+ "transformer.h.21.mlp.c_fc.bias": "model-00004-of-00006.safetensors",
211
+ "transformer.h.21.mlp.c_fc.weight": "model-00004-of-00006.safetensors",
212
+ "transformer.h.21.mlp.c_fc2.bias": "model-00004-of-00006.safetensors",
213
+ "transformer.h.21.mlp.c_fc2.weight": "model-00004-of-00006.safetensors",
214
+ "transformer.h.21.mlp.c_proj.bias": "model-00004-of-00006.safetensors",
215
+ "transformer.h.21.mlp.c_proj.weight": "model-00004-of-00006.safetensors",
216
+ "transformer.h.22.attn.c_attn.bias": "model-00004-of-00006.safetensors",
217
+ "transformer.h.22.attn.c_attn.weight": "model-00004-of-00006.safetensors",
218
+ "transformer.h.22.attn.c_proj.bias": "model-00004-of-00006.safetensors",
219
+ "transformer.h.22.attn.c_proj.weight": "model-00004-of-00006.safetensors",
220
+ "transformer.h.22.ln_1.bias": "model-00004-of-00006.safetensors",
221
+ "transformer.h.22.ln_1.weight": "model-00004-of-00006.safetensors",
222
+ "transformer.h.22.ln_2.bias": "model-00004-of-00006.safetensors",
223
+ "transformer.h.22.ln_2.weight": "model-00004-of-00006.safetensors",
224
+ "transformer.h.22.mlp.c_fc.bias": "model-00004-of-00006.safetensors",
225
+ "transformer.h.22.mlp.c_fc.weight": "model-00004-of-00006.safetensors",
226
+ "transformer.h.22.mlp.c_fc2.bias": "model-00004-of-00006.safetensors",
227
+ "transformer.h.22.mlp.c_fc2.weight": "model-00004-of-00006.safetensors",
228
+ "transformer.h.22.mlp.c_proj.bias": "model-00004-of-00006.safetensors",
229
+ "transformer.h.22.mlp.c_proj.weight": "model-00004-of-00006.safetensors",
230
+ "transformer.h.23.attn.c_attn.bias": "model-00004-of-00006.safetensors",
231
+ "transformer.h.23.attn.c_attn.weight": "model-00004-of-00006.safetensors",
232
+ "transformer.h.23.attn.c_proj.bias": "model-00004-of-00006.safetensors",
233
+ "transformer.h.23.attn.c_proj.weight": "model-00004-of-00006.safetensors",
234
+ "transformer.h.23.ln_1.bias": "model-00004-of-00006.safetensors",
235
+ "transformer.h.23.ln_1.weight": "model-00004-of-00006.safetensors",
236
+ "transformer.h.23.ln_2.bias": "model-00004-of-00006.safetensors",
237
+ "transformer.h.23.ln_2.weight": "model-00004-of-00006.safetensors",
238
+ "transformer.h.23.mlp.c_fc.bias": "model-00004-of-00006.safetensors",
239
+ "transformer.h.23.mlp.c_fc.weight": "model-00004-of-00006.safetensors",
240
+ "transformer.h.23.mlp.c_fc2.bias": "model-00005-of-00006.safetensors",
241
+ "transformer.h.23.mlp.c_fc2.weight": "model-00005-of-00006.safetensors",
242
+ "transformer.h.23.mlp.c_proj.bias": "model-00005-of-00006.safetensors",
243
+ "transformer.h.23.mlp.c_proj.weight": "model-00005-of-00006.safetensors",
244
+ "transformer.h.24.attn.c_attn.bias": "model-00005-of-00006.safetensors",
245
+ "transformer.h.24.attn.c_attn.weight": "model-00005-of-00006.safetensors",
246
+ "transformer.h.24.attn.c_proj.bias": "model-00005-of-00006.safetensors",
247
+ "transformer.h.24.attn.c_proj.weight": "model-00005-of-00006.safetensors",
248
+ "transformer.h.24.ln_1.bias": "model-00005-of-00006.safetensors",
249
+ "transformer.h.24.ln_1.weight": "model-00005-of-00006.safetensors",
250
+ "transformer.h.24.ln_2.bias": "model-00005-of-00006.safetensors",
251
+ "transformer.h.24.ln_2.weight": "model-00005-of-00006.safetensors",
252
+ "transformer.h.24.mlp.c_fc.bias": "model-00005-of-00006.safetensors",
253
+ "transformer.h.24.mlp.c_fc.weight": "model-00005-of-00006.safetensors",
254
+ "transformer.h.24.mlp.c_fc2.bias": "model-00005-of-00006.safetensors",
255
+ "transformer.h.24.mlp.c_fc2.weight": "model-00005-of-00006.safetensors",
256
+ "transformer.h.24.mlp.c_proj.bias": "model-00005-of-00006.safetensors",
257
+ "transformer.h.24.mlp.c_proj.weight": "model-00005-of-00006.safetensors",
258
+ "transformer.h.25.attn.c_attn.bias": "model-00005-of-00006.safetensors",
259
+ "transformer.h.25.attn.c_attn.weight": "model-00005-of-00006.safetensors",
260
+ "transformer.h.25.attn.c_proj.bias": "model-00005-of-00006.safetensors",
261
+ "transformer.h.25.attn.c_proj.weight": "model-00005-of-00006.safetensors",
262
+ "transformer.h.25.ln_1.bias": "model-00005-of-00006.safetensors",
263
+ "transformer.h.25.ln_1.weight": "model-00005-of-00006.safetensors",
264
+ "transformer.h.25.ln_2.bias": "model-00005-of-00006.safetensors",
265
+ "transformer.h.25.ln_2.weight": "model-00005-of-00006.safetensors",
266
+ "transformer.h.25.mlp.c_fc.bias": "model-00005-of-00006.safetensors",
267
+ "transformer.h.25.mlp.c_fc.weight": "model-00005-of-00006.safetensors",
268
+ "transformer.h.25.mlp.c_fc2.bias": "model-00005-of-00006.safetensors",
269
+ "transformer.h.25.mlp.c_fc2.weight": "model-00005-of-00006.safetensors",
270
+ "transformer.h.25.mlp.c_proj.bias": "model-00005-of-00006.safetensors",
271
+ "transformer.h.25.mlp.c_proj.weight": "model-00005-of-00006.safetensors",
272
+ "transformer.h.26.attn.c_attn.bias": "model-00005-of-00006.safetensors",
273
+ "transformer.h.26.attn.c_attn.weight": "model-00005-of-00006.safetensors",
274
+ "transformer.h.26.attn.c_proj.bias": "model-00005-of-00006.safetensors",
275
+ "transformer.h.26.attn.c_proj.weight": "model-00005-of-00006.safetensors",
276
+ "transformer.h.26.ln_1.bias": "model-00005-of-00006.safetensors",
277
+ "transformer.h.26.ln_1.weight": "model-00005-of-00006.safetensors",
278
+ "transformer.h.26.ln_2.bias": "model-00005-of-00006.safetensors",
279
+ "transformer.h.26.ln_2.weight": "model-00005-of-00006.safetensors",
280
+ "transformer.h.26.mlp.c_fc.bias": "model-00005-of-00006.safetensors",
281
+ "transformer.h.26.mlp.c_fc.weight": "model-00005-of-00006.safetensors",
282
+ "transformer.h.26.mlp.c_fc2.bias": "model-00005-of-00006.safetensors",
283
+ "transformer.h.26.mlp.c_fc2.weight": "model-00005-of-00006.safetensors",
284
+ "transformer.h.26.mlp.c_proj.bias": "model-00005-of-00006.safetensors",
285
+ "transformer.h.26.mlp.c_proj.weight": "model-00005-of-00006.safetensors",
286
+ "transformer.h.27.attn.c_attn.bias": "model-00005-of-00006.safetensors",
287
+ "transformer.h.27.attn.c_attn.weight": "model-00005-of-00006.safetensors",
288
+ "transformer.h.27.attn.c_proj.bias": "model-00005-of-00006.safetensors",
289
+ "transformer.h.27.attn.c_proj.weight": "model-00005-of-00006.safetensors",
290
+ "transformer.h.27.ln_1.bias": "model-00005-of-00006.safetensors",
291
+ "transformer.h.27.ln_1.weight": "model-00005-of-00006.safetensors",
292
+ "transformer.h.27.ln_2.bias": "model-00005-of-00006.safetensors",
293
+ "transformer.h.27.ln_2.weight": "model-00005-of-00006.safetensors",
294
+ "transformer.h.27.mlp.c_fc.bias": "model-00005-of-00006.safetensors",
295
+ "transformer.h.27.mlp.c_fc.weight": "model-00005-of-00006.safetensors",
296
+ "transformer.h.27.mlp.c_fc2.bias": "model-00005-of-00006.safetensors",
297
+ "transformer.h.27.mlp.c_fc2.weight": "model-00005-of-00006.safetensors",
298
+ "transformer.h.27.mlp.c_proj.bias": "model-00005-of-00006.safetensors",
299
+ "transformer.h.27.mlp.c_proj.weight": "model-00005-of-00006.safetensors",
300
+ "transformer.h.28.attn.c_attn.bias": "model-00005-of-00006.safetensors",
301
+ "transformer.h.28.attn.c_attn.weight": "model-00005-of-00006.safetensors",
302
+ "transformer.h.28.attn.c_proj.bias": "model-00005-of-00006.safetensors",
303
+ "transformer.h.28.attn.c_proj.weight": "model-00005-of-00006.safetensors",
304
+ "transformer.h.28.ln_1.bias": "model-00005-of-00006.safetensors",
305
+ "transformer.h.28.ln_1.weight": "model-00005-of-00006.safetensors",
306
+ "transformer.h.28.ln_2.bias": "model-00005-of-00006.safetensors",
307
+ "transformer.h.28.ln_2.weight": "model-00005-of-00006.safetensors",
308
+ "transformer.h.28.mlp.c_fc.bias": "model-00005-of-00006.safetensors",
309
+ "transformer.h.28.mlp.c_fc.weight": "model-00005-of-00006.safetensors",
310
+ "transformer.h.28.mlp.c_fc2.bias": "model-00005-of-00006.safetensors",
311
+ "transformer.h.28.mlp.c_fc2.weight": "model-00005-of-00006.safetensors",
312
+ "transformer.h.28.mlp.c_proj.bias": "model-00005-of-00006.safetensors",
313
+ "transformer.h.28.mlp.c_proj.weight": "model-00005-of-00006.safetensors",
314
+ "transformer.h.29.attn.c_attn.bias": "model-00005-of-00006.safetensors",
315
+ "transformer.h.29.attn.c_attn.weight": "model-00005-of-00006.safetensors",
316
+ "transformer.h.29.attn.c_proj.bias": "model-00005-of-00006.safetensors",
317
+ "transformer.h.29.attn.c_proj.weight": "model-00005-of-00006.safetensors",
318
+ "transformer.h.29.ln_1.bias": "model-00005-of-00006.safetensors",
319
+ "transformer.h.29.ln_1.weight": "model-00005-of-00006.safetensors",
320
+ "transformer.h.29.ln_2.bias": "model-00005-of-00006.safetensors",
321
+ "transformer.h.29.ln_2.weight": "model-00005-of-00006.safetensors",
322
+ "transformer.h.29.mlp.c_fc.bias": "model-00005-of-00006.safetensors",
323
+ "transformer.h.29.mlp.c_fc.weight": "model-00005-of-00006.safetensors",
324
+ "transformer.h.29.mlp.c_fc2.bias": "model-00006-of-00006.safetensors",
325
+ "transformer.h.29.mlp.c_fc2.weight": "model-00006-of-00006.safetensors",
326
+ "transformer.h.29.mlp.c_proj.bias": "model-00006-of-00006.safetensors",
327
+ "transformer.h.29.mlp.c_proj.weight": "model-00006-of-00006.safetensors",
328
+ "transformer.h.3.attn.c_attn.bias": "model-00001-of-00006.safetensors",
329
+ "transformer.h.3.attn.c_attn.weight": "model-00001-of-00006.safetensors",
330
+ "transformer.h.3.attn.c_proj.bias": "model-00001-of-00006.safetensors",
331
+ "transformer.h.3.attn.c_proj.weight": "model-00001-of-00006.safetensors",
332
+ "transformer.h.3.ln_1.bias": "model-00001-of-00006.safetensors",
333
+ "transformer.h.3.ln_1.weight": "model-00001-of-00006.safetensors",
334
+ "transformer.h.3.ln_2.bias": "model-00001-of-00006.safetensors",
335
+ "transformer.h.3.ln_2.weight": "model-00001-of-00006.safetensors",
336
+ "transformer.h.3.mlp.c_fc.bias": "model-00001-of-00006.safetensors",
337
+ "transformer.h.3.mlp.c_fc.weight": "model-00001-of-00006.safetensors",
338
+ "transformer.h.3.mlp.c_fc2.bias": "model-00001-of-00006.safetensors",
339
+ "transformer.h.3.mlp.c_fc2.weight": "model-00001-of-00006.safetensors",
340
+ "transformer.h.3.mlp.c_proj.bias": "model-00001-of-00006.safetensors",
341
+ "transformer.h.3.mlp.c_proj.weight": "model-00001-of-00006.safetensors",
342
+ "transformer.h.30.attn.c_attn.bias": "model-00006-of-00006.safetensors",
343
+ "transformer.h.30.attn.c_attn.weight": "model-00006-of-00006.safetensors",
344
+ "transformer.h.30.attn.c_proj.bias": "model-00006-of-00006.safetensors",
345
+ "transformer.h.30.attn.c_proj.weight": "model-00006-of-00006.safetensors",
346
+ "transformer.h.30.ln_1.bias": "model-00006-of-00006.safetensors",
347
+ "transformer.h.30.ln_1.weight": "model-00006-of-00006.safetensors",
348
+ "transformer.h.30.ln_2.bias": "model-00006-of-00006.safetensors",
349
+ "transformer.h.30.ln_2.weight": "model-00006-of-00006.safetensors",
350
+ "transformer.h.30.mlp.c_fc.bias": "model-00006-of-00006.safetensors",
351
+ "transformer.h.30.mlp.c_fc.weight": "model-00006-of-00006.safetensors",
352
+ "transformer.h.30.mlp.c_fc2.bias": "model-00006-of-00006.safetensors",
353
+ "transformer.h.30.mlp.c_fc2.weight": "model-00006-of-00006.safetensors",
354
+ "transformer.h.30.mlp.c_proj.bias": "model-00006-of-00006.safetensors",
355
+ "transformer.h.30.mlp.c_proj.weight": "model-00006-of-00006.safetensors",
356
+ "transformer.h.31.attn.c_attn.bias": "model-00006-of-00006.safetensors",
357
+ "transformer.h.31.attn.c_attn.weight": "model-00006-of-00006.safetensors",
358
+ "transformer.h.31.attn.c_proj.bias": "model-00006-of-00006.safetensors",
359
+ "transformer.h.31.attn.c_proj.weight": "model-00006-of-00006.safetensors",
360
+ "transformer.h.31.ln_1.bias": "model-00006-of-00006.safetensors",
361
+ "transformer.h.31.ln_1.weight": "model-00006-of-00006.safetensors",
362
+ "transformer.h.31.ln_2.bias": "model-00006-of-00006.safetensors",
363
+ "transformer.h.31.ln_2.weight": "model-00006-of-00006.safetensors",
364
+ "transformer.h.31.mlp.c_fc.bias": "model-00006-of-00006.safetensors",
365
+ "transformer.h.31.mlp.c_fc.weight": "model-00006-of-00006.safetensors",
366
+ "transformer.h.31.mlp.c_fc2.bias": "model-00006-of-00006.safetensors",
367
+ "transformer.h.31.mlp.c_fc2.weight": "model-00006-of-00006.safetensors",
368
+ "transformer.h.31.mlp.c_proj.bias": "model-00006-of-00006.safetensors",
369
+ "transformer.h.31.mlp.c_proj.weight": "model-00006-of-00006.safetensors",
370
+ "transformer.h.4.attn.c_attn.bias": "model-00001-of-00006.safetensors",
371
+ "transformer.h.4.attn.c_attn.weight": "model-00001-of-00006.safetensors",
372
+ "transformer.h.4.attn.c_proj.bias": "model-00001-of-00006.safetensors",
373
+ "transformer.h.4.attn.c_proj.weight": "model-00001-of-00006.safetensors",
374
+ "transformer.h.4.ln_1.bias": "model-00001-of-00006.safetensors",
375
+ "transformer.h.4.ln_1.weight": "model-00001-of-00006.safetensors",
376
+ "transformer.h.4.ln_2.bias": "model-00001-of-00006.safetensors",
377
+ "transformer.h.4.ln_2.weight": "model-00001-of-00006.safetensors",
378
+ "transformer.h.4.mlp.c_fc.bias": "model-00001-of-00006.safetensors",
379
+ "transformer.h.4.mlp.c_fc.weight": "model-00001-of-00006.safetensors",
380
+ "transformer.h.4.mlp.c_fc2.bias": "model-00001-of-00006.safetensors",
381
+ "transformer.h.4.mlp.c_fc2.weight": "model-00001-of-00006.safetensors",
382
+ "transformer.h.4.mlp.c_proj.bias": "model-00001-of-00006.safetensors",
383
+ "transformer.h.4.mlp.c_proj.weight": "model-00001-of-00006.safetensors",
384
+ "transformer.h.5.attn.c_attn.bias": "model-00001-of-00006.safetensors",
385
+ "transformer.h.5.attn.c_attn.weight": "model-00001-of-00006.safetensors",
386
+ "transformer.h.5.attn.c_proj.bias": "model-00001-of-00006.safetensors",
387
+ "transformer.h.5.attn.c_proj.weight": "model-00001-of-00006.safetensors",
388
+ "transformer.h.5.ln_1.bias": "model-00001-of-00006.safetensors",
389
+ "transformer.h.5.ln_1.weight": "model-00001-of-00006.safetensors",
390
+ "transformer.h.5.ln_2.bias": "model-00001-of-00006.safetensors",
391
+ "transformer.h.5.ln_2.weight": "model-00001-of-00006.safetensors",
392
+ "transformer.h.5.mlp.c_fc.bias": "model-00001-of-00006.safetensors",
393
+ "transformer.h.5.mlp.c_fc.weight": "model-00001-of-00006.safetensors",
394
+ "transformer.h.5.mlp.c_fc2.bias": "model-00002-of-00006.safetensors",
395
+ "transformer.h.5.mlp.c_fc2.weight": "model-00002-of-00006.safetensors",
396
+ "transformer.h.5.mlp.c_proj.bias": "model-00002-of-00006.safetensors",
397
+ "transformer.h.5.mlp.c_proj.weight": "model-00002-of-00006.safetensors",
398
+ "transformer.h.6.attn.c_attn.bias": "model-00002-of-00006.safetensors",
399
+ "transformer.h.6.attn.c_attn.weight": "model-00002-of-00006.safetensors",
400
+ "transformer.h.6.attn.c_proj.bias": "model-00002-of-00006.safetensors",
401
+ "transformer.h.6.attn.c_proj.weight": "model-00002-of-00006.safetensors",
402
+ "transformer.h.6.ln_1.bias": "model-00002-of-00006.safetensors",
403
+ "transformer.h.6.ln_1.weight": "model-00002-of-00006.safetensors",
404
+ "transformer.h.6.ln_2.bias": "model-00002-of-00006.safetensors",
405
+ "transformer.h.6.ln_2.weight": "model-00002-of-00006.safetensors",
406
+ "transformer.h.6.mlp.c_fc.bias": "model-00002-of-00006.safetensors",
407
+ "transformer.h.6.mlp.c_fc.weight": "model-00002-of-00006.safetensors",
408
+ "transformer.h.6.mlp.c_fc2.bias": "model-00002-of-00006.safetensors",
409
+ "transformer.h.6.mlp.c_fc2.weight": "model-00002-of-00006.safetensors",
410
+ "transformer.h.6.mlp.c_proj.bias": "model-00002-of-00006.safetensors",
411
+ "transformer.h.6.mlp.c_proj.weight": "model-00002-of-00006.safetensors",
412
+ "transformer.h.7.attn.c_attn.bias": "model-00002-of-00006.safetensors",
413
+ "transformer.h.7.attn.c_attn.weight": "model-00002-of-00006.safetensors",
414
+ "transformer.h.7.attn.c_proj.bias": "model-00002-of-00006.safetensors",
415
+ "transformer.h.7.attn.c_proj.weight": "model-00002-of-00006.safetensors",
416
+ "transformer.h.7.ln_1.bias": "model-00002-of-00006.safetensors",
417
+ "transformer.h.7.ln_1.weight": "model-00002-of-00006.safetensors",
418
+ "transformer.h.7.ln_2.bias": "model-00002-of-00006.safetensors",
419
+ "transformer.h.7.ln_2.weight": "model-00002-of-00006.safetensors",
420
+ "transformer.h.7.mlp.c_fc.bias": "model-00002-of-00006.safetensors",
421
+ "transformer.h.7.mlp.c_fc.weight": "model-00002-of-00006.safetensors",
422
+ "transformer.h.7.mlp.c_fc2.bias": "model-00002-of-00006.safetensors",
423
+ "transformer.h.7.mlp.c_fc2.weight": "model-00002-of-00006.safetensors",
424
+ "transformer.h.7.mlp.c_proj.bias": "model-00002-of-00006.safetensors",
425
+ "transformer.h.7.mlp.c_proj.weight": "model-00002-of-00006.safetensors",
426
+ "transformer.h.8.attn.c_attn.bias": "model-00002-of-00006.safetensors",
427
+ "transformer.h.8.attn.c_attn.weight": "model-00002-of-00006.safetensors",
428
+ "transformer.h.8.attn.c_proj.bias": "model-00002-of-00006.safetensors",
429
+ "transformer.h.8.attn.c_proj.weight": "model-00002-of-00006.safetensors",
430
+ "transformer.h.8.ln_1.bias": "model-00002-of-00006.safetensors",
431
+ "transformer.h.8.ln_1.weight": "model-00002-of-00006.safetensors",
432
+ "transformer.h.8.ln_2.bias": "model-00002-of-00006.safetensors",
433
+ "transformer.h.8.ln_2.weight": "model-00002-of-00006.safetensors",
434
+ "transformer.h.8.mlp.c_fc.bias": "model-00002-of-00006.safetensors",
435
+ "transformer.h.8.mlp.c_fc.weight": "model-00002-of-00006.safetensors",
436
+ "transformer.h.8.mlp.c_fc2.bias": "model-00002-of-00006.safetensors",
437
+ "transformer.h.8.mlp.c_fc2.weight": "model-00002-of-00006.safetensors",
438
+ "transformer.h.8.mlp.c_proj.bias": "model-00002-of-00006.safetensors",
439
+ "transformer.h.8.mlp.c_proj.weight": "model-00002-of-00006.safetensors",
440
+ "transformer.h.9.attn.c_attn.bias": "model-00002-of-00006.safetensors",
441
+ "transformer.h.9.attn.c_attn.weight": "model-00002-of-00006.safetensors",
442
+ "transformer.h.9.attn.c_proj.bias": "model-00002-of-00006.safetensors",
443
+ "transformer.h.9.attn.c_proj.weight": "model-00002-of-00006.safetensors",
444
+ "transformer.h.9.ln_1.bias": "model-00002-of-00006.safetensors",
445
+ "transformer.h.9.ln_1.weight": "model-00002-of-00006.safetensors",
446
+ "transformer.h.9.ln_2.bias": "model-00002-of-00006.safetensors",
447
+ "transformer.h.9.ln_2.weight": "model-00002-of-00006.safetensors",
448
+ "transformer.h.9.mlp.c_fc.bias": "model-00002-of-00006.safetensors",
449
+ "transformer.h.9.mlp.c_fc.weight": "model-00002-of-00006.safetensors",
450
+ "transformer.h.9.mlp.c_fc2.bias": "model-00002-of-00006.safetensors",
451
+ "transformer.h.9.mlp.c_fc2.weight": "model-00002-of-00006.safetensors",
452
+ "transformer.h.9.mlp.c_proj.bias": "model-00002-of-00006.safetensors",
453
+ "transformer.h.9.mlp.c_proj.weight": "model-00002-of-00006.safetensors",
454
+ "transformer.ln_f.bias": "model-00006-of-00006.safetensors",
455
+ "transformer.ln_f.weight": "model-00006-of-00006.safetensors",
456
+ "transformer.wte.weight": "model-00001-of-00006.safetensors"
457
+ }
458
+ }
modeling_crystalcoder.py ADDED
@@ -0,0 +1,1671 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ """ PyTorch CrystalCoder model."""
3
+
4
+ import math
5
+ import os
6
+ import warnings
7
+ from typing import Optional, Tuple, Union
8
+
9
+ import torch
10
+ from torch import Tensor, nn
11
+ from torch.cuda.amp import autocast
12
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
13
+
14
+ from transformers.activations import ACT2FN
15
+ from transformers.modeling_outputs import (
16
+ BaseModelOutputWithPastAndCrossAttentions,
17
+ CausalLMOutputWithCrossAttentions,
18
+ QuestionAnsweringModelOutput,
19
+ SequenceClassifierOutputWithPast,
20
+ TokenClassifierOutput,
21
+ )
22
+ from transformers.modeling_utils import PreTrainedModel
23
+ from transformers.pytorch_utils import Conv1D, find_pruneable_heads_and_indices, prune_conv1d_layer
24
+ from transformers.utils import (
25
+ add_code_sample_docstrings,
26
+ add_start_docstrings,
27
+ add_start_docstrings_to_model_forward,
28
+ logging,
29
+ )
30
+ from transformers.utils.model_parallel_utils import assert_device_map, get_device_map
31
+ from .configuration_crystalcoder import CrystalCoderConfig
32
+ # from configuration_crystalcoder import CrystalCoderConfig
33
+
34
+
35
+ logger = logging.get_logger(__name__)
36
+
37
+
38
+ _CONFIG_FOR_DOC = "CrystalCoderConfig"
39
+
40
+
41
+ def _duplicate_interleave(m):
42
+ """
43
+ A simple version of `torch.repeat_interleave` for duplicating a matrix while interleaving the copy.
44
+ """
45
+ dim0 = m.shape[0]
46
+ m = m.view(-1, 1) # flatten the matrix
47
+ m = m.repeat(1, 2) # repeat all elements into the 2nd dimension
48
+ m = m.view(dim0, -1) # reshape into a matrix, interleaving the copy
49
+ return m
50
+
51
+
52
+ class RotaryPositionEmbeddingHelper:
53
+ def __init__(self, max_position_embeddings, rotary_dim, base=10000):
54
+ super(RotaryPositionEmbeddingHelper, self).__init__()
55
+ self.max_position_embeddings = max_position_embeddings
56
+ self.rotary_dim = rotary_dim
57
+ self.base = base
58
+ self.sin_cached = None
59
+ self.cos_cached = None
60
+ # self.offset = 0
61
+
62
+ def create_fixed_pos_emb(self, x, offset):
63
+ if (self.sin_cached is not None and self.cos_cached is not None
64
+ and x.device == self.sin_cached.device
65
+ and x.device == self.cos_cached.device
66
+ ):
67
+ sin, cos = self.sin_cached, self.cos_cached
68
+ else:
69
+ # compute sin and cos for the fixed positional embeddings, using the maximum possible sequence length
70
+ # store as cache for future use
71
+ # self.offset = offset
72
+ device = x.device
73
+
74
+ inv_freq = 1.0 / (
75
+ self.base
76
+ ** (
77
+ torch.arange(0, self.rotary_dim, 2, device=device)
78
+ / self.rotary_dim
79
+ )
80
+ )
81
+ sinusoid_inp = torch.einsum(
82
+ "i , j -> i j",
83
+ torch.arange(self.max_position_embeddings, device=device),
84
+ inv_freq,
85
+ )
86
+ sin, cos = (
87
+ torch.sin(sinusoid_inp).to(x.dtype),
88
+ torch.cos(sinusoid_inp).to(x.dtype),
89
+ )
90
+
91
+ sin, cos = map(_duplicate_interleave, (sin, cos))
92
+
93
+ self.sin_cached = sin
94
+ self.cos_cached = cos
95
+
96
+ assert (
97
+ self.max_position_embeddings >= x.shape[1] + offset
98
+ ), "RoPE requires max position embeddings ({}) >= sequence length ({}) + offset ({})".format(
99
+ self.max_position_embeddings, x.shape[1], offset,
100
+ )
101
+
102
+ def slice_at_offset(t):
103
+ return t[None, offset : x.shape[1] + offset, None, :]
104
+
105
+ sin, cos = map(slice_at_offset, (sin, cos))
106
+
107
+ return sin, cos
108
+
109
+ def _apply_rotary_pos_emb(self, x, offset=0):
110
+ def rotate_every_two(x):
111
+ x1 = x[:, :, :, ::2]
112
+ x2 = x[:, :, :, 1::2]
113
+ x = torch.stack((-x2, x1), dim=-1)
114
+ # in einsum notation: rearrange(x, '... d j -> ... (d j)')
115
+ return x.flatten(-2)
116
+
117
+ sin, cos = self.create_fixed_pos_emb(x, offset)
118
+ l = x.size(1)
119
+ sin = sin[:, :l]
120
+ cos = cos[:, :l]
121
+
122
+ # einsum notation for lambda t: repeat(t[offset:x.shape[1]+offset,:], "n d -> () n () (d j)", j=2)
123
+ return (x * cos) + (rotate_every_two(x) * sin)
124
+
125
+ def rotate_tensor(self, x, offset=0):
126
+ assert (
127
+ len(x.shape) == 4
128
+ ), "Tensor should be of shape [batch_size, seq_length, num_heads, head_dim] !"
129
+ x_rotary = x[:, :, :, : self.rotary_dim]
130
+ x_pass = x[:, :, :, self.rotary_dim :]
131
+ x_rotated = self._apply_rotary_pos_emb(
132
+ x_rotary, offset=offset
133
+ )
134
+ x = torch.cat([x_rotated, x_pass], dim=-1)
135
+ return x
136
+
137
+
138
+ class SwiGLUActivation(nn.Module):
139
+ def forward(self, x1: Tensor, x2: Tensor) -> Tensor:
140
+ return x1 * nn.functional.silu(x2)
141
+
142
+
143
+ class AlibiPositionEmbeddingLayer(nn.Module):
144
+ def __init__(self, num_heads):
145
+ super(AlibiPositionEmbeddingLayer, self).__init__()
146
+
147
+ self.num_heads = num_heads
148
+ slopes = torch.tensor(AlibiPositionEmbeddingLayer._get_alibi_slopes(num_heads)).unsqueeze(-1)
149
+ self.slopes = nn.parameter.Parameter(slopes, requires_grad=False)
150
+
151
+ def forward(
152
+ self,
153
+ seq_length,
154
+ key_length,
155
+ cached_qk_len,
156
+ ):
157
+ context_position = torch.arange(
158
+ cached_qk_len, cached_qk_len + seq_length, device=self.slopes.device
159
+ )[:, None]
160
+ memory_position = torch.arange(
161
+ key_length + cached_qk_len, device=self.slopes.device
162
+ )[None, :]
163
+ relative_position = memory_position - context_position
164
+ relative_position = torch.abs(relative_position).unsqueeze(0).expand(self.num_heads, -1, -1)
165
+ alibi = (self.slopes * -1.0).unsqueeze(1) * relative_position
166
+ return alibi
167
+
168
+ @staticmethod
169
+ def _get_alibi_slopes(n):
170
+ def get_slopes_power_of_2(n):
171
+ start = 2 ** (-(2 ** -(math.log2(n) - 3)))
172
+ ratio = start
173
+ return [start * ratio**i for i in range(n)]
174
+
175
+ if math.log2(n).is_integer():
176
+ return get_slopes_power_of_2(
177
+ n
178
+ ) # In the paper, we only train models that have 2^a heads for some a. This function has
179
+ else: # some good properties that only occur when the input is a power of 2. To maintain that even
180
+ closest_power_of_2 = 2 ** math.floor(
181
+ math.log2(n)
182
+ ) # when the number of heads is not a power of 2, we use this workaround.
183
+ return (
184
+ get_slopes_power_of_2(closest_power_of_2)
185
+ + AlibiPositionEmbeddingLayer._get_alibi_slopes(2 * closest_power_of_2)[0::2][: n - closest_power_of_2]
186
+ )
187
+
188
+
189
+ def load_tf_weights_in_crystalcoder(model, config, crystalcoder_checkpoint_path):
190
+ """Load tf checkpoints in a pytorch model"""
191
+ try:
192
+ import re
193
+
194
+ import tensorflow as tf
195
+ except ImportError:
196
+ logger.error(
197
+ "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
198
+ "https://www.tensorflow.org/install/ for installation instructions."
199
+ )
200
+ raise
201
+ tf_path = os.path.abspath(crystalcoder_checkpoint_path)
202
+ logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
203
+ # Load weights from TF model
204
+ init_vars = tf.train.list_variables(tf_path)
205
+ names = []
206
+ arrays = []
207
+ for name, shape in init_vars:
208
+ logger.info(f"Loading TF weight {name} with shape {shape}")
209
+ array = tf.train.load_variable(tf_path, name)
210
+ names.append(name)
211
+ arrays.append(array.squeeze())
212
+
213
+ for name, array in zip(names, arrays):
214
+ name = name[6:] # skip "model/"
215
+ name = name.split("/")
216
+ pointer = model
217
+ for m_name in name:
218
+ if re.fullmatch(r"[A-Za-z]+\d+", m_name):
219
+ scope_names = re.split(r"(\d+)", m_name)
220
+ else:
221
+ scope_names = [m_name]
222
+ if scope_names[0] == "w" or scope_names[0] == "g":
223
+ pointer = getattr(pointer, "weight")
224
+ elif scope_names[0] == "b":
225
+ pointer = getattr(pointer, "bias")
226
+ elif scope_names[0] == "wpe" or scope_names[0] == "wte":
227
+ pointer = getattr(pointer, scope_names[0])
228
+ pointer = getattr(pointer, "weight")
229
+ else:
230
+ pointer = getattr(pointer, scope_names[0])
231
+ if len(scope_names) >= 2:
232
+ num = int(scope_names[1])
233
+ pointer = pointer[num]
234
+ try:
235
+ assert (
236
+ pointer.shape == array.shape
237
+ ), f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched"
238
+ except AssertionError as e:
239
+ e.args += (pointer.shape, array.shape)
240
+ raise
241
+ logger.info(f"Initialize PyTorch weight {name}")
242
+ pointer.data = torch.from_numpy(array)
243
+ return model
244
+
245
+
246
+ class CrystalCoderAttention(nn.Module):
247
+ def __init__(self, config, is_cross_attention=False, layer_idx=None):
248
+ super().__init__()
249
+
250
+ max_positions = config.max_position_embeddings
251
+ self.register_buffer(
252
+ "bias",
253
+ torch.tril(torch.ones((max_positions, max_positions), dtype=torch.bool)).view(
254
+ 1, 1, max_positions, max_positions
255
+ ),
256
+ persistent=False,
257
+ )
258
+ self.register_buffer("masked_bias", torch.tensor(-1e4), persistent=False)
259
+
260
+ self.embed_dim = config.hidden_size
261
+ self.num_heads = config.num_attention_heads
262
+ self.head_dim = self.embed_dim // self.num_heads
263
+ self.split_size = self.embed_dim
264
+ if self.head_dim * self.num_heads != self.embed_dim:
265
+ raise ValueError(
266
+ f"`embed_dim` must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
267
+ f" {self.num_heads})."
268
+ )
269
+ if config.position_embedding_type == "rotary":
270
+ rotary_dim = config.rotary_dim or self.head_dim
271
+ self.rope_helper = RotaryPositionEmbeddingHelper(max_positions, rotary_dim)
272
+ else:
273
+ self.rope_helper = None
274
+
275
+
276
+ self.scale_attn_weights = config.scale_attn_weights
277
+ self.is_cross_attention = is_cross_attention
278
+
279
+ # Layer-wise attention scaling, reordering, and upcasting
280
+ self.scale_attn_by_inverse_layer_idx = config.scale_attn_by_inverse_layer_idx
281
+ self.layer_idx = layer_idx
282
+ self.reorder_and_upcast_attn = config.reorder_and_upcast_attn
283
+
284
+ if self.is_cross_attention:
285
+ self.c_attn = Conv1D(2 * self.embed_dim, self.embed_dim)
286
+ self.q_attn = Conv1D(self.embed_dim, self.embed_dim)
287
+ else:
288
+ self.c_attn = Conv1D(3 * self.embed_dim, self.embed_dim)
289
+ self.c_proj = Conv1D(self.embed_dim, self.embed_dim)
290
+
291
+ self.attn_dropout = nn.Dropout(config.attn_pdrop)
292
+ self.resid_dropout = nn.Dropout(config.resid_pdrop)
293
+
294
+ self.pruned_heads = set()
295
+
296
+ self.attn_scale_power = 1.0 if config.mup_scale_qk_dot_by_d else 0.5
297
+
298
+ def prune_heads(self, heads):
299
+ if len(heads) == 0:
300
+ return
301
+ heads, index = find_pruneable_heads_and_indices(heads, self.num_heads, self.head_dim, self.pruned_heads)
302
+ index_attn = torch.cat([index, index + self.split_size, index + (2 * self.split_size)])
303
+
304
+ # Prune conv1d layers
305
+ self.c_attn = prune_conv1d_layer(self.c_attn, index_attn, dim=1)
306
+ self.c_proj = prune_conv1d_layer(self.c_proj, index, dim=0)
307
+
308
+ # Update hyper params
309
+ self.split_size = (self.split_size // self.num_heads) * (self.num_heads - len(heads))
310
+ self.num_heads = self.num_heads - len(heads)
311
+ self.pruned_heads = self.pruned_heads.union(heads)
312
+
313
+ def _attn(self, query, key, value, attention_mask=None, head_mask=None, position_bias=None):
314
+ attn_weights = torch.matmul(query, key.transpose(-1, -2))
315
+
316
+ if self.scale_attn_weights:
317
+ attn_weights = attn_weights / torch.full(
318
+ [], value.size(-1) ** self.attn_scale_power, dtype=attn_weights.dtype, device=attn_weights.device
319
+ )
320
+
321
+ # Layer-wise attention scaling
322
+ if self.scale_attn_by_inverse_layer_idx:
323
+ attn_weights = attn_weights / float(self.layer_idx + 1)
324
+
325
+ if not self.is_cross_attention:
326
+ # if only "normal" attention layer implements causal mask
327
+ query_length, key_length = query.size(-2), key.size(-2)
328
+ causal_mask = self.bias[:, :, key_length - query_length : key_length, :key_length]
329
+ mask_value = torch.finfo(attn_weights.dtype).min
330
+ # Need to be a tensor, otherwise we get error: `RuntimeError: expected scalar type float but found double`.
331
+ # Need to be on the same device, otherwise `RuntimeError: ..., x and y to be on the same device`
332
+ mask_value = torch.full([], mask_value, dtype=attn_weights.dtype).to(attn_weights.device)
333
+ attn_weights = torch.where(causal_mask, attn_weights.to(attn_weights.dtype), mask_value)
334
+
335
+ if attention_mask is not None:
336
+ # Apply the attention mask
337
+ attn_weights = attn_weights + attention_mask
338
+
339
+ if position_bias is not None:
340
+ attn_weights += position_bias.type_as(attn_weights).unsqueeze(0)
341
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
342
+
343
+ # Downcast (if necessary) back to V's dtype (if in mixed-precision) -- No-Op otherwise
344
+ attn_weights = attn_weights.type(value.dtype)
345
+ attn_weights = self.attn_dropout(attn_weights)
346
+
347
+ # Mask heads if we want to
348
+ if head_mask is not None:
349
+ attn_weights = attn_weights * head_mask
350
+
351
+ attn_output = torch.matmul(attn_weights, value)
352
+
353
+ return attn_output, attn_weights
354
+
355
+ def _upcast_and_reordered_attn(self, query, key, value, attention_mask=None, head_mask=None, position_bias=None):
356
+ # Use `torch.baddbmm` (a bit more efficient w/ alpha param for scaling -- from Megatron-LM)
357
+ bsz, num_heads, q_seq_len, dk = query.size()
358
+ _, _, k_seq_len, _ = key.size()
359
+
360
+ # Preallocate attn_weights for `baddbmm`
361
+ attn_weights = torch.empty(bsz * num_heads, q_seq_len, k_seq_len, dtype=torch.float32, device=query.device)
362
+
363
+ # Compute Scale Factor
364
+ scale_factor = 1.0
365
+ if self.scale_attn_weights:
366
+ scale_factor /= float(value.size(-1)) ** self.attn_scale_power
367
+
368
+ if self.scale_attn_by_inverse_layer_idx:
369
+ scale_factor /= float(self.layer_idx + 1)
370
+
371
+ # Upcast (turn off autocast) and reorder (Scale K by 1 / root(dk))
372
+ with autocast(enabled=False):
373
+ q, k = query.reshape(-1, q_seq_len, dk), key.transpose(-1, -2).reshape(-1, dk, k_seq_len)
374
+ attn_weights = torch.baddbmm(attn_weights, q.float(), k.float(), beta=0, alpha=scale_factor)
375
+ attn_weights = attn_weights.reshape(bsz, num_heads, q_seq_len, k_seq_len)
376
+
377
+ if not self.is_cross_attention:
378
+ # if only "normal" attention layer implements causal mask
379
+ query_length, key_length = query.size(-2), key.size(-2)
380
+ causal_mask = self.bias[:, :, key_length - query_length : key_length, :key_length]
381
+ mask_value = torch.finfo(attn_weights.dtype).min
382
+ # Need to be a tensor, otherwise we get error: `RuntimeError: expected scalar type float but found double`.
383
+ # Need to be on the same device, otherwise `RuntimeError: ..., x and y to be on the same device`
384
+ mask_value = torch.tensor(mask_value, dtype=attn_weights.dtype).to(attn_weights.device)
385
+ attn_weights = torch.where(causal_mask, attn_weights, mask_value)
386
+
387
+ if attention_mask is not None:
388
+ # Apply the attention mask
389
+ attn_weights = attn_weights + attention_mask
390
+
391
+ if position_bias is not None:
392
+ attn_weights += position_bias.type_as(attn_weights).unsqueeze(0)
393
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
394
+
395
+ # Downcast (if necessary) back to V's dtype (if in mixed-precision) -- No-Op if otherwise
396
+ if attn_weights.dtype != torch.float32:
397
+ raise RuntimeError("Error with upcasting, attn_weights does not have dtype torch.float32")
398
+ attn_weights = attn_weights.type(value.dtype)
399
+ attn_weights = self.attn_dropout(attn_weights)
400
+
401
+ # Mask heads if we want to
402
+ if head_mask is not None:
403
+ attn_weights = attn_weights * head_mask
404
+
405
+ attn_output = torch.matmul(attn_weights, value)
406
+
407
+ return attn_output, attn_weights
408
+
409
+ def _split_heads(self, tensor, num_heads, attn_head_size):
410
+ """
411
+ Splits hidden_size dim into attn_head_size and num_heads
412
+ """
413
+ new_shape = tensor.size()[:-1] + (num_heads, attn_head_size)
414
+ tensor = tensor.view(new_shape)
415
+ return tensor
416
+
417
+ def _merge_heads(self, tensor, num_heads, attn_head_size):
418
+ """
419
+ Merges attn_head_size dim and num_attn_heads dim into hidden_size
420
+ """
421
+ tensor = tensor.permute(0, 2, 1, 3).contiguous()
422
+ new_shape = tensor.size()[:-2] + (num_heads * attn_head_size,)
423
+ return tensor.view(new_shape)
424
+
425
+ def forward(
426
+ self,
427
+ hidden_states: Optional[Tuple[torch.FloatTensor]],
428
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
429
+ attention_mask: Optional[torch.FloatTensor] = None,
430
+ head_mask: Optional[torch.FloatTensor] = None,
431
+ encoder_hidden_states: Optional[torch.Tensor] = None,
432
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
433
+ use_cache: Optional[bool] = False,
434
+ output_attentions: Optional[bool] = False,
435
+ position_bias: Optional[torch.FloatTensor] = None,
436
+ ) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]], ...]:
437
+ if encoder_hidden_states is not None:
438
+ if not hasattr(self, "q_attn"):
439
+ raise ValueError(
440
+ "If class is used as cross attention, the weights `q_attn` have to be defined. "
441
+ "Please make sure to instantiate class with `CrystalCoderAttention(..., is_cross_attention=True)`."
442
+ )
443
+
444
+ query = self.q_attn(hidden_states)
445
+ key, value = self.c_attn(encoder_hidden_states).split(self.split_size, dim=2)
446
+ attention_mask = encoder_attention_mask
447
+ else:
448
+ query, key, value = self.c_attn(hidden_states).split(self.split_size, dim=2)
449
+
450
+ query = self._split_heads(query, self.num_heads, self.head_dim)
451
+ key = self._split_heads(key, self.num_heads, self.head_dim)
452
+ value = self._split_heads(value, self.num_heads, self.head_dim)
453
+
454
+ # apply rope and transpose
455
+ if self.rope_helper is not None:
456
+ len_past = (layer_past and layer_past[0].size(-2)) or 0
457
+ query = self.rope_helper.rotate_tensor(query, offset=len_past)
458
+ key = self.rope_helper.rotate_tensor(key, offset=len_past)
459
+ query = query.transpose(1, 2)
460
+ key = key.transpose(1, 2)
461
+ value = value.transpose(1, 2)
462
+
463
+ if layer_past is not None:
464
+ past_key, past_value = layer_past
465
+ key = torch.cat((past_key, key), dim=-2)
466
+ value = torch.cat((past_value, value), dim=-2)
467
+
468
+ if use_cache is True:
469
+ present = (key, value)
470
+ else:
471
+ present = None
472
+
473
+ if self.reorder_and_upcast_attn:
474
+ attn_output, attn_weights = self._upcast_and_reordered_attn(
475
+ query, key, value, attention_mask, head_mask, position_bias
476
+ )
477
+ else:
478
+ attn_output, attn_weights = self._attn(query, key, value, attention_mask, head_mask, position_bias)
479
+
480
+ attn_output = self._merge_heads(attn_output, self.num_heads, self.head_dim)
481
+ attn_output = self.c_proj(attn_output)
482
+ attn_output = self.resid_dropout(attn_output)
483
+
484
+ outputs = (attn_output, present)
485
+ if output_attentions:
486
+ outputs += (attn_weights,)
487
+
488
+ return outputs # a, present, (attentions)
489
+
490
+
491
+ class CrystalCoderMLP(nn.Module):
492
+ def __init__(self, intermediate_size, config):
493
+ super().__init__()
494
+ embed_dim = config.hidden_size
495
+ self.swiglu = config.activation_function == "swiglu"
496
+ self.c_fc = Conv1D(intermediate_size, embed_dim)
497
+ self.c_fc2 = Conv1D(intermediate_size, embed_dim) if self.swiglu else None
498
+ self.c_proj = Conv1D(embed_dim, intermediate_size)
499
+ self.act = SwiGLUActivation() if self.swiglu else ACT2FN[config.activation_function]
500
+ self.dropout = nn.Dropout(config.resid_pdrop)
501
+
502
+ def forward(self, hidden_states: Optional[Tuple[torch.FloatTensor]]) -> torch.FloatTensor:
503
+ if self.swiglu:
504
+ hidden_states2 = self.c_fc2(hidden_states)
505
+ hidden_states = self.c_fc(hidden_states)
506
+ hidden_states = self.act(hidden_states, hidden_states2) if self.swiglu else self.act(hidden_states)
507
+ hidden_states = self.c_proj(hidden_states)
508
+ hidden_states = self.dropout(hidden_states)
509
+ return hidden_states
510
+
511
+
512
+ class CrystalCoderBlock(nn.Module):
513
+ def __init__(self, config, layer_idx=None):
514
+ super().__init__()
515
+ hidden_size = config.hidden_size
516
+ inner_dim = config.n_inner if config.n_inner is not None else 4 * hidden_size
517
+
518
+ self.ln_1 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
519
+ self.attn = CrystalCoderAttention(config, layer_idx=layer_idx)
520
+ self.ln_2 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
521
+
522
+ if config.add_cross_attention:
523
+ self.crossattention = CrystalCoderAttention(config, is_cross_attention=True, layer_idx=layer_idx)
524
+ self.ln_cross_attn = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
525
+
526
+ self.mlp = CrystalCoderMLP(inner_dim, config)
527
+
528
+ def forward(
529
+ self,
530
+ hidden_states: Optional[Tuple[torch.FloatTensor]],
531
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
532
+ attention_mask: Optional[torch.FloatTensor] = None,
533
+ head_mask: Optional[torch.FloatTensor] = None,
534
+ encoder_hidden_states: Optional[torch.Tensor] = None,
535
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
536
+ use_cache: Optional[bool] = False,
537
+ output_attentions: Optional[bool] = False,
538
+ position_bias: Optional[torch.FloatTensor] = None,
539
+ ) -> Union[Tuple[torch.Tensor], Optional[Tuple[torch.Tensor, Tuple[torch.FloatTensor, ...]]]]:
540
+ residual = hidden_states
541
+ hidden_states = self.ln_1(hidden_states)
542
+ attn_outputs = self.attn(
543
+ hidden_states,
544
+ layer_past=layer_past,
545
+ attention_mask=attention_mask,
546
+ head_mask=head_mask,
547
+ use_cache=use_cache,
548
+ output_attentions=output_attentions,
549
+ position_bias=position_bias,
550
+ )
551
+ attn_output = attn_outputs[0] # output_attn: a, present, (attentions)
552
+ outputs = attn_outputs[1:]
553
+ # residual connection
554
+ hidden_states = attn_output + residual
555
+
556
+ if encoder_hidden_states is not None:
557
+ # add one self-attention block for cross-attention
558
+ if not hasattr(self, "crossattention"):
559
+ raise ValueError(
560
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with "
561
+ "cross-attention layers by setting `config.add_cross_attention=True`"
562
+ )
563
+ residual = hidden_states
564
+ hidden_states = self.ln_cross_attn(hidden_states)
565
+ cross_attn_outputs = self.crossattention(
566
+ hidden_states,
567
+ attention_mask=attention_mask,
568
+ head_mask=head_mask,
569
+ encoder_hidden_states=encoder_hidden_states,
570
+ encoder_attention_mask=encoder_attention_mask,
571
+ output_attentions=output_attentions,
572
+ position_bias=position_bias,
573
+ )
574
+ attn_output = cross_attn_outputs[0]
575
+ # residual connection
576
+ hidden_states = residual + attn_output
577
+ outputs = outputs + cross_attn_outputs[2:] # add cross attentions if we output attention weights
578
+
579
+ residual = hidden_states
580
+ hidden_states = self.ln_2(hidden_states)
581
+ feed_forward_hidden_states = self.mlp(hidden_states)
582
+ # residual connection
583
+ hidden_states = residual + feed_forward_hidden_states
584
+
585
+ if use_cache:
586
+ outputs = (hidden_states,) + outputs
587
+ else:
588
+ outputs = (hidden_states,) + outputs[1:]
589
+
590
+ return outputs # hidden_states, present, (attentions, cross_attentions)
591
+
592
+
593
+ class CrystalCoderPreTrainedModel(PreTrainedModel):
594
+ """
595
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
596
+ models.
597
+ """
598
+
599
+ config_class = CrystalCoderConfig
600
+ load_tf_weights = load_tf_weights_in_crystalcoder
601
+ base_model_prefix = "transformer"
602
+ is_parallelizable = True
603
+ supports_gradient_checkpointing = True
604
+ _no_split_modules = ["CrystalCoderBlock"]
605
+ _skip_keys_device_placement = "past_key_values"
606
+
607
+ def __init__(self, *inputs, **kwargs):
608
+ super().__init__(*inputs, **kwargs)
609
+
610
+ def _init_weights(self, module):
611
+ """Initialize the weights."""
612
+ mup_init_scale = math.sqrt(self.config.mup_width_scale)
613
+ if isinstance(module, (nn.Linear, Conv1D)):
614
+ # Slightly different from the TF version which uses truncated_normal for initialization
615
+ # cf https://github.com/pytorch/pytorch/pull/5617
616
+ module.weight.data.normal_(mean=0.0, std=(self.config.initializer_range * mup_init_scale))
617
+ if module.bias is not None:
618
+ module.bias.data.zero_()
619
+ elif isinstance(module, nn.Embedding):
620
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
621
+ if module.padding_idx is not None:
622
+ module.weight.data[module.padding_idx].zero_()
623
+ elif isinstance(module, nn.LayerNorm):
624
+ module.bias.data.zero_()
625
+ module.weight.data.fill_(1.0)
626
+
627
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
628
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
629
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
630
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
631
+ #
632
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
633
+ for name, p in module.named_parameters():
634
+ if name == "c_proj.weight":
635
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
636
+ stddev = self.config.initializer_range * mup_init_scale / math.sqrt(2 * self.config.n_layer)
637
+ p.data.normal_(mean=0.0, std=stddev)
638
+
639
+ def _set_gradient_checkpointing(self, module, value=False):
640
+ if isinstance(module, CrystalCoderModel):
641
+ module.gradient_checkpointing = value
642
+
643
+ def get_mup_param_groups(self, lr, weight_decay=0.0, decoupled_wd=True):
644
+ """
645
+ Returns list of dicts defining parameter groups for muP:
646
+ group 0: most model params get scaled learning rate and weight decay.
647
+ group 1: embedding layer gets non-scaled learning rate and weight decay.
648
+ group 2: normalization layers and biases get non-scaled learning rate only.
649
+
650
+ The output can be passed to Adam-base optimizers
651
+ e.g.
652
+ param_groups = model.get_mup_param_groups(lr=1e-3, weight_decay=0.1)
653
+ torch.optim.AdamW(param_groups, betas=(0.9, 0.95), eps=1e-8)
654
+ """
655
+ norm_modules = (
656
+ torch.nn.LayerNorm,
657
+ torch.nn.BatchNorm1d,
658
+ torch.nn.BatchNorm2d,
659
+ torch.nn.BatchNorm3d,
660
+ torch.nn.InstanceNorm1d,
661
+ torch.nn.InstanceNorm2d,
662
+ torch.nn.InstanceNorm3d,
663
+ torch.nn.GroupNorm,
664
+ torch.nn.SyncBatchNorm,
665
+ torch.nn.LocalResponseNorm,
666
+ )
667
+
668
+ def get_group_index(param_name):
669
+ for name, module in self.named_modules():
670
+ if name in param_name:
671
+ if isinstance(module, norm_modules):
672
+ return 2
673
+ elif isinstance(module, torch.nn.Embedding):
674
+ return 1
675
+ return 0
676
+
677
+ width_scale = self.config.mup_width_scale
678
+ new_param_groups = []
679
+ new_param_groups.append({"params": [], "lr": lr * width_scale, "weight_decay": weight_decay})
680
+ if not decoupled_wd:
681
+ new_param_groups[0]["weight_decay"] /= width_scale
682
+ new_param_groups.append({"params": [], "lr": lr, "weight_decay": weight_decay})
683
+ new_param_groups.append({"params": [], "lr": lr, "weight_decay": 0.0})
684
+
685
+ for name, param in self.named_parameters():
686
+ if not param.requires_grad:
687
+ continue
688
+
689
+ if name.endswith("bias"):
690
+ new_param_groups[2]["params"].append(param)
691
+ else:
692
+ new_param_groups[get_group_index(name)]["params"].append(param)
693
+
694
+ for idx, param_group in enumerate(new_param_groups):
695
+ if len(param_group["params"]) == 0:
696
+ del new_param_groups[idx]
697
+
698
+ return new_param_groups
699
+
700
+
701
+ CrystalCoder_START_DOCSTRING = r"""
702
+
703
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
704
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
705
+ etc.)
706
+
707
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
708
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
709
+ and behavior.
710
+
711
+ Parameters:
712
+ config ([`CrystalCoderConfig`]): Model configuration class with all the parameters of the model.
713
+ Initializing with a config file does not load the weights associated with the model, only the
714
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
715
+ """
716
+
717
+ CrystalCoder_INPUTS_DOCSTRING = r"""
718
+ Args:
719
+ input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
720
+ `input_ids_length` = `sequence_length` if `past_key_values` is `None` else
721
+ `past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input
722
+ sequence tokens in the vocabulary.
723
+
724
+ If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
725
+ `input_ids`.
726
+
727
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
728
+ [`PreTrainedTokenizer.__call__`] for details.
729
+
730
+ [What are input IDs?](../glossary#input-ids)
731
+ past_key_values (`Tuple[Tuple[torch.Tensor]]` of length `config.n_layers`):
732
+ Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (see
733
+ `past_key_values` output below). Can be used to speed up sequential decoding. The `input_ids` which have
734
+ their past given to this model should not be passed as `input_ids` as they have already been computed.
735
+ attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
736
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
737
+
738
+ - 1 for tokens that are **not masked**,
739
+ - 0 for tokens that are **masked**.
740
+
741
+ If `past_key_values` is used, `attention_mask` needs to contain the masking strategy that was used for
742
+ `past_key_values`. In other words, the `attention_mask` always has to have the length:
743
+ `len(past_key_values) + len(input_ids)`
744
+
745
+ [What are attention masks?](../glossary#attention-mask)
746
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`, *optional*):
747
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
748
+ 1]`:
749
+
750
+ - 0 corresponds to a *sentence A* token,
751
+ - 1 corresponds to a *sentence B* token.
752
+
753
+ [What are token type IDs?](../glossary#token-type-ids)
754
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
755
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
756
+ config.max_position_embeddings - 1]`.
757
+
758
+ [What are position IDs?](../glossary#position-ids)
759
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
760
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
761
+
762
+ - 1 indicates the head is **not masked**,
763
+ - 0 indicates the head is **masked**.
764
+
765
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
766
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
767
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
768
+ model's internal embedding lookup matrix.
769
+
770
+ If `past_key_values` is used, optionally only the last `inputs_embeds` have to be input (see
771
+ `past_key_values`).
772
+ use_cache (`bool`, *optional*):
773
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
774
+ `past_key_values`).
775
+ output_attentions (`bool`, *optional*):
776
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
777
+ tensors for more detail.
778
+ output_hidden_states (`bool`, *optional*):
779
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
780
+ more detail.
781
+ return_dict (`bool`, *optional*):
782
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
783
+ """
784
+ PARALLELIZE_DOCSTRING = r"""
785
+ This is an experimental feature and is a subject to change at a moment's notice.
786
+
787
+ Uses a device map to distribute attention modules of the model across several devices. If no device map is given,
788
+ it will evenly distribute blocks across all devices.
789
+
790
+ Args:
791
+ device_map (`Dict[int, list]`, optional, defaults to None):
792
+ A dictionary that maps attention modules to devices. Note that the embedding module and LMHead are always
793
+ automatically mapped to the first device (for esoteric reasons). That means that the first device should
794
+ have fewer attention modules mapped to it than other devices. For reference, the gpt2 models have the
795
+ following number of attention modules:
796
+
797
+ - gpt2: 12
798
+ - gpt2-medium: 24
799
+ - gpt2-large: 36
800
+ - gpt2-xl: 48
801
+
802
+ Example:
803
+
804
+ ```python
805
+ # Here is an example of a device map on a machine with 4 GPUs using gpt2-xl, which has a total of 48 attention modules:
806
+ model = GPT2LMHeadModel.from_pretrained("gpt2-xl")
807
+ device_map = {
808
+ 0: [0, 1, 2, 3, 4, 5, 6, 7, 8],
809
+ 1: [9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21],
810
+ 2: [22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34],
811
+ 3: [35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47],
812
+ }
813
+ model.parallelize(device_map)
814
+ ```
815
+ """
816
+ DEPARALLELIZE_DOCSTRING = r"""
817
+ Moves the model to cpu from a model parallel state.
818
+
819
+ Example:
820
+
821
+ ```python
822
+ # On a 4 GPU machine with gpt2-large:
823
+ model = GPT2LMHeadModel.from_pretrained("gpt2-large")
824
+ device_map = {
825
+ 0: [0, 1, 2, 3, 4, 5, 6, 7],
826
+ 1: [8, 9, 10, 11, 12, 13, 14, 15],
827
+ 2: [16, 17, 18, 19, 20, 21, 22, 23],
828
+ 3: [24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35],
829
+ }
830
+ model.parallelize(device_map) # Splits the model across several devices
831
+ model.deparallelize() # Put the model back on cpu and cleans memory by calling torch.cuda.empty_cache()
832
+ ```
833
+ """
834
+
835
+
836
+ @add_start_docstrings(
837
+ "The bare CrystalCoder Model transformer outputting raw hidden-states without any specific head on top.",
838
+ CrystalCoder_START_DOCSTRING,
839
+ )
840
+ class CrystalCoderModel(CrystalCoderPreTrainedModel):
841
+ _keys_to_ignore_on_load_unexpected = [r"h\.\d+\.attn\.bias", r"h\.\d+\.attn\.masked_bias"]
842
+ _keys_to_ignore_on_load_missing = [r"attn.masked_bias", r"h\.\d+\.attn\.masked_bias", r"h\.\d+\.attn\.bias"]
843
+
844
+ def __init__(self, config):
845
+ super().__init__(config)
846
+
847
+ self.embed_dim = config.hidden_size
848
+
849
+ self.wte = nn.Embedding(config.vocab_size, self.embed_dim)
850
+ self.wpe = (
851
+ nn.Embedding(config.max_position_embeddings, self.embed_dim)
852
+ if config.position_embedding_type == "learned"
853
+ else None
854
+ )
855
+ self.embeddings_scale = config.mup_embeddings_scale
856
+
857
+ self.drop = nn.Dropout(config.embd_pdrop)
858
+ self.h = nn.ModuleList([CrystalCoderBlock(config, layer_idx=i) for i in range(config.num_hidden_layers)])
859
+ self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
860
+
861
+ self.relative_pe = (
862
+ AlibiPositionEmbeddingLayer(config.num_attention_heads)
863
+ if config.position_embedding_type == "alibi"
864
+ else None
865
+ )
866
+
867
+ # Model parallel
868
+ self.model_parallel = False
869
+ self.device_map = None
870
+ self.gradient_checkpointing = False
871
+
872
+ # Initialize weights and apply final processing
873
+ self.post_init()
874
+
875
+ @add_start_docstrings(PARALLELIZE_DOCSTRING)
876
+ def parallelize(self, device_map=None):
877
+ # Check validity of device_map
878
+ warnings.warn(
879
+ "`CrystalCoderModel.parallelize` is deprecated and will be removed in v5 of Transformers, you should load your"
880
+ " model with `device_map='balanced'` in the call to `from_pretrained`. You can also provide your own"
881
+ " `device_map` but it needs to be a dictionary module_name to device, so for instance {'h.0': 0, 'h.1': 1,"
882
+ " ...}",
883
+ FutureWarning,
884
+ )
885
+ self.device_map = (
886
+ get_device_map(len(self.h), range(torch.cuda.device_count())) if device_map is None else device_map
887
+ )
888
+ assert_device_map(self.device_map, len(self.h))
889
+ self.model_parallel = True
890
+ self.first_device = "cpu" if "cpu" in self.device_map.keys() else "cuda:" + str(min(self.device_map.keys()))
891
+ self.last_device = "cuda:" + str(max(self.device_map.keys()))
892
+ self.wte = self.wte.to(self.first_device)
893
+ if self.wpe is not None:
894
+ self.wpe = self.wpe.to(self.first_device)
895
+ # Load onto devices
896
+ for k, v in self.device_map.items():
897
+ for block in v:
898
+ cuda_device = "cuda:" + str(k)
899
+ self.h[block] = self.h[block].to(cuda_device)
900
+ # ln_f to last
901
+ self.ln_f = self.ln_f.to(self.last_device)
902
+
903
+ @add_start_docstrings(DEPARALLELIZE_DOCSTRING)
904
+ def deparallelize(self):
905
+ warnings.warn(
906
+ "Like `parallelize`, `deparallelize` is deprecated and will be removed in v5 of Transformers.",
907
+ FutureWarning,
908
+ )
909
+ self.model_parallel = False
910
+ self.device_map = None
911
+ self.first_device = "cpu"
912
+ self.last_device = "cpu"
913
+ self.wte = self.wte.to("cpu")
914
+ if self.wpe is not None:
915
+ self.wpe = self.wpe.to("cpu")
916
+ for index in range(len(self.h)):
917
+ self.h[index] = self.h[index].to("cpu")
918
+ self.ln_f = self.ln_f.to("cpu")
919
+ torch.cuda.empty_cache()
920
+
921
+ def get_input_embeddings(self):
922
+ return self.wte
923
+
924
+ def set_input_embeddings(self, new_embeddings):
925
+ self.wte = new_embeddings
926
+
927
+ def _prune_heads(self, heads_to_prune):
928
+ """
929
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer}
930
+ """
931
+ for layer, heads in heads_to_prune.items():
932
+ self.h[layer].attn.prune_heads(heads)
933
+
934
+ @add_start_docstrings_to_model_forward(CrystalCoder_INPUTS_DOCSTRING)
935
+ def forward(
936
+ self,
937
+ input_ids: Optional[torch.LongTensor] = None,
938
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
939
+ attention_mask: Optional[torch.FloatTensor] = None,
940
+ token_type_ids: Optional[torch.LongTensor] = None,
941
+ position_ids: Optional[torch.LongTensor] = None,
942
+ head_mask: Optional[torch.FloatTensor] = None,
943
+ inputs_embeds: Optional[torch.FloatTensor] = None,
944
+ encoder_hidden_states: Optional[torch.Tensor] = None,
945
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
946
+ use_cache: Optional[bool] = None,
947
+ output_attentions: Optional[bool] = None,
948
+ output_hidden_states: Optional[bool] = None,
949
+ return_dict: Optional[bool] = None,
950
+ ) -> Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]:
951
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
952
+ output_hidden_states = (
953
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
954
+ )
955
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
956
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
957
+
958
+ if input_ids is not None and inputs_embeds is not None:
959
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
960
+ elif input_ids is not None:
961
+ input_shape = input_ids.size()
962
+ input_ids = input_ids.view(-1, input_shape[-1])
963
+ batch_size = input_ids.shape[0]
964
+ elif inputs_embeds is not None:
965
+ input_shape = inputs_embeds.size()[:-1]
966
+ batch_size = inputs_embeds.shape[0]
967
+ else:
968
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
969
+
970
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
971
+
972
+ if token_type_ids is not None:
973
+ token_type_ids = token_type_ids.view(-1, input_shape[-1])
974
+ if position_ids is not None:
975
+ position_ids = position_ids.view(-1, input_shape[-1])
976
+
977
+ if past_key_values is None:
978
+ past_length = 0
979
+ past_key_values = tuple([None] * len(self.h))
980
+ else:
981
+ past_length = past_key_values[0][0].size(-2)
982
+ if position_ids is None:
983
+ position_ids = torch.arange(past_length, input_shape[-1] + past_length, dtype=torch.long, device=device)
984
+ position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])
985
+
986
+ # CrystalCoderAttention mask.
987
+ if attention_mask is not None:
988
+ if batch_size <= 0:
989
+ raise ValueError("batch_size has to be defined and > 0")
990
+ attention_mask = attention_mask.view(batch_size, -1)
991
+ # We create a 3D attention mask from a 2D tensor mask.
992
+ # Sizes are [batch_size, 1, 1, to_seq_length]
993
+ # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
994
+ # this attention mask is more simple than the triangular masking of causal attention
995
+ # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
996
+ attention_mask = attention_mask[:, None, None, :]
997
+
998
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
999
+ # masked positions, this operation will create a tensor which is 0.0 for
1000
+ # positions we want to attend and the dtype's smallest value for masked positions.
1001
+ # Since we are adding it to the raw scores before the softmax, this is
1002
+ # effectively the same as removing these entirely.
1003
+ attention_mask = attention_mask.to(dtype=self.dtype) # fp16 compatibility
1004
+ attention_mask = (1.0 - attention_mask) * torch.finfo(self.dtype).min
1005
+
1006
+ # If a 2D or 3D attention mask is provided for the cross-attention
1007
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
1008
+ if self.config.add_cross_attention and encoder_hidden_states is not None:
1009
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
1010
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
1011
+ if encoder_attention_mask is None:
1012
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
1013
+ encoder_attention_mask = self.invert_attention_mask(encoder_attention_mask)
1014
+ else:
1015
+ encoder_attention_mask = None
1016
+
1017
+ # Prepare head mask if needed
1018
+ # 1.0 in head_mask indicate we keep the head
1019
+ # attention_probs has shape bsz x n_heads x N x N
1020
+ # head_mask has shape n_layer x batch x n_heads x N x N
1021
+ head_mask = self.get_head_mask(head_mask, self.config.n_layer)
1022
+
1023
+ if inputs_embeds is None:
1024
+ inputs_embeds = self.wte(input_ids)
1025
+ if self.wpe is not None:
1026
+ position_embeds = self.wpe(position_ids)
1027
+ hidden_states = inputs_embeds + position_embeds
1028
+ else:
1029
+ hidden_states = inputs_embeds
1030
+ hidden_states *= torch.tensor(
1031
+ float(self.embeddings_scale), dtype=hidden_states.dtype, device=hidden_states.device
1032
+ )
1033
+
1034
+ if token_type_ids is not None:
1035
+ token_type_embeds = self.wte(token_type_ids)
1036
+ hidden_states = hidden_states + token_type_embeds
1037
+
1038
+ hidden_states = self.drop(hidden_states)
1039
+
1040
+ if self.relative_pe is not None:
1041
+ length = input_ids.shape[1]
1042
+ cached_kv_length = 0
1043
+ cached_kv = past_key_values[0]
1044
+ if cached_kv is not None:
1045
+ cached_kv_length = cached_kv[0].shape[-2]
1046
+ position_bias = self.relative_pe(length, length, cached_kv_length)
1047
+ else:
1048
+ position_bias = None
1049
+
1050
+ output_shape = input_shape + (hidden_states.size(-1),)
1051
+
1052
+ if self.gradient_checkpointing and self.training:
1053
+ if use_cache:
1054
+ logger.warning_once(
1055
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1056
+ )
1057
+ use_cache = False
1058
+
1059
+ presents = () if use_cache else None
1060
+ all_self_attentions = () if output_attentions else None
1061
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
1062
+ all_hidden_states = () if output_hidden_states else None
1063
+ for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
1064
+ # Model parallel
1065
+ if self.model_parallel:
1066
+ torch.cuda.set_device(hidden_states.device)
1067
+ # Ensure layer_past is on same device as hidden_states (might not be correct)
1068
+ if layer_past is not None:
1069
+ layer_past = tuple(past_state.to(hidden_states.device) for past_state in layer_past)
1070
+ # Ensure that attention_mask is always on the same device as hidden_states
1071
+ if attention_mask is not None:
1072
+ attention_mask = attention_mask.to(hidden_states.device)
1073
+ if isinstance(head_mask, torch.Tensor):
1074
+ head_mask = head_mask.to(hidden_states.device)
1075
+ if output_hidden_states:
1076
+ all_hidden_states = all_hidden_states + (hidden_states,)
1077
+
1078
+ if self.gradient_checkpointing and self.training:
1079
+
1080
+ def create_custom_forward(module):
1081
+ def custom_forward(*inputs):
1082
+ # None for past_key_value
1083
+ return module(*inputs, use_cache, output_attentions)
1084
+
1085
+ return custom_forward
1086
+
1087
+ outputs = torch.utils.checkpoint.checkpoint(
1088
+ create_custom_forward(block),
1089
+ hidden_states,
1090
+ None,
1091
+ attention_mask,
1092
+ head_mask[i],
1093
+ encoder_hidden_states,
1094
+ encoder_attention_mask,
1095
+ )
1096
+ else:
1097
+ outputs = block(
1098
+ hidden_states,
1099
+ layer_past=layer_past,
1100
+ attention_mask=attention_mask,
1101
+ head_mask=head_mask[i],
1102
+ encoder_hidden_states=encoder_hidden_states,
1103
+ encoder_attention_mask=encoder_attention_mask,
1104
+ use_cache=use_cache,
1105
+ output_attentions=output_attentions,
1106
+ position_bias=position_bias,
1107
+ )
1108
+
1109
+ hidden_states = outputs[0]
1110
+ if use_cache is True:
1111
+ presents = presents + (outputs[1],)
1112
+
1113
+ if output_attentions:
1114
+ all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
1115
+ if self.config.add_cross_attention:
1116
+ all_cross_attentions = all_cross_attentions + (outputs[3 if use_cache else 2],)
1117
+
1118
+ # Model Parallel: If it's the last layer for that device, put things on the next device
1119
+ if self.model_parallel:
1120
+ for k, v in self.device_map.items():
1121
+ if i == v[-1] and "cuda:" + str(k) != self.last_device:
1122
+ hidden_states = hidden_states.to("cuda:" + str(k + 1))
1123
+
1124
+ hidden_states = self.ln_f(hidden_states)
1125
+
1126
+ hidden_states = hidden_states.view(output_shape)
1127
+ # Add last hidden state
1128
+ if output_hidden_states:
1129
+ all_hidden_states = all_hidden_states + (hidden_states,)
1130
+
1131
+ if not return_dict:
1132
+ return tuple(
1133
+ v
1134
+ for v in [hidden_states, presents, all_hidden_states, all_self_attentions, all_cross_attentions]
1135
+ if v is not None
1136
+ )
1137
+
1138
+ return BaseModelOutputWithPastAndCrossAttentions(
1139
+ last_hidden_state=hidden_states,
1140
+ past_key_values=presents,
1141
+ hidden_states=all_hidden_states,
1142
+ attentions=all_self_attentions,
1143
+ cross_attentions=all_cross_attentions,
1144
+ )
1145
+
1146
+
1147
+ @add_start_docstrings(
1148
+ """
1149
+ The CrystalCoder Model transformer with a language modeling head on top (linear layer with weights tied to the input
1150
+ embeddings).
1151
+ """,
1152
+ CrystalCoder_START_DOCSTRING,
1153
+ )
1154
+ class CrystalCoderLMHeadModel(CrystalCoderPreTrainedModel):
1155
+ _keys_to_ignore_on_load_missing = [r"lm_head.weight"]
1156
+ _keys_to_ignore_on_load_unexpected = [r"h\.\d+\.attn\.masked_bias", r"h\.\d+\.attn\.bias"]
1157
+
1158
+ def __init__(self, config):
1159
+ super().__init__(config)
1160
+ self.transformer = CrystalCoderModel(config)
1161
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
1162
+ self.output_logits_scale = config.mup_output_alpha * config.mup_width_scale
1163
+
1164
+ # Model parallel
1165
+ self.model_parallel = False
1166
+ self.device_map = None
1167
+
1168
+ # Initialize weights and apply final processing
1169
+ self.post_init()
1170
+
1171
+ @add_start_docstrings(PARALLELIZE_DOCSTRING)
1172
+ def parallelize(self, device_map=None):
1173
+ warnings.warn(
1174
+ "`CrystalCoderLMHeadModel.parallelize` is deprecated and will be removed in v5 of Transformers, you should load"
1175
+ " your model with `device_map='balanced'` in the call to `from_pretrained`. You can also provide your own"
1176
+ " `device_map` but it needs to be a dictionary module_name to device, so for instance {'transformer.h.0':"
1177
+ " 0, 'transformer.h.1': 1, ...}",
1178
+ FutureWarning,
1179
+ )
1180
+ self.device_map = (
1181
+ get_device_map(len(self.transformer.h), range(torch.cuda.device_count()))
1182
+ if device_map is None
1183
+ else device_map
1184
+ )
1185
+ assert_device_map(self.device_map, len(self.transformer.h))
1186
+ self.transformer.parallelize(self.device_map)
1187
+ self.lm_head = self.lm_head.to(self.transformer.first_device)
1188
+ self.model_parallel = True
1189
+
1190
+ @add_start_docstrings(DEPARALLELIZE_DOCSTRING)
1191
+ def deparallelize(self):
1192
+ warnings.warn(
1193
+ "Like `parallelize`, `deparallelize` is deprecated and will be removed in v5 of Transformers.",
1194
+ FutureWarning,
1195
+ )
1196
+ self.transformer.deparallelize()
1197
+ self.transformer = self.transformer.to("cpu")
1198
+ self.lm_head = self.lm_head.to("cpu")
1199
+ self.model_parallel = False
1200
+ torch.cuda.empty_cache()
1201
+
1202
+ def get_output_embeddings(self):
1203
+ return self.lm_head
1204
+
1205
+ def set_output_embeddings(self, new_embeddings):
1206
+ self.lm_head = new_embeddings
1207
+
1208
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
1209
+ token_type_ids = kwargs.get("token_type_ids", None)
1210
+ # only last token for inputs_ids if past is defined in kwargs
1211
+ if past_key_values:
1212
+ input_ids = input_ids[:, -1].unsqueeze(-1)
1213
+ if token_type_ids is not None:
1214
+ token_type_ids = token_type_ids[:, -1].unsqueeze(-1)
1215
+
1216
+ attention_mask = kwargs.get("attention_mask", None)
1217
+ position_ids = kwargs.get("position_ids", None)
1218
+
1219
+ if attention_mask is not None and position_ids is None:
1220
+ # create position_ids on the fly for batch generation
1221
+ position_ids = attention_mask.long().cumsum(-1) - 1
1222
+ position_ids.masked_fill_(attention_mask == 0, 1)
1223
+ if past_key_values:
1224
+ position_ids = position_ids[:, -1].unsqueeze(-1)
1225
+ else:
1226
+ position_ids = None
1227
+
1228
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1229
+ if inputs_embeds is not None and past_key_values is None:
1230
+ model_inputs = {"inputs_embeds": inputs_embeds}
1231
+ else:
1232
+ model_inputs = {"input_ids": input_ids}
1233
+
1234
+ model_inputs.update(
1235
+ {
1236
+ "past_key_values": past_key_values,
1237
+ "use_cache": kwargs.get("use_cache"),
1238
+ "position_ids": position_ids,
1239
+ "attention_mask": attention_mask,
1240
+ "token_type_ids": token_type_ids,
1241
+ }
1242
+ )
1243
+ return model_inputs
1244
+
1245
+ @add_start_docstrings_to_model_forward(CrystalCoder_INPUTS_DOCSTRING)
1246
+ def forward(
1247
+ self,
1248
+ input_ids: Optional[torch.LongTensor] = None,
1249
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1250
+ attention_mask: Optional[torch.FloatTensor] = None,
1251
+ token_type_ids: Optional[torch.LongTensor] = None,
1252
+ position_ids: Optional[torch.LongTensor] = None,
1253
+ head_mask: Optional[torch.FloatTensor] = None,
1254
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1255
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1256
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
1257
+ labels: Optional[torch.LongTensor] = None,
1258
+ use_cache: Optional[bool] = None,
1259
+ output_attentions: Optional[bool] = None,
1260
+ output_hidden_states: Optional[bool] = None,
1261
+ return_dict: Optional[bool] = None,
1262
+ ) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:
1263
+ r"""
1264
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1265
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
1266
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
1267
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
1268
+ """
1269
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1270
+
1271
+ transformer_outputs = self.transformer(
1272
+ input_ids,
1273
+ past_key_values=past_key_values,
1274
+ attention_mask=attention_mask,
1275
+ token_type_ids=token_type_ids,
1276
+ position_ids=position_ids,
1277
+ head_mask=head_mask,
1278
+ inputs_embeds=inputs_embeds,
1279
+ encoder_hidden_states=encoder_hidden_states,
1280
+ encoder_attention_mask=encoder_attention_mask,
1281
+ use_cache=use_cache,
1282
+ output_attentions=output_attentions,
1283
+ output_hidden_states=output_hidden_states,
1284
+ return_dict=return_dict,
1285
+ )
1286
+ hidden_states = transformer_outputs[0]
1287
+
1288
+ # Set device for model parallelism
1289
+ if self.model_parallel:
1290
+ torch.cuda.set_device(self.transformer.first_device)
1291
+ hidden_states = hidden_states.to(self.lm_head.weight.device)
1292
+
1293
+ lm_logits = self.lm_head(hidden_states)
1294
+ lm_logits *= torch.tensor(float(self.output_logits_scale), dtype=lm_logits.dtype, device=lm_logits.device)
1295
+
1296
+ loss = None
1297
+ if labels is not None:
1298
+ # move labels to correct device to enable model parallelism
1299
+ labels = labels.to(lm_logits.device)
1300
+ # Shift so that tokens < n predict n
1301
+ shift_logits = lm_logits[..., :-1, :].contiguous()
1302
+ shift_labels = labels[..., 1:].contiguous()
1303
+ # Flatten the tokens
1304
+ loss_fct = CrossEntropyLoss()
1305
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
1306
+
1307
+ if not return_dict:
1308
+ output = (lm_logits,) + transformer_outputs[1:]
1309
+ return ((loss,) + output) if loss is not None else output
1310
+
1311
+ return CausalLMOutputWithCrossAttentions(
1312
+ loss=loss,
1313
+ logits=lm_logits,
1314
+ past_key_values=transformer_outputs.past_key_values,
1315
+ hidden_states=transformer_outputs.hidden_states,
1316
+ attentions=transformer_outputs.attentions,
1317
+ cross_attentions=transformer_outputs.cross_attentions,
1318
+ )
1319
+
1320
+ @staticmethod
1321
+ def _reorder_cache(
1322
+ past_key_values: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor
1323
+ ) -> Tuple[Tuple[torch.Tensor]]:
1324
+ """
1325
+ This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
1326
+ [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
1327
+ beam_idx at every generation step.
1328
+ """
1329
+ return tuple(
1330
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past)
1331
+ for layer_past in past_key_values
1332
+ )
1333
+
1334
+
1335
+ @add_start_docstrings(
1336
+ """
1337
+ The CrystalCoder Model transformer with a sequence classification head on top (linear layer).
1338
+
1339
+ [`CrystalCoderForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1340
+ (e.g. GPT-1) do.
1341
+
1342
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1343
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1344
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1345
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1346
+ each row of the batch).
1347
+ """,
1348
+ CrystalCoder_START_DOCSTRING,
1349
+ )
1350
+ class CrystalCoderForSequenceClassification(CrystalCoderPreTrainedModel):
1351
+ _keys_to_ignore_on_load_unexpected = [r"h\.\d+\.attn\.bias", r"h\.\d+\.attn\.masked_bias"]
1352
+ _keys_to_ignore_on_load_missing = [r"h\.\d+\.attn\.masked_bias", r"lm_head.weight"]
1353
+
1354
+ def __init__(self, config):
1355
+ super().__init__(config)
1356
+ self.num_labels = config.num_labels
1357
+ self.transformer = CrystalCoderModel(config)
1358
+ self.score = nn.Linear(config.n_embd, self.num_labels, bias=False)
1359
+ self.output_logits_scale = config.mup_output_alpha * config.mup_width_scale
1360
+
1361
+ # Model parallel
1362
+ self.model_parallel = False
1363
+ self.device_map = None
1364
+
1365
+ # Initialize weights and apply final processing
1366
+ self.post_init()
1367
+
1368
+ @add_start_docstrings_to_model_forward(CrystalCoder_INPUTS_DOCSTRING)
1369
+ @add_code_sample_docstrings(
1370
+ checkpoint="microsoft/DialogRPT-updown",
1371
+ output_type=SequenceClassifierOutputWithPast,
1372
+ config_class=_CONFIG_FOR_DOC,
1373
+ )
1374
+ def forward(
1375
+ self,
1376
+ input_ids: Optional[torch.LongTensor] = None,
1377
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1378
+ attention_mask: Optional[torch.FloatTensor] = None,
1379
+ token_type_ids: Optional[torch.LongTensor] = None,
1380
+ position_ids: Optional[torch.LongTensor] = None,
1381
+ head_mask: Optional[torch.FloatTensor] = None,
1382
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1383
+ labels: Optional[torch.LongTensor] = None,
1384
+ use_cache: Optional[bool] = None,
1385
+ output_attentions: Optional[bool] = None,
1386
+ output_hidden_states: Optional[bool] = None,
1387
+ return_dict: Optional[bool] = None,
1388
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1389
+ r"""
1390
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1391
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1392
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1393
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1394
+ """
1395
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1396
+
1397
+ transformer_outputs = self.transformer(
1398
+ input_ids,
1399
+ past_key_values=past_key_values,
1400
+ attention_mask=attention_mask,
1401
+ token_type_ids=token_type_ids,
1402
+ position_ids=position_ids,
1403
+ head_mask=head_mask,
1404
+ inputs_embeds=inputs_embeds,
1405
+ use_cache=use_cache,
1406
+ output_attentions=output_attentions,
1407
+ output_hidden_states=output_hidden_states,
1408
+ return_dict=return_dict,
1409
+ )
1410
+ hidden_states = transformer_outputs[0]
1411
+ logits = self.score(hidden_states)
1412
+ logits *= torch.tensor(float(self.output_logits_scale), dtype=logits.dtype, device=logits.device)
1413
+
1414
+ if input_ids is not None:
1415
+ batch_size, sequence_length = input_ids.shape[:2]
1416
+ else:
1417
+ batch_size, sequence_length = inputs_embeds.shape[:2]
1418
+
1419
+ assert (
1420
+ self.config.pad_token_id is not None or batch_size == 1
1421
+ ), "Cannot handle batch sizes > 1 if no padding token is defined."
1422
+ if self.config.pad_token_id is None:
1423
+ sequence_lengths = -1
1424
+ else:
1425
+ if input_ids is not None:
1426
+ sequence_lengths = (torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1).to(logits.device)
1427
+ else:
1428
+ sequence_lengths = -1
1429
+ logger.warning(
1430
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
1431
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
1432
+ )
1433
+
1434
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1435
+
1436
+ loss = None
1437
+ if labels is not None:
1438
+ if self.config.problem_type is None:
1439
+ if self.num_labels == 1:
1440
+ self.config.problem_type = "regression"
1441
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1442
+ self.config.problem_type = "single_label_classification"
1443
+ else:
1444
+ self.config.problem_type = "multi_label_classification"
1445
+
1446
+ if self.config.problem_type == "regression":
1447
+ loss_fct = MSELoss()
1448
+ if self.num_labels == 1:
1449
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1450
+ else:
1451
+ loss = loss_fct(pooled_logits, labels)
1452
+ elif self.config.problem_type == "single_label_classification":
1453
+ loss_fct = CrossEntropyLoss()
1454
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1455
+ elif self.config.problem_type == "multi_label_classification":
1456
+ loss_fct = BCEWithLogitsLoss()
1457
+ loss = loss_fct(pooled_logits, labels)
1458
+ if not return_dict:
1459
+ output = (pooled_logits,) + transformer_outputs[1:]
1460
+ return ((loss,) + output) if loss is not None else output
1461
+
1462
+ return SequenceClassifierOutputWithPast(
1463
+ loss=loss,
1464
+ logits=pooled_logits,
1465
+ past_key_values=transformer_outputs.past_key_values,
1466
+ hidden_states=transformer_outputs.hidden_states,
1467
+ attentions=transformer_outputs.attentions,
1468
+ )
1469
+
1470
+
1471
+ @add_start_docstrings(
1472
+ """
1473
+ CrystalCoder Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1474
+ Named-Entity-Recognition (NER) tasks.
1475
+ """,
1476
+ CrystalCoder_START_DOCSTRING,
1477
+ )
1478
+ class CrystalCoderForTokenClassification(CrystalCoderPreTrainedModel):
1479
+ def __init__(self, config):
1480
+ super().__init__(config)
1481
+ self.num_labels = config.num_labels
1482
+
1483
+ self.transformer = CrystalCoderModel(config)
1484
+ if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
1485
+ classifier_dropout = config.classifier_dropout
1486
+ elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
1487
+ classifier_dropout = config.hidden_dropout
1488
+ else:
1489
+ classifier_dropout = 0.1
1490
+ self.dropout = nn.Dropout(classifier_dropout)
1491
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1492
+ self.output_logits_scale = config.mup_output_alpha * config.mup_width_scale
1493
+
1494
+ # Model parallel
1495
+ self.model_parallel = False
1496
+ self.device_map = None
1497
+
1498
+ # Initialize weights and apply final processing
1499
+ self.post_init()
1500
+
1501
+ @add_start_docstrings_to_model_forward(CrystalCoder_INPUTS_DOCSTRING)
1502
+ # fmt: off
1503
+ @add_code_sample_docstrings(
1504
+ checkpoint="brad1141/gpt2-finetuned-comp2",
1505
+ output_type=TokenClassifierOutput,
1506
+ config_class=_CONFIG_FOR_DOC,
1507
+ expected_loss=0.25,
1508
+ expected_output=["Lead", "Lead", "Lead", "Position", "Lead", "Lead", "Lead", "Lead", "Lead", "Lead", "Lead", "Lead"],
1509
+ )
1510
+ # fmt: on
1511
+ def forward(
1512
+ self,
1513
+ input_ids: Optional[torch.LongTensor] = None,
1514
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1515
+ attention_mask: Optional[torch.FloatTensor] = None,
1516
+ token_type_ids: Optional[torch.LongTensor] = None,
1517
+ position_ids: Optional[torch.LongTensor] = None,
1518
+ head_mask: Optional[torch.FloatTensor] = None,
1519
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1520
+ labels: Optional[torch.LongTensor] = None,
1521
+ use_cache: Optional[bool] = None,
1522
+ output_attentions: Optional[bool] = None,
1523
+ output_hidden_states: Optional[bool] = None,
1524
+ return_dict: Optional[bool] = None,
1525
+ ) -> Union[Tuple, TokenClassifierOutput]:
1526
+ r"""
1527
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1528
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1529
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1530
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1531
+ """
1532
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1533
+
1534
+ transformer_outputs = self.transformer(
1535
+ input_ids,
1536
+ past_key_values=past_key_values,
1537
+ attention_mask=attention_mask,
1538
+ token_type_ids=token_type_ids,
1539
+ position_ids=position_ids,
1540
+ head_mask=head_mask,
1541
+ inputs_embeds=inputs_embeds,
1542
+ use_cache=use_cache,
1543
+ output_attentions=output_attentions,
1544
+ output_hidden_states=output_hidden_states,
1545
+ return_dict=return_dict,
1546
+ )
1547
+
1548
+ hidden_states = transformer_outputs[0]
1549
+ hidden_states = self.dropout(hidden_states)
1550
+ logits = self.classifier(hidden_states)
1551
+ logits *= torch.tensor(float(self.output_logits_scale), dtype=logits.dtype, device=logits.device)
1552
+
1553
+ loss = None
1554
+ if labels is not None:
1555
+ labels = labels.to(logits.device)
1556
+ loss_fct = CrossEntropyLoss()
1557
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1558
+
1559
+ if not return_dict:
1560
+ output = (logits,) + transformer_outputs[2:]
1561
+ return ((loss,) + output) if loss is not None else output
1562
+
1563
+ return TokenClassifierOutput(
1564
+ loss=loss,
1565
+ logits=logits,
1566
+ hidden_states=transformer_outputs.hidden_states,
1567
+ attentions=transformer_outputs.attentions,
1568
+ )
1569
+
1570
+
1571
+ @add_start_docstrings(
1572
+ """
1573
+ The CrystalCoder Model transformer with a span classification head on top for extractive question-answering tasks like
1574
+ SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
1575
+ """,
1576
+ CrystalCoder_START_DOCSTRING,
1577
+ )
1578
+ class CrystalCoderForQuestionAnswering(CrystalCoderPreTrainedModel):
1579
+ _keys_to_ignore_on_load_unexpected = [r"h\.\d+\.attn\.bias", r"h\.\d+\.attn\.masked_bias"]
1580
+ _keys_to_ignore_on_load_missing = [r"h\.\d+\.attn\.masked_bias", r"h\.\d+\.attn\.bias", r"lm_head.weight"]
1581
+
1582
+ def __init__(self, config):
1583
+ super().__init__(config)
1584
+ self.num_labels = config.num_labels
1585
+ self.transformer = CrystalCoderModel(config)
1586
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
1587
+ self.output_logits_scale = config.mup_output_alpha * config.mup_width_scale
1588
+
1589
+ # Model parallel
1590
+ self.model_parallel = False
1591
+ self.device_map = None
1592
+ self.gradient_checkpointing = False
1593
+
1594
+ # Initialize weights and apply final processing
1595
+ self.post_init()
1596
+
1597
+ @add_start_docstrings_to_model_forward(CrystalCoder_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1598
+ def forward(
1599
+ self,
1600
+ input_ids: Optional[torch.LongTensor] = None,
1601
+ attention_mask: Optional[torch.FloatTensor] = None,
1602
+ token_type_ids: Optional[torch.LongTensor] = None,
1603
+ position_ids: Optional[torch.LongTensor] = None,
1604
+ head_mask: Optional[torch.FloatTensor] = None,
1605
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1606
+ start_positions: Optional[torch.LongTensor] = None,
1607
+ end_positions: Optional[torch.LongTensor] = None,
1608
+ output_attentions: Optional[bool] = None,
1609
+ output_hidden_states: Optional[bool] = None,
1610
+ return_dict: Optional[bool] = None,
1611
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1612
+ r"""
1613
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1614
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1615
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1616
+ are not taken into account for computing the loss.
1617
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1618
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1619
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1620
+ are not taken into account for computing the loss.
1621
+ """
1622
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1623
+
1624
+ outputs = self.transformer(
1625
+ input_ids,
1626
+ attention_mask=attention_mask,
1627
+ token_type_ids=token_type_ids,
1628
+ position_ids=position_ids,
1629
+ head_mask=head_mask,
1630
+ inputs_embeds=inputs_embeds,
1631
+ output_attentions=output_attentions,
1632
+ output_hidden_states=output_hidden_states,
1633
+ return_dict=return_dict,
1634
+ )
1635
+
1636
+ sequence_output = outputs[0]
1637
+
1638
+ logits = self.qa_outputs(sequence_output)
1639
+ logits *= torch.tensor(float(self.output_logits_scale), dtype=logits.dtype, device=logits.device)
1640
+ start_logits, end_logits = logits.split(1, dim=-1)
1641
+ start_logits = start_logits.squeeze(-1).contiguous()
1642
+ end_logits = end_logits.squeeze(-1).contiguous()
1643
+
1644
+ total_loss = None
1645
+ if start_positions is not None and end_positions is not None:
1646
+ # If we are on multi-GPU, split add a dimension
1647
+ if len(start_positions.size()) > 1:
1648
+ start_positions = start_positions.squeeze(-1).to(start_logits.device)
1649
+ if len(end_positions.size()) > 1:
1650
+ end_positions = end_positions.squeeze(-1).to(end_logits.device)
1651
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1652
+ ignored_index = start_logits.size(1)
1653
+ start_positions = start_positions.clamp(0, ignored_index)
1654
+ end_positions = end_positions.clamp(0, ignored_index)
1655
+
1656
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1657
+ start_loss = loss_fct(start_logits, start_positions)
1658
+ end_loss = loss_fct(end_logits, end_positions)
1659
+ total_loss = (start_loss + end_loss) / 2
1660
+
1661
+ if not return_dict:
1662
+ output = (start_logits, end_logits) + outputs[2:]
1663
+ return ((total_loss,) + output) if total_loss is not None else output
1664
+
1665
+ return QuestionAnsweringModelOutput(
1666
+ loss=total_loss,
1667
+ start_logits=start_logits,
1668
+ end_logits=end_logits,
1669
+ hidden_states=outputs.hidden_states,
1670
+ attentions=outputs.attentions,
1671
+ )
special_tokens_map.json ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|fim_prefix|>",
4
+ "<|fim_middle|>",
5
+ "<|fim_suffix|>",
6
+ "<|fim_pad|>",
7
+ "<|filename|>",
8
+ "<|gh_stars|>",
9
+ "<|issue_start|>",
10
+ "<|issue_comment|>",
11
+ "<|issue_closed|>",
12
+ "<|jupyter_start|>",
13
+ "<|jupyter_text|>",
14
+ "<|jupyter_code|>",
15
+ "<|jupyter_output|>",
16
+ "<|empty_output|>",
17
+ "<|commit_before|>",
18
+ "<|commit_msg|>",
19
+ "<|commit_after|>",
20
+ "<|reponame|>",
21
+ "<|im_start|>",
22
+ "<|im_end|>",
23
+ "<|sys_start|>",
24
+ "<|sys_end|>"
25
+ ],
26
+ "bos_token": {
27
+ "content": "<s>",
28
+ "lstrip": false,
29
+ "normalized": false,
30
+ "rstrip": false,
31
+ "single_word": false
32
+ },
33
+ "eos_token": {
34
+ "content": "</s>",
35
+ "lstrip": false,
36
+ "normalized": false,
37
+ "rstrip": false,
38
+ "single_word": false
39
+ },
40
+ "unk_token": {
41
+ "content": "<unk>",
42
+ "lstrip": false,
43
+ "normalized": false,
44
+ "rstrip": false,
45
+ "single_word": false
46
+ }
47
+ }
tokenization_crystalcoder_fast.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os
3
+ from shutil import copyfile
4
+ from typing import Optional, Tuple
5
+
6
+ from tokenizers import processors
7
+
8
+ from transformers.tokenization_utils_fast import PreTrainedTokenizerFast
9
+ from transformers.utils import is_sentencepiece_available, logging
10
+ from transformers.utils.versions import require_version
11
+
12
+
13
+ require_version("tokenizers>=0.13.3")
14
+
15
+
16
+
17
+ logger = logging.get_logger(__name__)
18
+ VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model", "tokenizer_file": "tokenizer.json"}
19
+
20
+ # fmt: off
21
+ DEFAULT_SYSTEM_PROMPT = """You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your \
22
+ answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure\
23
+ that your responses are socially unbiased and positive in nature.
24
+
25
+ If a question does not make any sense, or is not factually coherent, explain why instead of answering something not \
26
+ correct. If you don't know the answer to a question, please don't share false information."""
27
+ # fmt: on
28
+
29
+
30
+ class CrystalCoderTokenizerFast(PreTrainedTokenizerFast):
31
+
32
+
33
+ vocab_files_names = VOCAB_FILES_NAMES
34
+ slow_tokenizer_class = None
35
+ padding_side = "left"
36
+ model_input_names = ["input_ids", "attention_mask"]
37
+
38
+ def __init__(
39
+ self,
40
+ vocab_file=None,
41
+ tokenizer_file=None,
42
+ clean_up_tokenization_spaces=False,
43
+ unk_token="<|unk|>",
44
+ bos_token="<|startoftext|>",
45
+ eos_token="<|endoftext|>",
46
+ add_bos_token=False,
47
+ add_eos_token=False,
48
+ use_default_system_prompt=False,
49
+ **kwargs,
50
+ ):
51
+ super().__init__(
52
+ vocab_file=vocab_file,
53
+ tokenizer_file=tokenizer_file,
54
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
55
+ unk_token=unk_token,
56
+ bos_token=bos_token,
57
+ eos_token=eos_token,
58
+ use_default_system_prompt=use_default_system_prompt,
59
+ **kwargs,
60
+ )
61
+ self._add_bos_token = add_bos_token
62
+ self._add_eos_token = add_eos_token
63
+ self.update_post_processor()
64
+ self.use_default_system_prompt = use_default_system_prompt
65
+ self.vocab_file = vocab_file
66
+
67
+ @property
68
+ def can_save_slow_tokenizer(self) -> bool:
69
+ return os.path.isfile(self.vocab_file) if self.vocab_file else False
70
+
71
+ def update_post_processor(self):
72
+ """
73
+ Updates the underlying post processor with the current `bos_token` and `eos_token`.
74
+ """
75
+ bos = self.bos_token
76
+ bos_token_id = self.bos_token_id
77
+ if bos is None and self.add_bos_token:
78
+ raise ValueError("add_bos_token = True but bos_token = None")
79
+
80
+ eos = self.eos_token
81
+ eos_token_id = self.eos_token_id
82
+ if eos is None and self.add_eos_token:
83
+ raise ValueError("add_eos_token = True but eos_token = None")
84
+
85
+ single = f"{(bos+':0 ') if self.add_bos_token else ''}$A:0{(' '+eos+':0') if self.add_eos_token else ''}"
86
+ pair = f"{single}{(' '+bos+':1') if self.add_bos_token else ''} $B:1{(' '+eos+':1') if self.add_eos_token else ''}"
87
+
88
+ special_tokens = []
89
+ if self.add_bos_token:
90
+ special_tokens.append((bos, bos_token_id))
91
+ if self.add_eos_token:
92
+ special_tokens.append((eos, eos_token_id))
93
+ self._tokenizer.post_processor = processors.TemplateProcessing(
94
+ single=single, pair=pair, special_tokens=special_tokens
95
+ )
96
+
97
+ @property
98
+ def add_eos_token(self):
99
+ return self._add_eos_token
100
+
101
+ @property
102
+ def add_bos_token(self):
103
+ return self._add_bos_token
104
+
105
+ @add_eos_token.setter
106
+ def add_eos_token(self, value):
107
+ self._add_eos_token = value
108
+ self.update_post_processor()
109
+
110
+ @add_bos_token.setter
111
+ def add_bos_token(self, value):
112
+ self._add_bos_token = value
113
+ self.update_post_processor()
114
+
115
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
116
+ if not self.can_save_slow_tokenizer:
117
+ raise ValueError(
118
+ "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
119
+ "tokenizer."
120
+ )
121
+
122
+ if not os.path.isdir(save_directory):
123
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
124
+ return
125
+ out_vocab_file = os.path.join(
126
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
127
+ )
128
+
129
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
130
+ copyfile(self.vocab_file, out_vocab_file)
131
+
132
+ return (out_vocab_file,)
133
+
134
+
135
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
136
+ bos_token_id = [self.bos_token_id] if self.add_bos_token else []
137
+ eos_token_id = [self.eos_token_id] if self.add_eos_token else []
138
+
139
+ output = bos_token_id + token_ids_0 + eos_token_id
140
+
141
+ if token_ids_1 is not None:
142
+ output = output + bos_token_id + token_ids_1 + eos_token_id
143
+
144
+ return output
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "<unk>",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "1": {
12
+ "content": "<s>",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "2": {
20
+ "content": "</s>",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "32000": {
28
+ "content": "<|fim_prefix|>",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "32001": {
36
+ "content": "<|fim_middle|>",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ },
43
+ "32002": {
44
+ "content": "<|fim_suffix|>",
45
+ "lstrip": false,
46
+ "normalized": false,
47
+ "rstrip": false,
48
+ "single_word": false,
49
+ "special": true
50
+ },
51
+ "32003": {
52
+ "content": "<|fim_pad|>",
53
+ "lstrip": false,
54
+ "normalized": false,
55
+ "rstrip": false,
56
+ "single_word": false,
57
+ "special": true
58
+ },
59
+ "32004": {
60
+ "content": "<|filename|>",
61
+ "lstrip": false,
62
+ "normalized": false,
63
+ "rstrip": false,
64
+ "single_word": false,
65
+ "special": true
66
+ },
67
+ "32005": {
68
+ "content": "<|gh_stars|>",
69
+ "lstrip": false,
70
+ "normalized": false,
71
+ "rstrip": false,
72
+ "single_word": false,
73
+ "special": true
74
+ },
75
+ "32006": {
76
+ "content": "<|issue_start|>",
77
+ "lstrip": false,
78
+ "normalized": false,
79
+ "rstrip": false,
80
+ "single_word": false,
81
+ "special": true
82
+ },
83
+ "32007": {
84
+ "content": "<|issue_comment|>",
85
+ "lstrip": false,
86
+ "normalized": false,
87
+ "rstrip": false,
88
+ "single_word": false,
89
+ "special": true
90
+ },
91
+ "32008": {
92
+ "content": "<|issue_closed|>",
93
+ "lstrip": false,
94
+ "normalized": false,
95
+ "rstrip": false,
96
+ "single_word": false,
97
+ "special": true
98
+ },
99
+ "32009": {
100
+ "content": "<|jupyter_start|>",
101
+ "lstrip": false,
102
+ "normalized": false,
103
+ "rstrip": false,
104
+ "single_word": false,
105
+ "special": true
106
+ },
107
+ "32010": {
108
+ "content": "<|jupyter_text|>",
109
+ "lstrip": false,
110
+ "normalized": false,
111
+ "rstrip": false,
112
+ "single_word": false,
113
+ "special": true
114
+ },
115
+ "32011": {
116
+ "content": "<|jupyter_code|>",
117
+ "lstrip": false,
118
+ "normalized": false,
119
+ "rstrip": false,
120
+ "single_word": false,
121
+ "special": true
122
+ },
123
+ "32012": {
124
+ "content": "<|jupyter_output|>",
125
+ "lstrip": false,
126
+ "normalized": false,
127
+ "rstrip": false,
128
+ "single_word": false,
129
+ "special": true
130
+ },
131
+ "32013": {
132
+ "content": "<|empty_output|>",
133
+ "lstrip": false,
134
+ "normalized": false,
135
+ "rstrip": false,
136
+ "single_word": false,
137
+ "special": true
138
+ },
139
+ "32014": {
140
+ "content": "<|commit_before|>",
141
+ "lstrip": false,
142
+ "normalized": false,
143
+ "rstrip": false,
144
+ "single_word": false,
145
+ "special": true
146
+ },
147
+ "32015": {
148
+ "content": "<|commit_msg|>",
149
+ "lstrip": false,
150
+ "normalized": false,
151
+ "rstrip": false,
152
+ "single_word": false,
153
+ "special": true
154
+ },
155
+ "32016": {
156
+ "content": "<|commit_after|>",
157
+ "lstrip": false,
158
+ "normalized": false,
159
+ "rstrip": false,
160
+ "single_word": false,
161
+ "special": true
162
+ },
163
+ "32017": {
164
+ "content": "<|reponame|>",
165
+ "lstrip": false,
166
+ "normalized": false,
167
+ "rstrip": false,
168
+ "single_word": false,
169
+ "special": true
170
+ },
171
+ "32018": {
172
+ "content": "<|im_start|>",
173
+ "lstrip": false,
174
+ "normalized": false,
175
+ "rstrip": false,
176
+ "single_word": false,
177
+ "special": true
178
+ },
179
+ "32019": {
180
+ "content": "<|im_end|>",
181
+ "lstrip": false,
182
+ "normalized": false,
183
+ "rstrip": false,
184
+ "single_word": false,
185
+ "special": true
186
+ },
187
+ "32020": {
188
+ "content": "<|sys_start|>",
189
+ "lstrip": false,
190
+ "normalized": false,
191
+ "rstrip": false,
192
+ "single_word": false,
193
+ "special": true
194
+ },
195
+ "32021": {
196
+ "content": "<|sys_end|>",
197
+ "lstrip": false,
198
+ "normalized": false,
199
+ "rstrip": false,
200
+ "single_word": false,
201
+ "special": true
202
+ }
203
+ },
204
+ "additional_special_tokens": [
205
+ "<|fim_prefix|>",
206
+ "<|fim_middle|>",
207
+ "<|fim_suffix|>",
208
+ "<|fim_pad|>",
209
+ "<|filename|>",
210
+ "<|gh_stars|>",
211
+ "<|issue_start|>",
212
+ "<|issue_comment|>",
213
+ "<|issue_closed|>",
214
+ "<|jupyter_start|>",
215
+ "<|jupyter_text|>",
216
+ "<|jupyter_code|>",
217
+ "<|jupyter_output|>",
218
+ "<|empty_output|>",
219
+ "<|commit_before|>",
220
+ "<|commit_msg|>",
221
+ "<|commit_after|>",
222
+ "<|reponame|>",
223
+ "<|im_start|>",
224
+ "<|im_end|>",
225
+ "<|sys_start|>",
226
+ "<|sys_end|>"
227
+ ],
228
+ "auto_map": {
229
+ "AutoTokenizer": [
230
+ null,
231
+ "tokenization_crystalcoder_fast.CrystalCoderTokenizerFast"
232
+ ]
233
+ },
234
+ "bos_token": "<s>",
235
+ "clean_up_tokenization_spaces": false,
236
+ "eos_token": "</s>",
237
+ "legacy": false,
238
+ "model_max_length": 1000000000000000019884624838656,
239
+ "pad_token": null,
240
+ "padding_side": "right",
241
+ "sp_model_kwargs": {},
242
+ "tokenizer_class": "CrystalCoderTokenizer",
243
+ "unk_token": "<unk>",
244
+ "use_default_system_prompt": false
245
+ }