English
naveensp commited on
Commit
8aa1ccc
·
verified ·
1 Parent(s): be33a6c

Delete modeling_olmo.py

Browse files
Files changed (1) hide show
  1. modeling_olmo.py +0 -187
modeling_olmo.py DELETED
@@ -1,187 +0,0 @@
1
- from dataclasses import fields
2
- from typing import List, Optional, Tuple, Union
3
-
4
- import torch
5
- import torch.nn.functional as F
6
- import math
7
- from transformers import PreTrainedModel
8
- from transformers.modeling_outputs import CausalLMOutputWithPast, BaseModelOutputWithPast
9
- from transformers.models.auto import AutoModelForCausalLM
10
-
11
- from .config import ModelConfig
12
- from .model import OLMo
13
-
14
- from .configuration_olmo import OLMoConfig
15
-
16
- def create_model_config_from_pretrained_config(config: OLMoConfig):
17
- """
18
- Utility function
19
- """
20
-
21
- kwargs = {}
22
- for field in fields(ModelConfig):
23
- kwargs[field.name] = getattr(config, field.name)
24
-
25
- model_config = ModelConfig(**kwargs)
26
- return model_config
27
-
28
- class OLMoPreTrainedModel(PreTrainedModel):
29
- config_class = OLMoConfig
30
- base_model_prefix = "model"
31
- _no_split_modules = ["OLMoBlock"]
32
- # _skip_keys_device_placement = ["past_key_values", "causal_mask"]
33
- _skip_keys_device_placement = ["past_key_values"]
34
-
35
- def _init_weights(self, module):
36
- # `OLMoModel.reset_parameters` initializes weights of itself and its children
37
- if isinstance(module, OLMo):
38
- module.reset_parameters()
39
-
40
- class OLMoForCausalLM(OLMoPreTrainedModel):
41
- _tied_weights_keys = []
42
- # _tied_weights_keys = ["transformer.wte.weight"]
43
-
44
- def __init__(self, config: OLMoConfig):
45
- super().__init__(config)
46
- self.model = OLMo(config)
47
-
48
- # Initialize weights and apply final processing
49
- self.post_init()
50
-
51
- def get_input_embeddings(self) -> torch.nn.Module:
52
- return self.model.transformer.wte
53
-
54
- def set_input_embeddings(self, value: torch.nn.Module):
55
- self.model.transformer.wte = value
56
-
57
- def get_output_embeddings(self):
58
- if self.config.weight_tying:
59
- return self.model.transformer.wte
60
- else:
61
- return self.model.transformer.ff_out
62
-
63
- def set_output_embeddings(self, value: torch.nn.Module):
64
- if self.config.weight_tying:
65
- self.model.transformer.wte = value
66
- else:
67
- self.model.transformer.ff_out = value
68
-
69
- def set_decoder(self, decoder):
70
- self.model = decoder
71
-
72
- def get_decoder(self):
73
- return self.model
74
-
75
- def forward(
76
- self,
77
- input_ids: torch.LongTensor = None,
78
- inputs_embeds: Optional[torch.FloatTensor] = None,
79
- attention_mask: Optional[torch.Tensor] = None,
80
- attention_bias: Optional[torch.Tensor] = None,
81
- past_key_values: Optional[List[torch.FloatTensor]] = None,
82
- labels: Optional[torch.LongTensor] = None,
83
- use_cache: Optional[bool] = None,
84
- output_attentions: Optional[bool] = None,
85
- output_hidden_states: Optional[bool] = None,
86
- return_dict: Optional[bool] = None,
87
- ) -> Union[Tuple, CausalLMOutputWithPast]:
88
- r"""
89
- Args:
90
- labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
91
- Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
92
- config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
93
- (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
94
- Returns:
95
- Example:
96
- ```python
97
- >>> from transformers import AutoTokenizer, OLMoForCausalLM
98
- >>> model = OLMoForCausalLM.from_pretrained("allenai/OLMo-7B")
99
- >>> tokenizer = AutoTokenizer.from_pretrained("allenai/OLMo-7B")
100
- >>> prompt = "Hey, are you conscious? Can you talk to me?"
101
- >>> inputs = tokenizer(prompt, return_tensors="pt")
102
- >>> # Generate
103
- >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
104
- >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
105
- "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
106
- ```"""
107
- output_attentions = output_attentions or self.config.output_attentions
108
- output_hidden_states = output_hidden_states or self.config.output_hidden_states
109
- use_cache = use_cache if use_cache is not None else self.config.use_cache
110
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
111
-
112
- assert not output_attentions
113
-
114
- # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
115
- base_output: Union[BaseModelOutputWithPast, Tuple] = self.model.forward(
116
- input_ids=input_ids,
117
- inputs_embeds=inputs_embeds,
118
- attention_mask=attention_mask,
119
- attention_bias=attention_bias,
120
- past_key_values=past_key_values,
121
- use_cache=use_cache,
122
- output_hidden_states=output_hidden_states,
123
- )
124
-
125
- last_hidden_state = base_output.last_hidden_state if return_dict else base_output[0]
126
-
127
- # Get logits.
128
- # shape: (batch_size, seq_len or 1, vocab_size)
129
- if self.config.weight_tying:
130
- logits = F.linear(last_hidden_state, self.model.transformer.wte.weight, None) # type: ignore
131
- else:
132
- logits = self.model.transformer.ff_out(last_hidden_state) # type: ignore
133
- if self.config.scale_logits:
134
- logits.mul_(1 / math.sqrt(self.config.d_model))
135
-
136
- loss = None
137
- if labels is not None:
138
- # Shift so that tokens < n predict n
139
- shift_logits = logits[..., :-1, :].contiguous()
140
- shift_labels = labels[..., 1:].contiguous()
141
- # Flatten the tokens
142
- loss_fct = torch.nn.CrossEntropyLoss()
143
- shift_logits = shift_logits.view(-1, self.config.embedding_size) # changed to self.config.embedding_size from self.config.vocab_size
144
- shift_labels = shift_labels.view(-1)
145
- # Enable model parallelism
146
- shift_labels = shift_labels.to(shift_logits.device)
147
- loss = loss_fct(shift_logits, shift_labels)
148
-
149
- if not return_dict:
150
- output = (logits,) + base_output[1:]
151
- return (loss,) + output if loss is not None else output
152
-
153
- assert isinstance(base_output, BaseModelOutputWithPast)
154
- return CausalLMOutputWithPast(
155
- loss=loss,
156
- logits=logits,
157
- past_key_values=base_output.past_key_values,
158
- hidden_states=base_output.hidden_states,
159
- attentions=base_output.attentions,
160
- )
161
-
162
- def prepare_inputs_for_generation(
163
- self, input_ids: torch.LongTensor, past_key_values: Optional[List[Tuple]] = None, **kwargs
164
- ):
165
- if past_key_values:
166
- # This is because we want the model to only process the last generated token.
167
- input_ids = input_ids[:, -1:]
168
- model_inputs = {"input_ids": input_ids, "past_key_values": past_key_values}
169
-
170
- if 'cache_position' in kwargs: kwargs.pop("cache_position")
171
- if past_key_values and ("input_embeds" in kwargs or "inputs_embeds" in kwargs): kwargs.pop("inputs_embeds")
172
- model_inputs.update(kwargs)
173
- # logger.warning("%s %s", kwargs.keys(), model_inputs.keys())
174
- # model_inputs["use_cache"] = kwargs.pop("use_cache", self.config.use_cache)
175
- return model_inputs
176
-
177
- @staticmethod
178
- def _reorder_cache(past_key_values, beam_idx):
179
- reordered_past = ()
180
- for layer_past in past_key_values:
181
- reordered_past += (
182
- tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
183
- )
184
- return reordered_past
185
-
186
- # Register the model so that it is available for transformer pipelines, auto-loading, etc.
187
- # AutoModelForCausalLM.register(OLMoConfig, OLMoForCausalLM)