-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodel.py
More file actions
1423 lines (1134 loc) · 55.2 KB
/
Copy pathmodel.py
File metadata and controls
1423 lines (1134 loc) · 55.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import json
import re
import numpy as np
from collections import deque
from typing import Optional, Tuple, List, Dict, Any, Union, Callable
import os
import logging
from datetime import datetime
# Set up logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("llm.log"),
logging.StreamHandler()
]
)
logger = logging.getLogger("TaskSolvingLLM")
#######################################################
# Base Model Architecture Components
#######################################################
class RotaryPositionalEmbedding(nn.Module):
"""Rotary Position Embedding implementation for improved positional encoding."""
def __init__(self, dim: int, max_seq_len: int = 8192):
super().__init__()
self.dim = dim
self.max_seq_len = max_seq_len
# Create frequencies for each dimension
freqs = 1.0 / (10000 ** (torch.arange(0, dim, 2).float() / dim))
positions = torch.arange(max_seq_len).float()
# Create sin/cos angle table (max_seq_len, dim/2)
freqs = torch.outer(positions, freqs)
# Create complex exponentials e^(i*theta) = cos(theta) + i*sin(theta)
self.cos_cached = torch.cos(freqs).view(1, max_seq_len, 1, dim // 2)
self.sin_cached = torch.sin(freqs).view(1, max_seq_len, 1, dim // 2)
def forward(self, x, seq_len: Optional[int] = None):
# x: (batch, seq_len, heads, dim)
seq_len = seq_len or x.shape[1]
# Get cached sin/cos values up to needed sequence length
cos = self.cos_cached[:, :seq_len, :, :].to(x.device)
sin = self.sin_cached[:, :seq_len, :, :].to(x.device)
# Split dimensions into even and odd indices
x_even = x[:, :, :, 0::2]
x_odd = x[:, :, :, 1::2]
# Apply rotation (complex multiplication)
# [x_even; x_odd] * [cos; sin] = [x_even*cos - x_odd*sin; x_even*sin + x_odd*cos]
x_rotated_even = x_even * cos - x_odd * sin
x_rotated_odd = x_even * sin + x_odd * cos
# Merge back together
x_rotated = torch.zeros_like(x)
x_rotated[:, :, :, 0::2] = x_rotated_even
x_rotated[:, :, :, 1::2] = x_rotated_odd
return x_rotated
class FlashAttention(nn.Module):
"""Optimized attention mechanism with support for KV caching."""
def __init__(self, dim: int, num_heads: int, dropout: float = 0.1):
super().__init__()
self.dim = dim
self.num_heads = num_heads
self.head_dim = dim // num_heads
self.scale = self.head_dim ** -0.5
self.q_proj = nn.Linear(dim, dim, bias=False)
self.k_proj = nn.Linear(dim, dim, bias=False)
self.v_proj = nn.Linear(dim, dim, bias=False)
self.out_proj = nn.Linear(dim, dim, bias=False)
self.dropout = nn.Dropout(dropout)
self.rotary_emb = RotaryPositionalEmbedding(self.head_dim)
def forward(
self,
x: torch.Tensor,
kv_cache: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
attention_mask: Optional[torch.Tensor] = None
):
batch_size, seq_len, _ = x.shape
# Project queries, keys, and values
q = self.q_proj(x).view(batch_size, seq_len, self.num_heads, self.head_dim)
k = self.k_proj(x).view(batch_size, seq_len, self.num_heads, self.head_dim)
v = self.v_proj(x).view(batch_size, seq_len, self.num_heads, self.head_dim)
# Apply RoPE positional encoding
q = self.rotary_emb(q, seq_len)
k = self.rotary_emb(k, seq_len)
# Handle KV cache for autoregressive decoding
if kv_cache is not None:
k_cache, v_cache = kv_cache
k = torch.cat([k_cache, k], dim=1)
v = torch.cat([v_cache, v], dim=1)
new_kv_cache = (k, v)
else:
new_kv_cache = (k, v)
# Get effective sequence length (accounting for cache)
effective_seq_len = k.size(1)
# Transpose for attention computation: (batch, heads, seq, dim)
q = q.transpose(1, 2)
k = k.transpose(1, 2)
v = v.transpose(1, 2)
# Compute attention weights
# (batch, heads, seq_q, dim) @ (batch, heads, dim, seq_k) = (batch, heads, seq_q, seq_k)
attn_weights = torch.matmul(q, k.transpose(-2, -1)) * self.scale
# Apply attention mask if provided
if attention_mask is not None:
attn_weights = attn_weights + attention_mask
# Compute softmax
attn_weights = F.softmax(attn_weights, dim=-1)
attn_weights = self.dropout(attn_weights)
# Compute weighted sum of values
# (batch, heads, seq_q, seq_k) @ (batch, heads, seq_k, dim) = (batch, heads, seq_q, dim)
attn_output = torch.matmul(attn_weights, v)
# Reshape and project output
attn_output = attn_output.transpose(1, 2).contiguous().view(batch_size, seq_len, self.dim)
output = self.out_proj(attn_output)
return output, new_kv_cache
class FeedForward(nn.Module):
"""Enhanced Feed-Forward layer with SwiGLU activation."""
def __init__(self, dim: int, hidden_dim: int, dropout: float = 0.1):
super().__init__()
self.w1 = nn.Linear(dim, hidden_dim, bias=False)
self.w2 = nn.Linear(hidden_dim, dim, bias=False)
self.w3 = nn.Linear(dim, hidden_dim, bias=False) # For SwiGLU activation
self.dropout = nn.Dropout(dropout)
def forward(self, x):
# SwiGLU activation: swish(x*W1) * (x*W3)
swish = self.w1(x) * torch.sigmoid(self.w1(x) * 1.0)
gate = self.w3(x)
x = swish * gate
x = self.dropout(x)
x = self.w2(x)
return x
class TransformerLayer(nn.Module):
"""Optimized transformer layer with pre-normalization."""
def __init__(self, dim: int, num_heads: int, ff_dim: int, dropout: float = 0.1):
super().__init__()
self.attn_norm = nn.LayerNorm(dim, eps=1e-5)
self.attn = FlashAttention(dim, num_heads, dropout)
self.ff_norm = nn.LayerNorm(dim, eps=1e-5)
self.ff = FeedForward(dim, ff_dim, dropout)
def forward(
self,
x: torch.Tensor,
kv_cache: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
attention_mask: Optional[torch.Tensor] = None
):
# Pre-normalization for attention
normed_x = self.attn_norm(x)
attn_output, new_kv_cache = self.attn(normed_x, kv_cache, attention_mask)
x = x + attn_output
# Pre-normalization for FF
normed_x = self.ff_norm(x)
ff_output = self.ff(normed_x)
x = x + ff_output
return x, new_kv_cache
class QuantizedLinear(nn.Module):
"""8-bit quantized linear layer for model efficiency."""
def __init__(self, in_features: int, out_features: int):
super().__init__()
self.in_features = in_features
self.out_features = out_features
# Create 8-bit quantized weights
self.weight = nn.Parameter(torch.zeros(out_features, in_features, dtype=torch.int8))
self.scale = nn.Parameter(torch.ones(out_features, 1, dtype=torch.float32))
# Initialization
nn_weight = torch.empty(out_features, in_features, dtype=torch.float32)
nn.init.kaiming_uniform_(nn_weight, a=math.sqrt(5))
# Quantize weights to int8
weight_scale = nn_weight.abs().max(dim=1, keepdim=True)[0] / 127.0
quantized_weight = (nn_weight / weight_scale).round().clamp(-127, 127).to(torch.int8)
self.weight.data.copy_(quantized_weight)
self.scale.data.copy_(weight_scale)
def forward(self, x):
# Dequantize weights to float32 for computation
float_weight = self.weight.float() * self.scale
return F.linear(x, float_weight)
#######################################################
# Memory and Cognitive Components
#######################################################
class MemoryItem:
"""Individual memory item with metadata."""
def __init__(
self,
memory_type: str,
content: str,
embedding: Optional[torch.Tensor] = None,
metadata: Optional[Dict[str, Any]] = None
):
self.type = memory_type
self.content = content
self.embedding = embedding.detach().cpu() if embedding is not None else None
self.timestamp = datetime.now().isoformat()
self.metadata = metadata or {}
def to_dict(self) -> Dict[str, Any]:
"""Convert memory to dictionary for storage."""
return {
"type": self.type,
"content": self.content,
"timestamp": self.timestamp,
"metadata": self.metadata,
# Embedding is handled separately
}
@classmethod
def from_dict(cls, data: Dict[str, Any], embedding: Optional[torch.Tensor] = None) -> "MemoryItem":
"""Create memory item from dictionary."""
memory = cls(
memory_type=data["type"],
content=data["content"],
embedding=embedding,
metadata=data.get("metadata", {})
)
memory.timestamp = data.get("timestamp", datetime.now().isoformat())
return memory
class MemoryStore:
"""Enhanced long-term memory with persistence and sophisticated retrieval."""
def __init__(self, capacity: int = 10000, storage_path: Optional[str] = None):
self.capacity = capacity
self.memories = deque(maxlen=capacity)
self.storage_path = storage_path
# Load memories if storage path is provided
if storage_path and os.path.exists(storage_path):
self.load_memories()
def add(
self,
memory_type: str,
content: str,
embedding: Optional[torch.Tensor] = None,
metadata: Optional[Dict[str, Any]] = None
) -> MemoryItem:
"""Add an item to memory with timestamp and metadata."""
memory = MemoryItem(memory_type, content, embedding, metadata)
self.memories.append(memory)
# Save to disk if storage path exists
if self.storage_path:
self.save_memories()
return memory
def save_memories(self):
"""Save memories to disk."""
if not self.storage_path:
return
os.makedirs(os.path.dirname(self.storage_path), exist_ok=True)
# Save memory text content and metadata
memory_data = [memory.to_dict() for memory in self.memories]
with open(self.storage_path, 'w') as f:
json.dump(memory_data, f)
# Save embeddings separately
if any(memory.embedding is not None for memory in self.memories):
embeddings = [
memory.embedding.numpy() if memory.embedding is not None
else np.zeros((1, 1)) # Placeholder for memories without embeddings
for memory in self.memories
]
embedding_path = self.storage_path.replace(".json", "_embeddings.npy")
np.save(embedding_path, embeddings)
def load_memories(self):
"""Load memories from disk."""
if not os.path.exists(self.storage_path):
return
# Load memory content and metadata
with open(self.storage_path, 'r') as f:
memory_data = json.load(f)
# Load embeddings if they exist
embedding_path = self.storage_path.replace(".json", "_embeddings.npy")
embeddings = None
if os.path.exists(embedding_path):
try:
embeddings_array = np.load(embedding_path, allow_pickle=True)
embeddings = [
torch.tensor(emb) if emb.size > 1 else None
for emb in embeddings_array
]
except Exception as e:
logger.error(f"Error loading embeddings: {e}")
# Recreate memories
self.memories = deque(maxlen=self.capacity)
for i, data in enumerate(memory_data):
emb = embeddings[i] if embeddings and i < len(embeddings) else None
memory = MemoryItem.from_dict(data, emb)
self.memories.append(memory)
def search(
self,
query_embedding: Optional[torch.Tensor] = None,
query_text: Optional[str] = None,
memory_type: Optional[str] = None,
k: int = 5,
threshold: float = 0.6
) -> List[MemoryItem]:
"""Enhanced memory search with filtering options."""
if len(self.memories) == 0:
return []
# First, filter by memory type if specified
filtered_memories = list(self.memories)
if memory_type:
filtered_memories = [m for m in filtered_memories if m.type == memory_type]
if not filtered_memories:
return []
# Search by vector similarity if embedding provided
if query_embedding is not None:
memories_with_embeddings = [m for m in filtered_memories if m.embedding is not None]
if not memories_with_embeddings:
return self.get_recent(k, memory_type)
# Compute similarities
embeddings = torch.stack([m.embedding for m in memories_with_embeddings])
similarities = F.cosine_similarity(query_embedding.unsqueeze(0), embeddings)
# Filter by threshold and get top-k
mask = similarities >= threshold
if not mask.any():
return self.get_recent(k, memory_type)
filtered_similarities = similarities[mask]
filtered_indices = torch.nonzero(mask).squeeze(-1)
if len(filtered_similarities) <= k:
selected_indices = filtered_indices
else:
_, top_indices = torch.topk(filtered_similarities, k)
selected_indices = filtered_indices[top_indices]
return [memories_with_embeddings[i] for i in selected_indices.tolist()]
# Search by text if query provided
elif query_text:
results = []
# Tokenize query for better matching
query_tokens = set(query_text.lower().split())
# Score each memory based on token overlap
scored_memories = []
for memory in filtered_memories:
memory_tokens = set(memory.content.lower().split())
overlap = len(query_tokens & memory_tokens) / max(1, len(query_tokens))
if overlap > 0:
scored_memories.append((memory, overlap))
# Sort by score and take top k
scored_memories.sort(key=lambda x: x[1], reverse=True)
results = [memory for memory, score in scored_memories[:k] if score >= threshold]
return results if results else self.get_recent(k, memory_type)
# Default to recent memories
return self.get_recent(k, memory_type)
def get_recent(self, k: int = 5, memory_type: Optional[str] = None) -> List[MemoryItem]:
"""Get the k most recent memories, optionally filtered by type."""
if memory_type:
filtered = [m for m in self.memories if m.type == memory_type]
return list(reversed(filtered))[:k]
else:
return list(reversed(list(self.memories)))[:k]
def clear(self):
"""Clear all memories."""
self.memories.clear()
# Remove saved files if they exist
if self.storage_path and os.path.exists(self.storage_path):
try:
os.remove(self.storage_path)
embedding_path = self.storage_path.replace(".json", "_embeddings.npy")
if os.path.exists(embedding_path):
os.remove(embedding_path)
except Exception as e:
logger.error(f"Error removing memory files: {e}")
class WorkingMemory:
"""Enhanced short-term memory for the current thinking process."""
def __init__(self, max_size: int = 15):
self.thoughts = []
self.max_size = max_size
self.context = {} # Current context information
self.scratch_pad = "" # Area for temporary calculations
def add_thought(self, thought: str, thought_type: str = "thinking"):
"""Add a thought to working memory with type."""
self.thoughts.append({
"content": thought,
"type": thought_type,
"timestamp": datetime.now().isoformat()
})
if len(self.thoughts) > self.max_size:
self.thoughts.pop(0)
def update_context(self, key: str, value: Any):
"""Update context information."""
self.context[key] = value
def update_scratch_pad(self, content: str):
"""Update or replace scratch pad content."""
self.scratch_pad = content
def append_to_scratch_pad(self, content: str):
"""Append content to scratch pad."""
self.scratch_pad += content
def clear_scratch_pad(self):
"""Clear scratch pad content."""
self.scratch_pad = ""
def get_formatted(self) -> str:
"""Get formatted working memory for prompt construction."""
formatted = "Previous thoughts:\n"
for i, thought in enumerate(self.thoughts, 1):
formatted += f"{i}. [{thought['type']}] {thought['content']}\n"
if self.context:
formatted += "\nContext:\n"
for key, value in self.context.items():
formatted += f"- {key}: {value}\n"
if self.scratch_pad:
formatted += "\nScratch Pad (for calculations):\n"
formatted += self.scratch_pad + "\n"
return formatted
def clear(self):
"""Clear working memory."""
self.thoughts = []
self.context = {}
self.scratch_pad = ""
#######################################################
# Specialized Task Solving Components
#######################################################
class TaskParser:
"""Parse and understand different types of user tasks."""
TASK_TYPES = {
"question_answering": [
r"(?:what|who|when|where|why|how|can you|could you tell|explain)",
r"(?:tell me about|explain|describe|what is|who is|define)",
],
"code_generation": [
r"(?:write|create|generate|implement|code|program|function|class)",
r"(?:in (?:python|javascript|java|c\+\+|ruby|go|rust|php))",
],
"math_problem": [
r"(?:calculate|compute|solve|find|evaluate|what is|determine)",
r"(?:\d+\s*[\+\-\*\/\^\(\)]+|\bequation\b|\balgebra\b|\bintegral\b)",
],
"creative_writing": [
r"(?:write|draft|create|compose) (?:a|an|the) (?:story|poem|essay|letter|blog|article)",
r"(?:creative|fiction|narrative|imaginative)",
],
"summarization": [
r"(?:summarize|summary|tldr|brief|overview|recap)",
r"(?:condense|shorten|simplify)",
],
"translation": [
r"(?:translate|convert|change) (?:to|into|from) (?:english|spanish|french|german|chinese|russian|japanese|korean|italian|portuguese|arabic)",
r"(?:translation|translator)",
],
"reasoning": [
r"(?:reason|think through|analyze|evaluate|assess|critique)",
r"(?:logical|critical|careful|step by step)",
],
}
@classmethod
def classify_task(cls, query: str) -> str:
"""Classify the task type based on the query."""
query = query.lower()
# Check each task type
for task_type, patterns in cls.TASK_TYPES.items():
for pattern in patterns:
if re.search(pattern, query):
return task_type
# Default to question answering
return "question_answering"
@classmethod
def extract_constraints(cls, query: str) -> Dict[str, Any]:
"""Extract constraints and parameters from the query."""
constraints = {}
# Look for length constraints
length_match = re.search(r"(?:in|within|at most|at least|about) (\d+) (?:words|sentences|paragraphs|lines)", query.lower())
if length_match:
constraints["length"] = int(length_match.group(1))
constraints["length_unit"] = re.search(r"(?:words|sentences|paragraphs|lines)", length_match.group(0)).group(0)
# Look for format constraints
format_patterns = [
(r"as (?:a|an) (list|table|diagram|chart|graph|json|xml|markdown|outline)", "format"),
(r"in (?:a|an) (formal|informal|academic|professional|casual|conversational) (?:style|tone|manner)", "tone"),
(r"for (?:a|an) (beginner|intermediate|advanced|expert|technical|non-technical|general) audience", "audience"),
]
for pattern, key in format_patterns:
match = re.search(pattern, query.lower())
if match:
constraints[key] = match.group(1)
# For code generation tasks, extract language
if cls.classify_task(query) == "code_generation":
lang_match = re.search(r"in (python|javascript|java|c\+\+|ruby|go|rust|php|html|css|sql|bash|typescript)", query.lower())
if lang_match:
constraints["language"] = lang_match.group(1)
return constraints
class ReasoningEngine:
"""Enhanced engine for step-by-step reasoning and reflection."""
def __init__(self, model, tokenizer, max_steps: int = 8):
self.model = model
self.tokenizer = tokenizer
self.max_steps = max_steps
self.working_memory = WorkingMemory()
self.verification_enabled = True
def think(self, query: str, context: str = "", max_tokens_per_step: int = 150) -> Dict:
"""Perform multi-step thinking with different reasoning strategies."""
self.working_memory.clear()
# Determine reasoning strategy based on task
task_type = TaskParser.classify_task(query)
if task_type == "math_problem":
return self._mathematical_reasoning(query, context, max_tokens_per_step)
elif task_type == "code_generation":
return self._code_reasoning(query, context, max_tokens_per_step)
elif task_type in ["reasoning", "question_answering"]:
return self._analytical_reasoning(query, context, max_tokens_per_step)
else:
# Default reasoning approach
return self._default_reasoning(query, context, max_tokens_per_step)
def _build_prompt(self, query: str, context: str, instruction: str) -> str:
"""Build a prompt with query, context, and working memory."""
prompt = f"Question: {query}\n\n"
if context:
prompt += f"Context:\n{context}\n\n"
prompt += f"{self.working_memory.get_formatted()}\n"
prompt += f"{instruction}\n"
return prompt
def _generate_thought(self, prompt: str, max_tokens: int) -> str:
"""Generate a thought using the model."""
device = next(self.model.parameters()).device
input_ids = self.tokenizer.encode(prompt, return_tensors="pt").to(device)
with torch.inference_mode():
output_ids = self.model.generate(
input_ids=input_ids,
max_new_tokens=max_tokens,
temperature=0.7,
do_sample=True,
)
return self.tokenizer.decode(
output_ids[0, input_ids.shape[1]:],
skip_special_tokens=True
).strip()
def _default_reasoning(self, query: str, context: str, max_tokens_per_step: int) -> Dict:
"""Standard reasoning approach for general questions."""
self.working_memory.add_thought(f"Initial question: {query}", "question")
all_thoughts = []
current_step = 1
# Multi-step thinking loop
for _ in range(self.max_steps):
# Generate next thought
instruction = f"Thinking step {current_step}: I'll reason through this carefully..."
prompt = self._build_prompt(query, context, instruction)
thought = self._generate_thought(prompt, max_tokens_per_step)
# Save the thought
step_thought = f"Step {current_step}: {thought}"
all_thoughts.append(step_thought)
self.working_memory.add_thought(thought, "thinking")
# Check if we have a conclusion
if any(phrase in thought.lower() for phrase in
["therefore", "conclusion", "answer is", "in summary", "finally"]):
break
current_step += 1
# Generate final answer if needed
if not any(phrase in " ".join(all_thoughts).lower() for phrase in
["therefore", "conclusion", "answer is", "in summary", "finally"]):
instruction = "Based on my analysis above, my final answer is:"
prompt = self._build_prompt(query, context, instruction)
final_answer = self._generate_thought(prompt, max_tokens_per_step)
all_thoughts.append(f"Conclusion: {final_answer}")
self.working_memory.add_thought(f"Final answer: {final_answer}", "conclusion")
return {
"steps": all_thoughts,
"final_answer": all_thoughts[-1],
"working_memory": self.working_memory.get_formatted()
}
def _mathematical_reasoning(self, query: str, context: str, max_tokens_per_step: int) -> Dict:
"""Specialized reasoning for mathematical problems."""
self.working_memory.add_thought(f"Mathematical problem: {query}", "question")
all_thoughts = []
current_step = 1
# First, understand the problem
instruction = "Let me understand this math problem by identifying the key variables and what I need to find:"
prompt = self._build_prompt(query, context, instruction)
understanding = self._generate_thought(prompt, max_tokens_per_step)
all_thoughts.append(f"Understanding: {understanding}")
self.working_memory.add_thought(understanding, "understanding")
# Multi-step solving
for _ in range(self.max_steps - 1): # -1 because we used one step for understanding
# Determine the next step based on current progress
if current_step == 1:
instruction = "Let me start solving this step-by-step:"
else:
instruction = f"Step {current_step} of the solution:"
prompt = self._build_prompt(query, context, instruction)
thought = self._generate_thought(prompt, max_tokens_per_step)
step_thought = f"Step {current_step}: {thought}"
all_thoughts.append(step_thought)
self.working_memory.add_thought(thought, "calculation")
# Check if we've reached the solution
if any(phrase in thought.lower() for phrase in
["therefore", "thus", "so", "answer is", "result is", "solution is", "=", "equals"]):
break
current_step += 1
# Verify the solution if enabled
if self.verification_enabled:
instruction = "Let me verify my solution by checking my work:"
prompt = self._build_prompt(query, context, instruction)
verification = self._generate_thought(prompt, max_tokens_per_step)
all_thoughts.append(f"Verification: {verification}")
self.working_memory.add_thought(verification, "verification")
# Final answer
instruction = "Based on my calculations, the final answer is:"
prompt = self._build_prompt(query, context, instruction)
final_answer = self._generate_thought(prompt, max_tokens_per_step)
all_thoughts.append(f"Answer: {final_answer}")
self.working_memory.add_thought(final_answer, "answer")
return {
"steps": all_thoughts,
"final_answer": final_answer,
"working_memory": self.working_memory.get_formatted()
}
def _code_reasoning(self, query: str, context: str, max_tokens_per_step: int) -> Dict:
"""Specialized reasoning for code generation tasks."""
self.working_memory.add_thought(f"Code task: {query}", "question")
all_thoughts = []
# Understand requirements
instruction = "Let me analyze the requirements for this code task:"
prompt = self._build_prompt(query, context, instruction)
requirements = self._generate_thought(prompt, max_tokens_per_step)
all_thoughts.append(f"Requirements: {requirements}")
self.working_memory.add_thought(requirements, "requirements")
# Design approach
instruction = "Let me design a solution approach with pseudocode or high-level description:"
prompt = self._build_prompt(query, context, instruction)
design = self._generate_thought(prompt, max_tokens_per_step)
all_thoughts.append(f"Design: {design}")
self.working_memory.add_thought(design, "design")
# Generate code
constraints = TaskParser.extract_constraints(query)
language = constraints.get("language", "python")
instruction = f"Now I'll implement the solution in {language}:"
prompt = self._build_prompt(query, context, instruction)
# Use more tokens for code generation
code = self._generate_thought(prompt, max_tokens_per_step * 2)
all_thoughts.append(f"Implementation: {code}")
self.working_memory.add_thought(code, "implementation")
# Test cases or example usage
instruction = "Let me provide test cases or example usage to demonstrate the code:"
prompt = self._build_prompt(query, context, instruction)
testing = self._generate_thought(prompt, max_tokens_per_step)
all_thoughts.append(f"Testing: {testing}")
self.working_memory.add_thought(testing, "testing")
# Format final solution
instruction = "Let me present the complete solution with explanation:"
prompt = self._build_prompt(query, context, instruction)
final_solution = self._generate_thought(prompt, max_tokens_per_step * 2)
all_thoughts.append(f"Solution: {final_solution}")
self.working_memory.add_thought(final_solution, "solution")
return {
"steps": all_thoughts,
"final_answer": final_solution,
"working_memory": self.working_memory.get_formatted()
}
def _analytical_reasoning(self, query: str, context: str, max_tokens_per_step: int) -> Dict:
"""Critical analytical reasoning for complex questions."""
self.working_memory.add_thought(f"Analysis question: {query}", "question")
all_thoughts = []
# Define perspectives/angles to consider
perspectives = [
"Let me first consider the key facts and definitions:",
"Let me analyze the underlying assumptions:",
"Let me consider different viewpoints and perspectives:",
"Let me identify potential logical fallacies or biases:",
"Let me examine the evidence and support for each position:",
"Let me synthesize the information and draw connections:"
]
# Generate thoughts from different perspectives
for i, perspective in enumerate(perspectives[:min(len(perspectives), self.max_steps - 1)]):
prompt = self._build_prompt(query, context, perspective)
thought = self._generate_thought(prompt, max_tokens_per_step)
angle = perspective.replace("Let me ", "").replace(":", "")
all_thoughts.append(f"{angle}: {thought}")
self.working_memory.add_thought(thought, f"perspective_{i+1}")
# Generate conclusion
instruction = "Based on my comprehensive analysis, I can now conclude:"
prompt = self._build_prompt(query, context, instruction)
conclusion = self._generate_thought(prompt, max_tokens_per_step)
all_thoughts.append(f"Conclusion: {conclusion}")
self.working_memory.add_thought(conclusion, "conclusion")
return {
"steps": all_thoughts,
"final_answer": conclusion,
"working_memory": self.working_memory.get_formatted()
}
#######################################################
# Advanced Tokenization
#######################################################
class AdvancedTokenizer:
"""Enhanced tokenizer with better handling of text structures."""
def __init__(self, vocab_size=50257, unk_token="<unk>", pad_token="<pad>", eos_token="<eos>"):
self.vocab_size = vocab_size
# Special tokens
self.unk_token = unk_token
self.pad_token = pad_token
self.eos_token = eos_token
# Token IDs
self.unk_token_id = 0
self.pad_token_id = 1
self.eos_token_id = 2
# Initialize basic vocabulary (simplified)
self._init_vocab()
def _init_vocab(self):
"""Initialize the vocabulary with basic tokens."""
# Special tokens
self.token_to_id = {
self.unk_token: self.unk_token_id,
self.pad_token: self.pad_token_id,
self.eos_token: self.eos_token_id,
}
# Simple vocab - would be replaced with real tokenization in production
# Here we just create a basic character-level tokenization for demonstration
for i, c in enumerate(list(" abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,!?;:\"'()[]{}-_+=*/\\<>@#$%^&|~`"), 3):
self.token_to_id[c] = i
# Words for common programming languages and concepts (simplified)
common_words = ["function", "class", "def", "var", "let", "const", "import", "from", "return",
"if", "else", "for", "while", "in", "of", "try", "except", "finally", "with",
"async", "await", "python", "javascript", "java", "c++", "algorithm", "data",
"analysis", "model", "train", "predict", "tensor", "matrix", "vector"]
word_id = max(self.token_to_id.values()) + 1
for word in common_words:
if word not in self.token_to_id:
self.token_to_id[word] = word_id
word_id += 1
# Create the reverse mapping
self.id_to_token = {v: k for k, v in self.token_to_id.items()}
def encode(self, text: str, return_tensors: Optional[str] = None) -> Union[List[int], torch.Tensor]:
"""Convert text to token IDs using a simple approach."""
if not text:
token_ids = [self.pad_token_id]
else:
# Simple tokenization (character-level with some basic words)
# In a real tokenizer, this would use BPE, WordPiece, or other algorithm
token_ids = []
i = 0
while i < len(text):
# Try to match longer words first
matched = False
for word_len in range(20, 0, -1): # Try words up to 20 chars
if i + word_len <= len(text):
word = text[i:i+word_len]
if word in self.token_to_id:
token_ids.append(self.token_to_id[word])
i += word_len
matched = True
break
# If no word match, add character
if not matched:
char = text[i]
token_ids.append(self.token_to_id.get(char, self.unk_token_id))
i += 1
# Add EOS token
token_ids.append(self.eos_token_id)
# Return as tensor if requested
if return_tensors == "pt":
return torch.tensor([token_ids], dtype=torch.long)
return token_ids
def decode(self, ids: Union[List[int], torch.Tensor], skip_special_tokens: bool = False) -> str:
"""Convert token IDs back to text."""
if isinstance(ids, torch.Tensor):
ids = ids.tolist()
if skip_special_tokens:
ids = [id for id in ids if id not in [self.pad_token_id, self.eos_token_id]]
return "".join(self.id_to_token.get(id, self.unk_token) for id in ids)
def batch_encode(self, texts: List[str], padding: bool = True, return_tensors: Optional[str] = None) -> Dict:
"""Encode a batch of texts."""
encoded = [self.encode(text) for text in texts]
# Add padding if requested
if padding:
max_len = max(len(ids) for ids in encoded)
encoded = [ids + [self.pad_token_id] * (max_len - len(ids)) for ids in encoded]
# Create attention masks
attention_masks = [[1] * len(ids) if id != self.pad_token_id else 0 for ids in encoded for id in ids]
# Return as tensors if requested
if return_tensors == "pt":
return {
"input_ids": torch.tensor(encoded, dtype=torch.long),
"attention_mask": torch.tensor(attention_masks, dtype=torch.long)
}
return {
"input_ids": encoded,
"attention_mask": attention_masks
}
#######################################################
# Main TaskSolvingLLM Class
#######################################################
class TaskSolvingLLM(nn.Module):
"""Enhanced language model with task understanding and solving capabilities."""
def __init__(
self,
vocab_size: int,
dim: int = 768,
num_layers: int = 12,
num_heads: int = 12,
max_seq_len: int = 8192,
dropout: float = 0.1,
use_quantization: bool = True,
memory_capacity: int = 10000,
memory_path: Optional[str] = None,
tokenizer = None,
):
super().__init__()
# Architecture parameters
self.dim = dim
self.vocab_size = vocab_size
self.max_seq_len = max_seq_len
self.use_quantization = use_quantization
# Initialize tokenizer
self.tokenizer = tokenizer if tokenizer else AdvancedTokenizer(vocab_size)