tommytracx commited on
Commit
c0471e1
·
verified ·
1 Parent(s): 9104d9c

Add modeling_ollama.py

Browse files
Files changed (1) hide show
  1. modeling_ollama.py +246 -0
modeling_ollama.py ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ NeuralQuantum Ollama Model Implementation for Hugging Face Transformers
3
+ """
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+ from transformers import PreTrainedModel
8
+ from transformers.modeling_outputs import CausalLMOutputWithPast
9
+ from .configuration_ollama import NeuralQuantumOllamaConfig
10
+
11
+
12
+ class QuantumOllamaLayer(nn.Module):
13
+ """Quantum-inspired layer optimized for Ollama"""
14
+
15
+ def __init__(self, config):
16
+ super().__init__()
17
+ self.config = config
18
+ self.quantum_circuit_depth = config.quantum_circuit_depth
19
+ self.hidden_size = config.hidden_size
20
+
21
+ # Quantum-inspired parameters optimized for Ollama
22
+ self.quantum_weights = nn.Parameter(torch.randn(self.quantum_circuit_depth, self.hidden_size, self.hidden_size))
23
+ self.quantum_bias = nn.Parameter(torch.randn(self.hidden_size))
24
+ self.quantum_scale = nn.Parameter(torch.ones(self.hidden_size))
25
+
26
+ def forward(self, hidden_states):
27
+ # Simulate quantum circuit operations optimized for Ollama
28
+ for i in range(self.quantum_circuit_depth):
29
+ # Apply quantum-inspired transformation with scaling
30
+ hidden_states = torch.matmul(hidden_states, self.quantum_weights[i])
31
+ hidden_states = torch.tanh(hidden_states) # Non-linear activation
32
+ hidden_states = hidden_states * self.quantum_scale
33
+
34
+ return hidden_states + self.quantum_bias
35
+
36
+
37
+ class NeuralQuantumOllamaAttention(nn.Module):
38
+ """Quantum-enhanced attention mechanism optimized for Ollama"""
39
+
40
+ def __init__(self, config):
41
+ super().__init__()
42
+ self.config = config
43
+ self.num_attention_heads = config.num_attention_heads
44
+ self.hidden_size = config.hidden_size
45
+ self.head_dim = self.hidden_size // self.num_attention_heads
46
+
47
+ self.query = nn.Linear(self.hidden_size, self.hidden_size)
48
+ self.key = nn.Linear(self.hidden_size, self.hidden_size)
49
+ self.value = nn.Linear(self.hidden_size, self.hidden_size)
50
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
51
+
52
+ # Quantum enhancement layer optimized for Ollama
53
+ self.quantum_layer = QuantumOllamaLayer(config)
54
+
55
+ def forward(self, hidden_states, attention_mask=None):
56
+ batch_size, seq_len, hidden_size = hidden_states.size()
57
+
58
+ # Apply quantum enhancement
59
+ quantum_enhanced = self.quantum_layer(hidden_states)
60
+
61
+ # Standard attention computation
62
+ query = self.query(quantum_enhanced)
63
+ key = self.key(quantum_enhanced)
64
+ value = self.value(quantum_enhanced)
65
+
66
+ # Reshape for multi-head attention
67
+ query = query.view(batch_size, seq_len, self.num_attention_heads, self.head_dim).transpose(1, 2)
68
+ key = key.view(batch_size, seq_len, self.num_attention_heads, self.head_dim).transpose(1, 2)
69
+ value = value.view(batch_size, seq_len, self.num_attention_heads, self.head_dim).transpose(1, 2)
70
+
71
+ # Compute attention scores
72
+ attention_scores = torch.matmul(query, key.transpose(-2, -1)) / (self.head_dim ** 0.5)
73
+
74
+ if attention_mask is not None:
75
+ attention_scores = attention_scores.masked_fill(attention_mask == 0, -1e9)
76
+
77
+ attention_probs = torch.softmax(attention_scores, dim=-1)
78
+ attention_probs = self.dropout(attention_probs)
79
+
80
+ # Apply attention to values
81
+ context = torch.matmul(attention_probs, value)
82
+ context = context.transpose(1, 2).contiguous().view(batch_size, seq_len, hidden_size)
83
+
84
+ return context
85
+
86
+
87
+ class NeuralQuantumOllamaBlock(nn.Module):
88
+ """NeuralQuantum Ollama transformer block"""
89
+
90
+ def __init__(self, config):
91
+ super().__init__()
92
+ self.config = config
93
+ self.attention = NeuralQuantumOllamaAttention(config)
94
+ self.ln_1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
95
+ self.mlp = nn.Sequential(
96
+ nn.Linear(config.hidden_size, config.intermediate_size),
97
+ nn.GELU(),
98
+ nn.Linear(config.intermediate_size, config.hidden_size),
99
+ nn.Dropout(config.hidden_dropout_prob)
100
+ )
101
+ self.ln_2 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
102
+
103
+ def forward(self, hidden_states, attention_mask=None):
104
+ # Self-attention with residual connection
105
+ attn_output = self.attention(hidden_states, attention_mask)
106
+ hidden_states = self.ln_1(hidden_states + attn_output)
107
+
108
+ # MLP with residual connection
109
+ mlp_output = self.mlp(hidden_states)
110
+ hidden_states = self.ln_2(hidden_states + mlp_output)
111
+
112
+ return hidden_states
113
+
114
+
115
+ class NeuralQuantumOllamaForCausalLM(PreTrainedModel):
116
+ """NeuralQuantum Ollama model for causal language modeling"""
117
+
118
+ config_class = NeuralQuantumOllamaConfig
119
+
120
+ def __init__(self, config):
121
+ super().__init__(config)
122
+ self.config = config
123
+
124
+ # Embeddings
125
+ self.wte = nn.Embedding(config.vocab_size, config.hidden_size)
126
+ self.wpe = nn.Embedding(config.max_position_embeddings, config.hidden_size)
127
+ self.drop = nn.Dropout(config.hidden_dropout_prob)
128
+
129
+ # Transformer blocks
130
+ self.h = nn.ModuleList([
131
+ NeuralQuantumOllamaBlock(config) for _ in range(config.num_hidden_layers)
132
+ ])
133
+
134
+ # Output layer
135
+ self.ln_f = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
136
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
137
+
138
+ # Initialize weights
139
+ self.init_weights()
140
+
141
+ def get_input_embeddings(self):
142
+ return self.wte
143
+
144
+ def set_input_embeddings(self, new_embeddings):
145
+ self.wte = new_embeddings
146
+
147
+ def get_output_embeddings(self):
148
+ return self.lm_head
149
+
150
+ def set_output_embeddings(self, new_embeddings):
151
+ self.lm_head = new_embeddings
152
+
153
+ def forward(
154
+ self,
155
+ input_ids=None,
156
+ attention_mask=None,
157
+ position_ids=None,
158
+ past_key_values=None,
159
+ use_cache=None,
160
+ output_attentions=None,
161
+ output_hidden_states=None,
162
+ return_dict=None,
163
+ labels=None,
164
+ ):
165
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
166
+
167
+ batch_size, seq_len = input_ids.size()
168
+
169
+ # Position embeddings
170
+ if position_ids is None:
171
+ position_ids = torch.arange(0, seq_len, dtype=torch.long, device=input_ids.device)
172
+ position_ids = position_ids.unsqueeze(0).expand(batch_size, -1)
173
+
174
+ # Input embeddings
175
+ inputs_embeds = self.wte(input_ids)
176
+ position_embeds = self.wpe(position_ids)
177
+ hidden_states = inputs_embeds + position_embeds
178
+ hidden_states = self.drop(hidden_states)
179
+
180
+ # Transformer blocks
181
+ for i, block in enumerate(self.h):
182
+ hidden_states = block(hidden_states, attention_mask)
183
+
184
+ # Final layer norm
185
+ hidden_states = self.ln_f(hidden_states)
186
+
187
+ # Language modeling head
188
+ logits = self.lm_head(hidden_states)
189
+
190
+ loss = None
191
+ if labels is not None:
192
+ # Shift so that tokens < n predict n
193
+ shift_logits = logits[..., :-1, :].contiguous()
194
+ shift_labels = labels[..., 1:].contiguous()
195
+
196
+ # Flatten the tokens
197
+ loss_fct = nn.CrossEntropyLoss()
198
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
199
+
200
+ if not return_dict:
201
+ output = (logits,) + (None,) * 6
202
+ return ((loss,) + output) if loss is not None else output
203
+
204
+ return CausalLMOutputWithPast(
205
+ loss=loss,
206
+ logits=logits,
207
+ past_key_values=None,
208
+ hidden_states=None,
209
+ attentions=None,
210
+ )
211
+
212
+ def generate(self, input_ids, max_length=50, temperature=0.7, top_p=0.9, top_k=40, do_sample=True, **kwargs):
213
+ """Generate text using Ollama-optimized parameters"""
214
+ self.eval()
215
+
216
+ with torch.no_grad():
217
+ for _ in range(max_length - input_ids.size(1)):
218
+ # Get logits for the last token
219
+ outputs = self.forward(input_ids)
220
+ logits = outputs.logits[:, -1, :] / temperature
221
+
222
+ if do_sample:
223
+ # Apply top-k filtering
224
+ if top_k > 0:
225
+ top_k_logits, top_k_indices = torch.topk(logits, top_k)
226
+ logits = torch.full_like(logits, -float('inf'))
227
+ logits.scatter_(1, top_k_indices, top_k_logits)
228
+
229
+ # Apply top-p filtering
230
+ if top_p < 1.0:
231
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True)
232
+ cumulative_probs = torch.cumsum(torch.softmax(sorted_logits, dim=-1), dim=-1)
233
+ sorted_indices_to_remove = cumulative_probs > top_p
234
+ sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
235
+ sorted_indices_to_remove[..., 0] = 0
236
+ indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove)
237
+ logits[indices_to_remove] = -float('inf')
238
+
239
+ probs = torch.softmax(logits, dim=-1)
240
+ next_token = torch.multinomial(probs, 1)
241
+ else:
242
+ next_token = torch.argmax(logits, dim=-1, keepdim=True)
243
+
244
+ input_ids = torch.cat([input_ids, next_token], dim=1)
245
+
246
+ return input_ids