kyone commited on
Commit
3d6b885
·
verified ·
1 Parent(s): 78ca15e

Upload OLMoForCausalLM

Browse files
Files changed (3) hide show
  1. README.md +2 -2
  2. config.json +1 -1
  3. modeling_olmo.py +146 -0
README.md CHANGED
@@ -1,8 +1,8 @@
1
  ---
2
- library_name: transformers
3
- license: apache-2.0
4
  language:
5
  - en
 
 
6
  ---
7
 
8
  # Model Card for Model ID
 
1
  ---
 
 
2
  language:
3
  - en
4
+ license: apache-2.0
5
+ library_name: transformers
6
  ---
7
 
8
  # Model Card for Model ID
config.json CHANGED
@@ -11,7 +11,7 @@
11
  "attention_layer_norm_with_affine": false,
12
  "auto_map": {
13
  "AutoConfig": "configuration_olmo.OLMoConfig",
14
- "AutoModelForCausalLM": "allenai/OLMo-1B--modeling_olmo.OLMoForCausalLM",
15
  "AutoTokenizer": [
16
  "allenai/OLMo-1B--tokenization_olmo_fast.OLMoTokenizerFast",
17
  "allenai/OLMo-1B--tokenization_olmo_fast.OLMoTokenizerFast"
 
11
  "attention_layer_norm_with_affine": false,
12
  "auto_map": {
13
  "AutoConfig": "configuration_olmo.OLMoConfig",
14
+ "AutoModelForCausalLM": "modeling_olmo.OLMoForCausalLM",
15
  "AutoTokenizer": [
16
  "allenai/OLMo-1B--tokenization_olmo_fast.OLMoTokenizerFast",
17
  "allenai/OLMo-1B--tokenization_olmo_fast.OLMoTokenizerFast"
modeling_olmo.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import fields
2
+ from typing import List, Optional, Tuple, Union
3
+
4
+ import torch
5
+ from transformers import PreTrainedModel
6
+ from transformers.modeling_outputs import CausalLMOutputWithPast
7
+ from transformers.models.auto import AutoModelForCausalLM
8
+
9
+ from olmo.config import ModelConfig
10
+ from olmo.model import Olmo
11
+
12
+ from .configuration_olmo import OLMoConfig
13
+
14
+
15
+ def create_model_config_from_pretrained_config(config: OLMoConfig):
16
+ """
17
+ Utility function
18
+ """
19
+
20
+ kwargs = {}
21
+ for field in fields(ModelConfig):
22
+ kwargs[field.name] = getattr(config, field.name)
23
+
24
+ model_config = ModelConfig(**kwargs)
25
+ return model_config
26
+
27
+
28
+ class OLMoForCausalLM(PreTrainedModel):
29
+ """
30
+ Extremely barebones HF model wrapper.
31
+ """
32
+
33
+ config_class = OLMoConfig
34
+ base_model_prefix = "model"
35
+ _no_split_modules = ["OLMoBlock"]
36
+
37
+ def __init__(self, config: OLMoConfig, model: Optional[Olmo] = None, init_params: bool = False):
38
+ super().__init__(config)
39
+
40
+ if not model:
41
+ model_config = create_model_config_from_pretrained_config(config)
42
+ # Initialize model (always on CPU to start with so we don't run out of GPU memory).
43
+ model_config.init_device = "cpu"
44
+ self.model = Olmo(model_config, init_params=init_params)
45
+ else:
46
+ self.model = model
47
+
48
+ def forward(
49
+ self,
50
+ input_ids: torch.LongTensor = None,
51
+ attention_mask: Optional[torch.Tensor] = None,
52
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
53
+ labels: Optional[torch.LongTensor] = None,
54
+ use_cache: Optional[bool] = None,
55
+ output_attentions: Optional[bool] = None,
56
+ output_hidden_states: Optional[bool] = None,
57
+ return_dict: Optional[bool] = None,
58
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
59
+ if use_cache is None:
60
+ use_cache = self.config.use_cache
61
+
62
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
63
+
64
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
65
+ outputs = self.model.forward(
66
+ input_ids=input_ids,
67
+ attention_mask=attention_mask,
68
+ past_key_values=past_key_values,
69
+ use_cache=use_cache,
70
+ )
71
+
72
+ logits = outputs.logits
73
+
74
+ loss = None
75
+ if labels is not None:
76
+ # Shift so that tokens < n predict n
77
+ shift_logits = logits[..., :-1, :].contiguous()
78
+ shift_labels = labels[..., 1:].contiguous()
79
+ # Flatten the tokens
80
+ loss_fct = torch.nn.CrossEntropyLoss()
81
+ shift_logits = shift_logits.view(-1, self.config.embedding_size)
82
+ shift_labels = shift_labels.view(-1)
83
+ # Enable model parallelism
84
+ shift_labels = shift_labels.to(shift_logits.device)
85
+ loss = loss_fct(shift_logits, shift_labels)
86
+
87
+ if not return_dict:
88
+ output = (logits,) + outputs[1:]
89
+ return (loss,) + output if loss is not None else output
90
+
91
+ return CausalLMOutputWithPast(
92
+ loss=loss,
93
+ logits=logits,
94
+ past_key_values=outputs.attn_key_values,
95
+ )
96
+
97
+ def can_generate(self) -> bool:
98
+ return True
99
+
100
+ def prepare_inputs_for_generation(
101
+ self, input_ids: torch.LongTensor, past_key_values: Optional[List[Tuple]] = None, **kwargs
102
+ ):
103
+ if past_key_values:
104
+ # This is because we want the model to only process the last generated token.
105
+ input_ids = input_ids[:, -1:]
106
+ model_inputs = {"input_ids": input_ids, "past_key_values": past_key_values}
107
+
108
+ model_inputs.update(kwargs)
109
+ model_inputs["use_cache"] = kwargs.pop("use_cache", self.config.use_cache)
110
+ return model_inputs
111
+
112
+ # TODO: these are required to make the implementation complete.
113
+ # def resize_position_embeddings(self, new_num_position_embeddings: int):
114
+ # pass
115
+ #
116
+ # def get_position_embeddings(self) -> Union[nn.Embedding, Tuple[nn.Embedding]]:
117
+ # pass
118
+ #
119
+ # def _reorder_cache(self, past_key_values, beam_idx):
120
+ # pass
121
+
122
+ def get_input_embeddings(self) -> torch.nn.Module:
123
+ return self.model.transformer.wte
124
+
125
+ def set_input_embeddings(self, value: torch.nn.Module):
126
+ self.model.transformer.wte = value
127
+
128
+ def get_output_embeddings(self):
129
+ if self.config.weight_tying:
130
+ return self.model.transformer.wte
131
+ else:
132
+ return self.model.transformer.ff_out
133
+
134
+ def set_output_embeddings(self, value: torch.nn.Module):
135
+ if self.config.weight_tying:
136
+ self.model.transformer.wte = value
137
+ else:
138
+ self.model.transformer.ff_out = value
139
+
140
+ def tie_weights(self):
141
+ if self.config.weight_tying:
142
+ self.model.transformer.ff_out = self.model.transformer.wte
143
+
144
+
145
+ # Register the model so that it is available for transformer pipelines, auto-loading, etc.
146
+ AutoModelForCausalLM.register(OLMoConfig, OLMoForCausalLM)