RobbiePasquale commited on
Commit
5c18e4c
1 Parent(s): 5370d9f

Create lihtbulb_custom

Browse files
Files changed (1) hide show
  1. lihtbulb_custom +2254 -0
lihtbulb_custom ADDED
@@ -0,0 +1,2254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import math
3
+ import os
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+ import torch.optim as optim
8
+ from torch.utils.data import DataLoader
9
+ import copy
10
+ from torch.optim.lr_scheduler import CosineAnnealingLR
11
+ from torch.cuda.amp import autocast, GradScaler
12
+ from datasets import load_dataset
13
+ from transformers import AutoTokenizer
14
+ from typing import List, Tuple
15
+ import sys
16
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
17
+
18
+ def parse_args():
19
+ parser = argparse.ArgumentParser(description='Train or Inference with World Model and Tree of Thought.')
20
+ parser.add_argument('--model_name', type=str, default='gpt2', help='Pretrained model name or path')
21
+
22
+ parser.add_argument('--dataset_name', type=str, default='wikitext', help='Dataset name from HuggingFace Datasets')
23
+ parser.add_argument('--dataset_config', type=str, default='wikitext-2-raw-v1', help='Dataset configuration name')
24
+ parser.add_argument('--batch_size', type=int, default=4, help='Batch size')
25
+ parser.add_argument('--num_epochs', type=int, default=3, help='Number of epochs')
26
+ parser.add_argument('--max_length', type=int, default=128, help='Maximum sequence length')
27
+ parser.add_argument('--mcts_iterations', type=int, default=3, help='Number of MCTS Iterations')
28
+ parser.add_argument('--mcts_exploration_constant', type=float, default=1.414, help='Exploration constant for MCTS')
29
+ parser.add_argument('--accumulation_steps', type=int, default=4, help='Gradient accumulation steps')
30
+ parser.add_argument('--learning_rate', type=float, default=1e-4, help='Learning rate')
31
+ parser.add_argument('--weight_decay', type=float, default=1e-2, help='Weight decay')
32
+ parser.add_argument('--alpha', type=float, default=0.1, help='Entropy regularization weight')
33
+ parser.add_argument('--beta', type=float, default=0.1, help='Variance regularization weight')
34
+ parser.add_argument('--max_grad_norm', type=float, default=1.0, help='Max gradient norm for clipping')
35
+ parser.add_argument('--save_dir', type=str, default='./models', help='Directory to save the models')
36
+ parser.add_argument('--temperature', type=float, default=1.0, help='Temperature parameter for entropy and variance')
37
+ parser.add_argument('--mode', type=str, choices=['train', 'inference'], default='train', help='Mode: train or inference')
38
+ parser.add_argument('--inference_mode', type=str, choices=['world_model', 'without_world_model', 'world_model_tree_of_thought'], default='world_model_tree_of_thought', help='Inference mode')
39
+ parser.add_argument('--query', type=str, default='', help='Input query for inference')
40
+ parser.add_argument('--train_mode', type=str, choices=['world_model', 'language_model'], default='language_model', help='Train world model or language model only')
41
+ parser.add_argument('--beam_size', type=int, default=5, help='Beam size for beam search')
42
+ parser.add_argument('--n_tokens_predict', type=int, default=3, help='Number of tokens to predict at each step')
43
+ parser.add_argument('--load_model', type=str, default=None,
44
+ help='Path to load saved model. If not provided, a new model will be initialized.')
45
+
46
+ parser.add_argument('--use_custom_data', action='store_true', help='Use custom data for training')
47
+
48
+ # Determine the base directory
49
+ if hasattr(sys, 'frozen') and hasattr(sys, '_MEIPASS'):
50
+ # PyInstaller creates a temp folder and stores path in _MEIPASS
51
+ base_dir = sys._MEIPASS
52
+ elif '__file__' in globals():
53
+ # Running as a script
54
+ base_dir = os.path.dirname(os.path.abspath(__file__))
55
+ else:
56
+ # Running in an interactive environment (e.g., Jupyter, Colab)
57
+ base_dir = os.getcwd()
58
+
59
+ default_paths = [
60
+ '/content/drive/MyDrive/lightbulb/knowledge_base.json',
61
+ '/content/drive/MyDrive/lightbulb/rag_cache.json',
62
+ '/content/drive/MyDrive/lightbulb/llm_training_data/llm_training_data.jsonl'
63
+ ]
64
+
65
+ parser.add_argument('--custom_data_paths', nargs='+', default=default_paths,
66
+ help='Paths to custom data files (relative to the script location or current working directory)')
67
+
68
+ args, unknown = parser.parse_known_args()
69
+
70
+ # Convert relative paths to absolute paths
71
+ args.custom_data_paths = [os.path.abspath(os.path.join(base_dir, path)) for path in args.custom_data_paths]
72
+
73
+ return args
74
+
75
+ import json
76
+ import jsonlines
77
+
78
+ def load_custom_data_from_files(file_paths):
79
+ custom_data = []
80
+ for file_path in file_paths:
81
+ if file_path.endswith('.json'):
82
+ with open(file_path, 'r') as f:
83
+ data = json.load(f)
84
+ if isinstance(data, list):
85
+ custom_data.extend(data)
86
+ else:
87
+ custom_data.append(data)
88
+ elif file_path.endswith('.jsonl'):
89
+ with jsonlines.open(file_path) as reader:
90
+ custom_data.extend(reader)
91
+ return custom_data
92
+
93
+ def preprocess_custom_data(data_list):
94
+ processed_data = []
95
+ for item in data_list:
96
+ # Check if the item is a string (JSON)
97
+ if isinstance(item, str):
98
+ try:
99
+ item = json.loads(item)
100
+ except json.JSONDecodeError:
101
+ print(f"Failed to parse JSON: {item[:100]}...") # Print first 100 chars for debugging
102
+ continue # Skip this item if it's not valid JSON
103
+
104
+ # Process query and content
105
+ query = item.get('query', '')
106
+ content = item.get('content', '')
107
+ if content == "RAG response generation failed.":
108
+ content = ""
109
+
110
+ # Combine query and content
111
+ combined_text = f"Query: {query} Content: {content}"
112
+
113
+ # Process numerical data (assuming these are available in the item dict)
114
+ episode_reward = item.get('episode_reward', 0)
115
+ loss = item.get('loss', 0)
116
+ cosine_similarity = item.get('cosine_similarity', 0)
117
+ rag_performance = item.get('rag_performance', 0)
118
+ ranking_model_performance = item.get('ranking_model_performance', 0)
119
+
120
+ # Create a dictionary with processed data
121
+ processed_item = {
122
+ 'text': combined_text,
123
+ 'episode_reward': episode_reward,
124
+ 'loss': loss,
125
+ 'cosine_similarity': cosine_similarity,
126
+ 'rag_performance': rag_performance,
127
+ 'ranking_model_performance': ranking_model_performance
128
+ }
129
+
130
+ processed_data.append(processed_item)
131
+
132
+ return processed_data
133
+
134
+ def load_custom_data(args, tokenizer, custom_data):
135
+ # Preprocess the custom data
136
+ processed_data = preprocess_custom_data(custom_data)
137
+
138
+ # Create a custom dataset
139
+ class CustomDataset(torch.utils.data.Dataset):
140
+ def __init__(self, data, tokenizer, max_length):
141
+ self.data = data
142
+ self.tokenizer = tokenizer
143
+ self.max_length = max_length
144
+
145
+ def __len__(self):
146
+ return len(self.data)
147
+
148
+ def __getitem__(self, idx):
149
+ item = self.data[idx]
150
+ encoded = self.tokenizer.encode_plus(
151
+ item['text'],
152
+ max_length=self.max_length,
153
+ padding='max_length',
154
+ truncation=True,
155
+ return_tensors='pt'
156
+ )
157
+ return {
158
+ 'input_ids': encoded['input_ids'].squeeze(),
159
+ 'attention_mask': encoded['attention_mask'].squeeze(),
160
+ 'episode_reward': torch.tensor(item['episode_reward'], dtype=torch.float),
161
+ 'loss': torch.tensor(item['loss'], dtype=torch.float),
162
+ 'cosine_similarity': torch.tensor(item['cosine_similarity'], dtype=torch.float),
163
+ 'rag_performance': torch.tensor(item['rag_performance'], dtype=torch.float),
164
+ 'ranking_model_performance': torch.tensor(item['ranking_model_performance'], dtype=torch.float)
165
+ }
166
+
167
+ # Create dataset and dataloader
168
+ dataset = CustomDataset(processed_data, tokenizer, args.max_length)
169
+
170
+ # Split the dataset into train and eval
171
+ train_size = int(0.8 * len(dataset))
172
+ eval_size = len(dataset) - train_size
173
+ train_dataset, eval_dataset = torch.utils.data.random_split(dataset, [train_size, eval_size])
174
+
175
+ train_loader = DataLoader(
176
+ train_dataset,
177
+ batch_size=args.batch_size,
178
+ shuffle=True,
179
+ num_workers=4
180
+ )
181
+ eval_loader = DataLoader(
182
+ eval_dataset,
183
+ batch_size=args.batch_size,
184
+ shuffle=False,
185
+ num_workers=4
186
+ )
187
+
188
+ return train_loader, eval_loader
189
+
190
+
191
+
192
+ def load_data(args, tokenizer):
193
+ # Load the dataset
194
+ dataset = load_dataset(args.dataset_name, args.dataset_config)
195
+
196
+ # Ensure the tokenizer has a padding token
197
+ if tokenizer.pad_token is None:
198
+ tokenizer.pad_token = tokenizer.eos_token
199
+
200
+ def tokenize_function(examples):
201
+ return tokenizer(examples['text'], truncation=True, max_length=args.max_length)
202
+
203
+ tokenized_datasets = dataset.map(
204
+ tokenize_function,
205
+ batched=True,
206
+ num_proc=4,
207
+ remove_columns=dataset['train'].column_names,
208
+ )
209
+
210
+ # Build inputs and labels for language modeling
211
+ block_size = args.max_length
212
+
213
+ def group_texts(examples):
214
+ # Concatenate all texts
215
+ concatenated_examples = {k: sum(examples[k], []) for k in examples.keys()}
216
+ total_length = len(concatenated_examples['input_ids'])
217
+ # We drop the small remainder
218
+ total_length = (total_length // block_size) * block_size
219
+ # Split by chunks of block_size
220
+ result = {
221
+ k: [t[i : i + block_size] for i in range(0, total_length, block_size)]
222
+ for k, t in concatenated_examples.items()
223
+ }
224
+ result['labels'] = result['input_ids'].copy()
225
+ return result
226
+
227
+ lm_datasets = tokenized_datasets.map(
228
+ group_texts,
229
+ batched=True,
230
+ num_proc=4,
231
+ )
232
+
233
+ # Create DataLoader
234
+ train_dataset = lm_datasets['train']
235
+ eval_dataset = lm_datasets['validation'] if 'validation' in lm_datasets else lm_datasets['test']
236
+
237
+ def data_collator(data):
238
+ return {
239
+ 'input_ids': torch.tensor([f['input_ids'] for f in data], dtype=torch.long),
240
+ 'labels': torch.tensor([f['labels'] for f in data], dtype=torch.long)
241
+ }
242
+
243
+ train_loader = DataLoader(
244
+ train_dataset,
245
+ shuffle=True,
246
+ batch_size=args.batch_size,
247
+ collate_fn=data_collator,
248
+ pin_memory=True, # Speeds up transfer to GPU
249
+ num_workers=4
250
+ )
251
+ eval_loader = DataLoader(
252
+ eval_dataset,
253
+ shuffle=False,
254
+ batch_size=args.batch_size,
255
+ collate_fn=data_collator,
256
+ pin_memory=True,
257
+ num_workers=4
258
+ )
259
+
260
+ return train_loader, eval_loader
261
+
262
+ def save_all_models(transformer_model, representation_network, dynamics_network, prediction_network, action_encoder, save_dir, epoch):
263
+ """
264
+ Save all models to the specified directory.
265
+
266
+ Args:
267
+ transformer_model (nn.Module): Transformer model.
268
+ representation_network (nn.Module): Representation network.
269
+ dynamics_network (nn.Module): Dynamics network.
270
+ prediction_network (nn.Module): Prediction network.
271
+ action_encoder (nn.Module): Action encoder.
272
+ save_dir (str): Directory to save the models.
273
+ epoch (int): Current epoch number.
274
+ """
275
+ os.makedirs(save_dir, exist_ok=True)
276
+
277
+ torch.save(transformer_model.state_dict(), os.path.join(save_dir, f'transformer_model_epoch_{epoch}.pt'))
278
+ torch.save(representation_network.state_dict(), os.path.join(save_dir, f'representation_network_epoch_{epoch}.pt'))
279
+ torch.save(dynamics_network.state_dict(), os.path.join(save_dir, f'dynamics_network_epoch_{epoch}.pt'))
280
+ torch.save(prediction_network.state_dict(), os.path.join(save_dir, f'prediction_network_epoch_{epoch}.pt'))
281
+ torch.save(action_encoder.state_dict(), os.path.join(save_dir, f'action_encoder_epoch_{epoch}.pt'))
282
+
283
+ print(f"All models saved for epoch {epoch}.")
284
+
285
+ class RotaryPositionalEncoding(nn.Module):
286
+ def __init__(self, d_model):
287
+ super(RotaryPositionalEncoding, self).__init__()
288
+ inv_freq = 1.0 / (10000 ** (torch.arange(0, d_model, 2).float() / d_model))
289
+ self.register_buffer('inv_freq', inv_freq)
290
+
291
+ def forward(self, x):
292
+ seq_len, batch_size, _ = x.size()
293
+ t = torch.arange(seq_len, device=x.device).type_as(self.inv_freq)
294
+ sinusoid_inp = torch.einsum("i,j->ij", t, self.inv_freq)
295
+ sin = sinusoid_inp.sin().unsqueeze(1) # (seq_len, 1, d_model/2)
296
+ cos = sinusoid_inp.cos().unsqueeze(1) # (seq_len, 1, d_model/2)
297
+
298
+ x1 = x[..., 0::2]
299
+ x2 = x[..., 1::2]
300
+
301
+ # Apply rotation
302
+ x_rotated = torch.zeros_like(x)
303
+ x_rotated[..., 0::2] = x1 * cos - x2 * sin
304
+ x_rotated[..., 1::2] = x1 * sin + x2 * cos
305
+
306
+ return x_rotated
307
+
308
+ class MultiHeadAttention(nn.Module):
309
+ def __init__(self, d_model, num_heads):
310
+ super(MultiHeadAttention, self).__init__()
311
+ assert d_model % num_heads == 0, "d_model must be divisible by num_heads"
312
+ self.d_k = d_model // num_heads
313
+ self.num_heads = num_heads
314
+ self.linear_q = nn.Linear(d_model, d_model)
315
+ self.linear_k = nn.Linear(d_model, d_model)
316
+ self.linear_v = nn.Linear(d_model, d_model)
317
+ self.linear_out = nn.Linear(d_model, d_model)
318
+
319
+ def forward(self, query, key, value, mask=None):
320
+ batch_size = query.size(0)
321
+ query = self.linear_q(query).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)
322
+ key = self.linear_k(key).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)
323
+ value = self.linear_v(value).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)
324
+
325
+ scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(self.d_k)
326
+ if mask is not None:
327
+ scores = scores.masked_fill(mask == 0, -1e4)
328
+ attn = F.softmax(scores, dim=-1)
329
+ output = torch.matmul(attn, value)
330
+
331
+ output = output.transpose(1, 2).contiguous().view(batch_size, -1, self.num_heads * self.d_k)
332
+ return self.linear_out(output)
333
+
334
+ class MoE(nn.Module):
335
+ def __init__(self, d_model, num_experts, d_ff, top_k=2, dropout=0.1):
336
+ super(MoE, self).__init__()
337
+ self.num_experts = num_experts
338
+ self.top_k = top_k
339
+ self.experts = nn.ModuleList([
340
+ nn.Sequential(
341
+ nn.Linear(d_model, d_ff),
342
+ nn.GELU() if i % 2 == 0 else nn.SiLU(),
343
+ nn.Linear(d_ff, d_model)
344
+ )
345
+ for i in range(num_experts)
346
+ ])
347
+ self.gate = nn.Linear(d_model, num_experts)
348
+ self.dropout = nn.Dropout(dropout)
349
+
350
+ def forward(self, x):
351
+ batch_size, seq_len, d_model = x.size()
352
+ # Compute gating scores
353
+ gate_scores = self.gate(x) # (batch_size, seq_len, num_experts)
354
+ top_k_scores, top_k_indices = torch.topk(gate_scores, self.top_k, dim=-1) # (batch_size, seq_len, top_k)
355
+ top_k_scores = F.softmax(top_k_scores, dim=-1) # (batch_size, seq_len, top_k)
356
+
357
+ # Initialize output
358
+ output = torch.zeros_like(x)
359
+
360
+ # Flatten batch and sequence dimensions
361
+ x_flat = x.view(-1, d_model) # (batch_size * seq_len, d_model)
362
+ output_flat = output.view(-1, d_model)
363
+ top_k_indices_flat = top_k_indices.view(-1, self.top_k) # (batch_size * seq_len, top_k)
364
+ top_k_scores_flat = top_k_scores.view(-1, self.top_k) # (batch_size * seq_len, top_k)
365
+
366
+ for k in range(self.top_k):
367
+ expert_idx_flat = top_k_indices_flat[:, k] # (batch_size * seq_len)
368
+ expert_scores_flat = top_k_scores_flat[:, k] # (batch_size * seq_len)
369
+ for e in range(self.num_experts):
370
+ mask = (expert_idx_flat == e) # Boolean mask
371
+ if mask.any():
372
+ x_masked = x_flat[mask] # Select tokens for expert e
373
+ expert_output = self.experts[e](x_masked) # Apply expert e
374
+ output_flat[mask] += expert_scores_flat[mask].unsqueeze(-1) * expert_output
375
+
376
+ output = output_flat.view(batch_size, seq_len, d_model)
377
+ return self.dropout(output)
378
+
379
+ class TransformerBlock(nn.Module):
380
+ def __init__(self, d_model, num_heads, d_ff, num_experts, dropout=0.1, top_k=2):
381
+ super(TransformerBlock, self).__init__()
382
+ self.self_attention = MultiHeadAttention(d_model, num_heads)
383
+ self.norm1 = nn.LayerNorm(d_model)
384
+ self.cross_attention = MultiHeadAttention(d_model, num_heads)
385
+ self.norm2 = nn.LayerNorm(d_model)
386
+ self.moe = MoE(d_model, num_experts, d_ff, top_k, dropout)
387
+ self.norm3 = nn.LayerNorm(d_model)
388
+
389
+ def forward(self, x, mask=None, enc_output=None, enc_mask=None):
390
+ # Self-attention
391
+ attn_output = self.self_attention(x, x, x, mask)
392
+ x = self.norm1(x + attn_output)
393
+ # Cross-attention (only in decoder)
394
+ if enc_output is not None:
395
+ cross_attn_output = self.cross_attention(x, enc_output, enc_output, enc_mask)
396
+ x = self.norm2(x + cross_attn_output)
397
+ # Feedforward/MoE
398
+ moe_output = self.moe(x)
399
+ return self.norm3(x + moe_output)
400
+
401
+ class Transformer(nn.Module):
402
+ def __init__(self, input_dim, d_model, num_heads, num_layers, d_ff, num_experts, output_dim, dropout=0.1, top_k=2):
403
+ super(Transformer, self).__init__()
404
+ self.embedding = nn.Embedding(input_dim, d_model, padding_idx=input_dim - 1)
405
+ self.rotary_positional_encoding = RotaryPositionalEncoding(d_model)
406
+ self.encoder_layers = nn.ModuleList(
407
+ [TransformerBlock(d_model, num_heads, d_ff, num_experts, dropout, top_k) for _ in range(num_layers)]
408
+ )
409
+ self.decoder_layers = nn.ModuleList(
410
+ [TransformerBlock(d_model, num_heads, d_ff, num_experts, dropout, top_k) for _ in range(num_layers)]
411
+ )
412
+ self.output_layer = nn.Linear(d_model, output_dim)
413
+ self.d_model = d_model
414
+
415
+ def forward(self, src, tgt, src_mask=None, tgt_mask=None):
416
+ # Encoder
417
+ src = self.embedding(src) * math.sqrt(self.d_model)
418
+ src = src.transpose(0, 1) # (batch_size, seq_len, d_model) -> (seq_len, batch_size, d_model)
419
+ src = self.rotary_positional_encoding(src)
420
+ src = src.transpose(0, 1) # (seq_len, batch_size, d_model) -> (batch_size, seq_len, d_model)
421
+ for layer in self.encoder_layers:
422
+ src = layer(src, src_mask)
423
+
424
+ # Decoder
425
+ tgt = self.embedding(tgt) * math.sqrt(self.d_model)
426
+ tgt = tgt.transpose(0, 1)
427
+ tgt = self.rotary_positional_encoding(tgt)
428
+ tgt = tgt.transpose(0, 1)
429
+ for layer in self.decoder_layers:
430
+ tgt = layer(tgt, tgt_mask, src, src_mask)
431
+ output = self.output_layer(tgt)
432
+ return output
433
+
434
+ def generate_with_beam_search(self, src, tokenizer, beam_size=5, max_length=20, n_tokens_predict=3, temperature=1.0):
435
+ """
436
+ Generate sequences using beam search with multi-token prediction.
437
+
438
+ Args:
439
+ src (torch.Tensor): Source input tensor of shape (batch_size, seq_len)
440
+ tokenizer: Tokenizer to access special tokens
441
+ beam_size (int): Size of the beam for beam search
442
+ max_length (int): Maximum length of the generated sequence
443
+ n_tokens_predict (int): Number of tokens to predict at each step
444
+ temperature (float): Temperature parameter for softmax
445
+
446
+ Returns:
447
+ List[Tuple[torch.Tensor, float]]: List of (sequence, score) tuples
448
+ """
449
+ batch_size = src.size(0)
450
+ device = src.device
451
+ vocab_size = self.output_layer.out_features
452
+
453
+ # Encode the source
454
+ src_enc = self.encode(src)
455
+
456
+ # Initialize beam
457
+ beam = [(torch.full((batch_size, 1), tokenizer.bos_token_id, dtype=torch.long, device=device),
458
+ 0.0, # log probability
459
+ torch.zeros(batch_size, device=device), # cumulative entropy
460
+ torch.zeros(batch_size, device=device))] # cumulative variance
461
+
462
+ for _ in range(max_length // n_tokens_predict):
463
+ all_candidates = []
464
+ for seq, score, cum_entropy, cum_variance in beam:
465
+ if seq[:, -1].item() == tokenizer.eos_token_id:
466
+ all_candidates.append((seq, score, cum_entropy, cum_variance))
467
+ continue
468
+
469
+ # Predict next n tokens
470
+ logits = self.predict_next_n_tokens(src_enc, seq, n_tokens_predict)
471
+
472
+ # Calculate probabilities, entropy, and variance
473
+ probs = F.softmax(logits / temperature, dim=-1)
474
+ entropy = -torch.sum(probs * torch.log(probs + 1e-9), dim=-1)
475
+ variance = torch.var(probs, dim=-1)
476
+
477
+ # Sample top-k tokens for each position
478
+ topk_probs, topk_indices = torch.topk(probs, k=beam_size, dim=-1)
479
+
480
+ # Generate all possible continuations
481
+ for i in range(beam_size ** n_tokens_predict):
482
+ indices = [i // (beam_size ** j) % beam_size for j in range(n_tokens_predict)]
483
+ new_tokens = topk_indices[:, range(n_tokens_predict), indices]
484
+ new_seq = torch.cat([seq, new_tokens], dim=-1)
485
+ new_score = score + torch.sum(torch.log(topk_probs[:, range(n_tokens_predict), indices]))
486
+ new_entropy = cum_entropy + torch.sum(entropy[:, indices])
487
+ new_variance = cum_variance + torch.sum(variance[:, indices])
488
+
489
+ all_candidates.append((new_seq, new_score, new_entropy, new_variance))
490
+
491
+ # Select top beam_size candidates
492
+ beam = sorted(all_candidates, key=lambda x: x[1] - 0.1 * x[2] + 0.05 * x[3], reverse=True)[:beam_size]
493
+
494
+ # Stop if all beams have ended
495
+ if all(seq[:, -1].item() == tokenizer.eos_token_id for seq, _, _, _ in beam):
496
+ break
497
+
498
+ return [(seq, score) for seq, score, _, _ in beam]
499
+
500
+ def encode(self, src):
501
+ src_emb = self.embedding(src) * math.sqrt(self.d_model)
502
+ src_emb = src_emb.transpose(0, 1)
503
+ src_emb = self.rotary_positional_encoding(src_emb)
504
+ src_emb = src_emb.transpose(0, 1)
505
+ src_enc = src_emb
506
+ for layer in self.encoder_layers:
507
+ src_enc = layer(src_enc)
508
+ return src_enc
509
+
510
+ def predict_next_n_tokens(self, src_enc, tgt_seq, n_tokens):
511
+ tgt_emb = self.embedding(tgt_seq) * math.sqrt(self.d_model)
512
+ tgt_emb = tgt_emb.transpose(0, 1)
513
+ tgt_emb = self.rotary_positional_encoding(tgt_emb)
514
+ tgt_emb = tgt_emb.transpose(0, 1)
515
+ tgt_dec = tgt_emb
516
+ for layer in self.decoder_layers:
517
+ tgt_dec = layer(tgt_dec, None, src_enc, None)
518
+ output = self.output_layer(tgt_dec[:, -1:])
519
+ return output.repeat(1, n_tokens, 1)
520
+
521
+ # Objective Functions
522
+
523
+ class InfoNCE_Loss(nn.Module):
524
+ def __init__(self, temperature=0.07):
525
+ super(InfoNCE_Loss, self).__init__()
526
+ self.temperature = temperature
527
+ self.cross_entropy = nn.CrossEntropyLoss()
528
+
529
+ def forward(self, z_i, z_j):
530
+ """
531
+ Args:
532
+ z_i (torch.Tensor): Flattened representations from view i, shape (2n, embed_dim)
533
+ z_j (torch.Tensor): Flattened representations from view j, shape (2n, embed_dim)
534
+
535
+ Returns:
536
+ torch.Tensor: InfoNCE loss
537
+ """
538
+ n = z_i.size(0)
539
+ z = torch.cat([z_i, z_j], dim=0) # Shape: (2n, embed_dim)
540
+
541
+ z = F.normalize(z, dim=1)
542
+ similarity_matrix = torch.matmul(z, z.T) # Shape: (2n, 2n)
543
+
544
+ # Create a mask to exclude self-similarity
545
+ mask = torch.eye(2 * n, device=z.device, dtype=torch.bool)
546
+ similarity_matrix = similarity_matrix.masked_fill(mask, -1e4) # Use a manageable negative value
547
+
548
+ # Create labels for contrastive learning
549
+ labels = torch.arange(n, device=z.device)
550
+ labels = torch.cat([labels + n, labels], dim=0) # Shape: (2n,)
551
+
552
+ # Apply temperature scaling
553
+ similarity_matrix /= self.temperature
554
+
555
+ # Compute cross-entropy loss
556
+ loss = self.cross_entropy(similarity_matrix, labels)
557
+ return loss
558
+
559
+ class CovarianceRegularization(nn.Module):
560
+ def __init__(self, lambda_reg=1e-3):
561
+ super(CovarianceRegularization, self).__init__()
562
+ self.lambda_reg = lambda_reg
563
+
564
+ def forward(self, embeddings):
565
+ """
566
+ Args:
567
+ embeddings (torch.Tensor): Embedding tensor, shape (batch_size, embed_dim)
568
+
569
+ Returns:
570
+ torch.Tensor: Covariance regularization loss
571
+ """
572
+ batch_size, embed_dim = embeddings.size()
573
+ mean = embeddings.mean(dim=0)
574
+ embeddings_centered = embeddings - mean
575
+ cov = (embeddings_centered.T @ embeddings_centered) / (batch_size - 1)
576
+ cov_loss = torch.sum(cov ** 2) - torch.sum(torch.diag(cov) ** 2)
577
+ return self.lambda_reg * cov_loss
578
+
579
+ class DynamicsPerformanceLoss(nn.Module):
580
+ def __init__(self, lambda_var=1e-3):
581
+ super(DynamicsPerformanceLoss, self).__init__()
582
+ self.lambda_var = lambda_var
583
+
584
+ def forward(self, true_next_state, predicted_next_state):
585
+ """
586
+ Args:
587
+ true_next_state (torch.Tensor): Ground truth next state, shape (batch_size, state_dim)
588
+ predicted_next_state (torch.Tensor): Predicted next state, shape (batch_size, state_dim)
589
+
590
+ Returns:
591
+ torch.Tensor: Dynamics performance loss
592
+ """
593
+ mse_loss = F.mse_loss(predicted_next_state, true_next_state)
594
+ variance_loss = torch.var(predicted_next_state, dim=0).mean()
595
+ return mse_loss + self.lambda_var * variance_loss
596
+
597
+ class ThoughtConsistencyLoss(nn.Module):
598
+ def __init__(self):
599
+ super(ThoughtConsistencyLoss, self).__init__()
600
+
601
+ def forward(self, true_next_state, perturbed_next_state):
602
+ """
603
+ Args:
604
+ true_next_state (torch.Tensor): Ground truth next state, shape (batch_size, state_dim)
605
+ perturbed_next_state (torch.Tensor): Perturbed next state, shape (batch_size, state_dim)
606
+
607
+ Returns:
608
+ torch.Tensor: Thought-consistency loss
609
+ """
610
+ return F.mse_loss(true_next_state, perturbed_next_state)
611
+
612
+ class PolicyValueJointLoss(nn.Module):
613
+ def __init__(self, lambda_value=0.5):
614
+ super(PolicyValueJointLoss, self).__init__()
615
+ self.lambda_value = lambda_value
616
+ self.cross_entropy = nn.CrossEntropyLoss()
617
+ self.mse_loss = nn.MSELoss()
618
+
619
+ def forward(self, policy_logits, true_policy, value_pred, true_value):
620
+ """
621
+ Args:
622
+ policy_logits (torch.Tensor): Logits from the policy network, shape (batch_size * seq_len, num_actions)
623
+ true_policy (torch.Tensor): Ground truth policy, shape (batch_size * seq_len, num_actions)
624
+ value_pred (torch.Tensor): Predicted values, shape (batch_size * seq_len)
625
+ true_value (torch.Tensor): Ground truth values, shape (batch_size * seq_len)
626
+
627
+ Returns:
628
+ torch.Tensor: Combined policy and value loss
629
+ """
630
+ policy_logits = policy_logits.reshape(-1, policy_logits.size(-1))
631
+ true_policy = true_policy.reshape(-1, true_policy.size(-1))
632
+ value_pred = value_pred.reshape(-1)
633
+ true_value = true_value.reshape(-1)
634
+
635
+
636
+ policy_loss = self.cross_entropy(policy_logits, true_policy.argmax(dim=1))
637
+ value_loss = self.mse_loss(value_pred, true_value)
638
+ return policy_loss + self.lambda_value * value_loss
639
+
640
+ class ActionDiversityReward(nn.Module):
641
+ def __init__(self, lambda_div=1e-3):
642
+ super(ActionDiversityReward, self).__init__()
643
+ self.lambda_div = lambda_div
644
+
645
+ def forward(self, action_embeddings):
646
+ """
647
+ Args:
648
+ action_embeddings (torch.Tensor): Embeddings of actions, shape (batch_size, embed_dim)
649
+
650
+ Returns:
651
+ torch.Tensor: Action diversity loss
652
+ """
653
+ similarity_matrix = F.cosine_similarity(action_embeddings.unsqueeze(1), action_embeddings.unsqueeze(0), dim=2)
654
+ # Zero out self-similarity
655
+ similarity_matrix = similarity_matrix - torch.eye(similarity_matrix.size(0)).to(action_embeddings.device)
656
+ diversity_loss = torch.sum(similarity_matrix ** 2)
657
+ return self.lambda_div * diversity_loss
658
+
659
+ class ExpectedThoughtValueLoss(nn.Module):
660
+ def __init__(self):
661
+ super(ExpectedThoughtValueLoss, self).__init__()
662
+
663
+ def forward(self, mcts_best_values):
664
+ """
665
+ Args:
666
+ mcts_best_values (torch.Tensor): Best values from MCTS, shape (batch_size)
667
+
668
+ Returns:
669
+ torch.Tensor: ETV loss
670
+ """
671
+ return -mcts_best_values.mean()
672
+
673
+ class ExplorationRegularization(nn.Module):
674
+ def __init__(self, lambda_expl=1e-3):
675
+ super(ExplorationRegularization, self).__init__()
676
+ self.lambda_expl = lambda_expl
677
+
678
+ def forward(self, visit_counts):
679
+ """
680
+ Args:
681
+ visit_counts (torch.Tensor): Visit counts for actions, shape (batch_size, num_actions)
682
+
683
+ Returns:
684
+ torch.Tensor: Exploration regularization loss
685
+ """
686
+ reward = torch.sum(1.0 / (visit_counts + 1), dim=-1)
687
+ return self.lambda_expl * reward.mean()
688
+
689
+ class KL_DivergenceLoss(nn.Module):
690
+ def __init__(self):
691
+ super(KL_DivergenceLoss, self).__init__()
692
+
693
+ def forward(self, old_policy, new_policy):
694
+ """
695
+ Args:
696
+ old_policy (torch.Tensor): Old policy probabilities, shape (batch_size, num_actions)
697
+ new_policy (torch.Tensor): New policy probabilities, shape (batch_size, num_actions)
698
+
699
+ Returns:
700
+ torch.Tensor: KL divergence loss
701
+ """
702
+ kl_div = F.kl_div(new_policy.log(), old_policy, reduction='batchmean')
703
+ return kl_div
704
+
705
+ # MuZero Components
706
+
707
+ class ActionEncoder(nn.Module):
708
+ def __init__(self, action_vocab_size, embed_dim):
709
+ super(ActionEncoder, self).__init__()
710
+ self.embedding = nn.Embedding(action_vocab_size, embed_dim)
711
+
712
+ def forward(self, action_indices):
713
+ """
714
+ Args:
715
+ action_indices (torch.Tensor): Tensor of shape (batch_size, seq_len)
716
+
717
+ Returns:
718
+ torch.Tensor: Encoded actions of shape (batch_size, seq_len, embed_dim)
719
+ """
720
+ return self.embedding(action_indices)
721
+
722
+ class RepresentationNetwork(nn.Module):
723
+ def __init__(self, vocab_dim, d_model, state_dim):
724
+ super(RepresentationNetwork, self).__init__()
725
+ self.proj = nn.Linear(vocab_dim, d_model) # Project from vocab_dim to d_model
726
+ self.linear = nn.Linear(d_model, state_dim) # Project from d_model to state_dim
727
+ self.norm = nn.LayerNorm(state_dim)
728
+
729
+ def forward(self, transformer_output):
730
+ """
731
+ Args:
732
+ transformer_output (torch.Tensor): Shape (batch_size, seq_len, vocab_dim)
733
+
734
+ Returns:
735
+ torch.Tensor: Encoded state of shape (batch_size, seq_len, state_dim)
736
+ """
737
+ # First project down from vocab_dim to d_model
738
+ projected_output = self.proj(transformer_output) # Shape: (batch_size, seq_len, d_model)
739
+ # Then project down from d_model to state_dim
740
+ state = self.linear(projected_output) # Shape: (batch_size, seq_len, state_dim)
741
+ state = self.norm(state) # Shape: (batch_size, seq_len, state_dim)
742
+ return state
743
+
744
+
745
+ class DynamicsNetwork(nn.Module):
746
+ def __init__(self, state_dim, action_dim, hidden_dim):
747
+ super(DynamicsNetwork, self).__init__()
748
+ self.rms_norm = nn.LayerNorm(state_dim)
749
+ self.fc1 = nn.Linear(state_dim + action_dim, hidden_dim)
750
+ self.activation = nn.GELU()
751
+ self.fc2 = nn.Linear(hidden_dim, state_dim)
752
+
753
+ def forward(self, state, action):
754
+ """
755
+ Args:
756
+ state (torch.Tensor): Current state, shape (batch_size, seq_len, state_dim)
757
+ action (torch.Tensor): Action embedding, shape (batch_size, seq_len, action_dim)
758
+
759
+ Returns:
760
+ torch.Tensor: Predicted next state, shape (batch_size, seq_len, state_dim)
761
+ """
762
+ norm_state = self.rms_norm(state)
763
+ combined = torch.cat([norm_state, action], dim=-1)
764
+ hidden = self.activation(self.fc1(combined))
765
+ next_state = self.fc2(hidden)
766
+ return next_state
767
+
768
+ class PredictionNetwork(nn.Module):
769
+ def __init__(self, state_dim, action_vocab_size, value_dim):
770
+ super(PredictionNetwork, self).__init__()
771
+ self.state_dim = state_dim
772
+ self.rms_norm = nn.LayerNorm(state_dim)
773
+ self.policy_head = nn.Linear(state_dim, action_vocab_size) # Output size is action_vocab_size
774
+ self.value_head = nn.Linear(state_dim, value_dim)
775
+
776
+ def forward(self, state):
777
+ """
778
+ Args:
779
+ state (torch.Tensor): State representation, shape (batch_size, state_dim)
780
+ Returns:
781
+ Tuple[torch.Tensor, torch.Tensor]: Policy logits and value estimates
782
+ """
783
+ norm_state = self.rms_norm(state)
784
+ policy_logits = self.policy_head(norm_state) # Shape: (batch_size, action_vocab_size)
785
+ value_estimates = self.value_head(norm_state).squeeze(-1) # Shape: (batch_size)
786
+ return policy_logits, value_estimates
787
+
788
+
789
+
790
+
791
+ class MCTSNode:
792
+ __slots__ = [
793
+ 'state',
794
+ 'parent',
795
+ 'action',
796
+ 'children',
797
+ 'visit_count',
798
+ 'value_sum',
799
+ 'prior',
800
+ 'cached_policy',
801
+ 'cached_value',
802
+ 'thought_node',
803
+ 'entropy',
804
+ 'variance'
805
+ ]
806
+
807
+ def __init__(self, state, thought_node, parent=None, action=None):
808
+ self.state = state
809
+ self.thought_node = thought_node
810
+ self.parent = parent
811
+ self.action = action
812
+ self.children = {}
813
+ self.visit_count = 0
814
+ self.value_sum = 0.0
815
+ self.prior = 0.0
816
+ self.cached_policy = None
817
+ self.cached_value = None
818
+ self.entropy = 0.0
819
+ self.variance = 0.0
820
+
821
+ def expand(self, priors):
822
+ for child_thought_node in self.thought_node.children:
823
+ action = child_thought_node.name
824
+ if action not in self.children:
825
+ child_state = self.state.apply_action(action)
826
+ child_node = MCTSNode(
827
+ state=child_state,
828
+ thought_node=child_thought_node,
829
+ parent=self,
830
+ action=action
831
+ )
832
+ child_node.prior = priors.get(action, 1.0 / len(self.thought_node.children))
833
+ self.children[action] = child_node
834
+
835
+ def is_leaf(self):
836
+ return len(self.children) == 0
837
+
838
+ def ucb_score(self, total_visits, exploration_constant=math.sqrt(2)):
839
+ if self.visit_count == 0:
840
+ return float('inf') # Ensure unvisited nodes are selected first
841
+ avg_value = self.value_sum / self.visit_count
842
+ exploration_term = exploration_constant * self.prior * math.sqrt(total_visits) / (1 + self.visit_count)
843
+ entropy_term = -0.1 * self.entropy # Slightly prefer lower entropy
844
+ variance_term = 0.05 * self.variance # Slightly prefer higher variance
845
+ return avg_value + exploration_term + entropy_term + variance_term
846
+
847
+
848
+ class MCTS:
849
+ def __init__(self, prediction_network, dynamics_network, action_encoder, num_iterations=10, exploration_constant=math.sqrt(2), beam_size=5, n_tokens_predict=3):
850
+ self.prediction_network = prediction_network
851
+ self.dynamics_network = dynamics_network
852
+ self.action_encoder = action_encoder
853
+ self.num_iterations = num_iterations
854
+ self.exploration_constant = exploration_constant
855
+ self.beam_size = beam_size
856
+ self.n_tokens_predict = n_tokens_predict
857
+ self.cache = {}
858
+
859
+ def search_with_beam(self, root_state):
860
+ root_node = MCTSNode(state=root_state, thought_node=root_state.thought_node)
861
+
862
+ # Evaluate the root node and backpropagate
863
+ value_estimate = self.evaluate(root_node) # Evaluate and expand root_node
864
+ self.backpropagate(root_node, value_estimate) # Backpropagate the value
865
+
866
+ beam = [(root_node, 0.0, 0.0, 0.0, [])] # (node, score, cum_entropy, cum_variance, action_sequence)
867
+
868
+ for iteration in range(self.num_iterations):
869
+ all_candidates = []
870
+ for node, score, cum_entropy, cum_variance, action_sequence in beam:
871
+ if node.is_leaf():
872
+ value_estimate = self.evaluate(node)
873
+ self.backpropagate(node, value_estimate) # Backpropagate after evaluation
874
+ if len(node.children) == 0:
875
+ continue # No children to expand
876
+
877
+ total_visits = sum(child.visit_count for child in node.children.values())
878
+ # Select top actions based on UCB score
879
+ sorted_children = sorted(
880
+ node.children.items(),
881
+ key=lambda item: item[1].ucb_score(total_visits, self.exploration_constant),
882
+ reverse=True
883
+ )[:self.beam_size]
884
+
885
+ for selected_action, selected_node in sorted_children:
886
+ current_node = selected_node
887
+ current_sequence = action_sequence + [selected_action]
888
+ current_score = score
889
+ current_entropy = cum_entropy + selected_node.entropy
890
+ current_variance = cum_variance + selected_node.variance
891
+
892
+ # Predict n_tokens_predict actions
893
+ for _ in range(self.n_tokens_predict):
894
+ if current_node.is_leaf():
895
+ value_estimate = self.evaluate(current_node)
896
+ self.backpropagate(current_node, value_estimate) # Backpropagate after evaluation
897
+ if len(current_node.children) == 0:
898
+ break # No more actions
899
+ total_visits = sum(child.visit_count for child in current_node.children.values())
900
+ next_action, next_node = max(
901
+ current_node.children.items(),
902
+ key=lambda item: item[1].ucb_score(total_visits, self.exploration_constant)
903
+ )
904
+ current_sequence.append(next_action)
905
+
906
+ # Prevent division by zero by ensuring visit_count > 0
907
+ if next_node.visit_count > 0:
908
+ current_score += next_node.value_sum / next_node.visit_count
909
+ else:
910
+ # Assign a default value or handle the zero division case
911
+ current_score += 0.0 # Alternatively, use a small epsilon or skip
912
+
913
+ current_entropy += next_node.entropy
914
+ current_variance += next_node.variance
915
+ current_node = next_node
916
+
917
+ all_candidates.append((current_node, current_score, current_entropy, current_variance, current_sequence))
918
+
919
+ if not all_candidates:
920
+ break # No more candidates to expand
921
+
922
+ # Select top beam_size candidates
923
+ beam = sorted(all_candidates, key=lambda x: x[1] - 0.1 * x[2] + 0.05 * x[3], reverse=True)[:self.beam_size]
924
+ print(f"Iteration {iteration + 1}: Beam size after sorting: {len(beam)}") # Debug
925
+
926
+ if beam:
927
+ best_sequence = beam[0][4]
928
+ return best_sequence
929
+ else:
930
+ return []
931
+
932
+
933
+
934
+ def search(self, root_state):
935
+ root_node = MCTSNode(state=root_state, thought_node=root_state.thought_node)
936
+
937
+ for _ in range(self.num_iterations):
938
+ node = self.select(root_node)
939
+ value = self.evaluate(node)
940
+ self.backpropagate(node, value)
941
+
942
+ return self.best_action_sequence(root_node)
943
+
944
+ def select(self, node):
945
+ while not node.is_leaf():
946
+ total_visits = sum(child.visit_count for child in node.children.values())
947
+ _, node = max(
948
+ node.children.items(),
949
+ key=lambda item: item[1].ucb_score(total_visits, self.exploration_constant)
950
+ )
951
+ return node
952
+
953
+ def evaluate(self, node):
954
+ # Extract the last time step
955
+ state_representation = node.state.representation[:, -1, :] # Shape: (batch_size=1, state_dim)
956
+ print(f"Evaluating node with state_representation shape: {state_representation.shape}") # Debug
957
+ policy_logits, value_estimate = self.prediction_network(state_representation)
958
+ print(f"Policy logits shape: {policy_logits.shape}, Value estimate shape: {value_estimate.shape}") # Debug
959
+ value_estimate = value_estimate.item() # Now safe as batch_size=1
960
+
961
+ policy_probs = F.softmax(policy_logits, dim=-1).squeeze(0) # Shape: (action_vocab_size,)
962
+ print(f"Policy probabilities shape: {policy_probs.shape}") # Debug
963
+
964
+ priors = {}
965
+ for child in node.thought_node.children:
966
+ action_name = child.name
967
+ action_idx = action_to_index.get(action_name, None)
968
+ if action_idx is not None and action_idx < policy_probs.size(0):
969
+ priors[action_name] = policy_probs[action_idx].item()
970
+ else:
971
+ priors[action_name] = 1.0 / len(node.thought_node.children)
972
+
973
+ node.expand(priors)
974
+
975
+ # Calculate entropy and variance
976
+ entropy = -torch.sum(policy_probs * torch.log(policy_probs + 1e-9))
977
+ variance = torch.var(policy_probs)
978
+ node.entropy = entropy.item()
979
+ node.variance = variance.item()
980
+
981
+ print(f"Node entropy: {node.entropy}, variance: {node.variance}") # Debug
982
+
983
+ return value_estimate # Return the value estimate for backpropagation
984
+
985
+
986
+ def backpropagate(self, node, value):
987
+ while node is not None:
988
+ node.visit_count += 1
989
+ node.value_sum += value
990
+ node = node.parent
991
+
992
+ def best_action_sequence(self, root_node):
993
+ sequences = []
994
+ self._generate_sequences(root_node, [], sequences)
995
+
996
+ # Score sequences based on visit counts, entropy, and variance
997
+ scored_sequences = []
998
+ for seq in sequences:
999
+ score = sum(node.visit_count for node in seq)
1000
+ entropy = sum(node.entropy for node in seq)
1001
+ variance = sum(node.variance for node in seq)
1002
+ adjusted_score = score - 0.1 * entropy + 0.05 * variance
1003
+ scored_sequences.append((seq, adjusted_score))
1004
+
1005
+ # Sort sequences by adjusted score and select top beam_size
1006
+ best_sequences = sorted(scored_sequences, key=lambda x: x[1], reverse=True)[:self.beam_size]
1007
+
1008
+ # Return the actions of the best sequence
1009
+ best_sequence = best_sequences[0][0]
1010
+ return [node.action for node in best_sequence[1:self.n_tokens_predict+1]] # Exclude root node
1011
+
1012
+ def _generate_sequences(self, node, current_sequence, sequences):
1013
+ current_sequence.append(node)
1014
+ if len(current_sequence) > self.n_tokens_predict or not node.children:
1015
+ sequences.append(current_sequence)
1016
+ else:
1017
+ for child in node.children.values():
1018
+ self._generate_sequences(child, current_sequence.copy(), sequences)
1019
+
1020
+ class State:
1021
+ def __init__(self, representation, dynamics_network, action_encoder, thought_node):
1022
+ self.representation = representation
1023
+ self.dynamics_network = dynamics_network
1024
+ self.action_encoder = action_encoder
1025
+ self.thought_node = thought_node
1026
+
1027
+ def apply_action(self, action):
1028
+ next_thought_node = None
1029
+ for child in self.thought_node.children:
1030
+ if child.name == action:
1031
+ next_thought_node = child
1032
+ break
1033
+ if next_thought_node is None:
1034
+ raise ValueError(f"Action '{action}' is not valid from the current thought node.")
1035
+
1036
+ # Adjust action_index and action_embedding shapes
1037
+ action_index = torch.tensor([action_to_index[action]], device=self.representation.device)
1038
+ action_embedding = self.action_encoder(action_index) # Shape: (batch_size=1, action_dim)
1039
+
1040
+ # Extract the last time step of the state
1041
+ state = self.representation[:, -1, :] # Shape: (batch_size, state_dim)
1042
+
1043
+ # Ensure action_embedding matches the state dimension
1044
+ next_state_representation = self.dynamics_network(state, action_embedding) # Shape: (batch_size, state_dim)
1045
+
1046
+ # Append the new state to the representation history
1047
+ new_representation = torch.cat([self.representation, next_state_representation.unsqueeze(1)], dim=1) # Shape: (batch_size, seq_len+1, state_dim)
1048
+
1049
+ return State(
1050
+ representation=new_representation,
1051
+ dynamics_network=self.dynamics_network,
1052
+ action_encoder=self.action_encoder,
1053
+ thought_node=next_thought_node
1054
+ )
1055
+
1056
+ class PPOAgent:
1057
+ def __init__(self, policy_network, optimizer, clip_epsilon=0.2, entropy_coef=0.01, value_coef=0.5):
1058
+ self.policy_network = policy_network
1059
+ self.optimizer = optimizer
1060
+ self.clip_epsilon = clip_epsilon
1061
+ self.entropy_coef = entropy_coef
1062
+ self.value_coef = value_coef
1063
+
1064
+ def compute_loss(self, states, old_log_probs, actions, returns, advantages):
1065
+ # Get policy logits and value estimates
1066
+ policy_logits, value_estimates = self.policy_network(states)
1067
+
1068
+ # Flatten all tensors
1069
+ policy_logits = policy_logits.reshape(-1, policy_logits.size(-1))
1070
+ value_estimates = value_estimates.reshape(-1)
1071
+ actions = actions.reshape(-1)
1072
+ old_log_probs = old_log_probs.reshape(-1)
1073
+ returns = returns.reshape(-1)
1074
+ advantages = advantages.reshape(-1)
1075
+
1076
+ # Ensure all tensors have the same first dimension
1077
+ assert policy_logits.size(0) == value_estimates.size(0) == actions.size(0) == old_log_probs.size(0) == returns.size(0) == advantages.size(0), "Tensor sizes mismatch"
1078
+
1079
+ # Compute new log probabilities
1080
+ new_log_probs_all = F.log_softmax(policy_logits, dim=-1)
1081
+ new_log_probs = new_log_probs_all.gather(1, actions.unsqueeze(-1)).squeeze(-1)
1082
+
1083
+ # Compute ratios
1084
+ ratios = torch.exp(new_log_probs - old_log_probs)
1085
+
1086
+ # PPO surrogate loss
1087
+ surr1 = ratios * advantages
1088
+ surr2 = torch.clamp(ratios, 1 - self.clip_epsilon, 1 + self.clip_epsilon) * advantages
1089
+ policy_loss = -torch.min(surr1, surr2).mean()
1090
+
1091
+ # Value loss
1092
+ value_loss = F.mse_loss(value_estimates, returns)
1093
+
1094
+ # Entropy loss
1095
+ entropy = -(new_log_probs * torch.exp(new_log_probs)).mean()
1096
+
1097
+ # Total loss
1098
+ total_loss = policy_loss + self.value_coef * value_loss - self.entropy_coef * entropy
1099
+ return total_loss
1100
+
1101
+ # Tree of Thought Components
1102
+
1103
+ class ThoughtNode:
1104
+ def __init__(self, name):
1105
+ self.name = name
1106
+ self.children = []
1107
+ self.parent = None
1108
+
1109
+ def add_child(self, child_node):
1110
+ child_node.parent = self
1111
+ self.children.append(child_node)
1112
+
1113
+ # Function to build the Tree of Thought from your detailed structure
1114
+ def build_tree_of_thought():
1115
+ # Create the root node
1116
+ root = ThoughtNode('Problem-Solving Process')
1117
+
1118
+ # Level 1 nodes
1119
+ problem_identification = ThoughtNode('Problem Identification')
1120
+ problem_analysis = ThoughtNode('Problem Analysis')
1121
+ solution_generation = ThoughtNode('Solution Generation')
1122
+ implementation = ThoughtNode('Implementation')
1123
+ evaluation_adjustment = ThoughtNode('Evaluation and Adjustment')
1124
+
1125
+ root.add_child(problem_identification)
1126
+ root.add_child(problem_analysis)
1127
+ root.add_child(solution_generation)
1128
+ root.add_child(implementation)
1129
+ root.add_child(evaluation_adjustment)
1130
+
1131
+ # Problem Identification children
1132
+ B1 = ThoughtNode('Define the Problem')
1133
+ B2 = ThoughtNode('Identify Stakeholders')
1134
+ B3 = ThoughtNode('Determine Constraints')
1135
+ B4 = ThoughtNode('Recognize Problem Type')
1136
+ B5 = ThoughtNode('Historical Context')
1137
+ problem_identification.add_child(B1)
1138
+ problem_identification.add_child(B2)
1139
+ problem_identification.add_child(B3)
1140
+ problem_identification.add_child(B4)
1141
+ problem_identification.add_child(B5)
1142
+
1143
+ # Define the Problem children
1144
+ B1a = ThoughtNode('Problem Statement Formulation')
1145
+ B1b = ThoughtNode('Scope Definition')
1146
+ B1c = ThoughtNode('Objective Setting')
1147
+ B1.add_child(B1a)
1148
+ B1.add_child(B1b)
1149
+ B1.add_child(B1c)
1150
+
1151
+ # Identify Stakeholders children
1152
+ B2a = ThoughtNode('Stakeholder Mapping')
1153
+ B2b = ThoughtNode('Interest and Influence Analysis')
1154
+ B2c = ThoughtNode('Engagement Strategy')
1155
+ B2.add_child(B2a)
1156
+ B2.add_child(B2b)
1157
+ B2.add_child(B2c)
1158
+
1159
+ # Determine Constraints children
1160
+ B3a = ThoughtNode('Resource Limitations')
1161
+ B3b = ThoughtNode('Time Constraints')
1162
+ B3c = ThoughtNode('Legal and Regulatory Constraints')
1163
+ B3.add_child(B3a)
1164
+ B3.add_child(B3b)
1165
+ B3.add_child(B3c)
1166
+
1167
+ # Recognize Problem Type children
1168
+ B4a = ThoughtNode('Simple vs Complex')
1169
+ B4b = ThoughtNode('Known vs Unknown')
1170
+ B4c = ThoughtNode('Tame vs Wicked Problems')
1171
+ B4.add_child(B4a)
1172
+ B4.add_child(B4b)
1173
+ B4.add_child(B4c)
1174
+
1175
+ # Historical Context children
1176
+ B5a = ThoughtNode('Previous Attempts')
1177
+ B5b = ThoughtNode('Lessons Learned')
1178
+ B5c = ThoughtNode('Environmental Factors')
1179
+ B5.add_child(B5a)
1180
+ B5.add_child(B5b)
1181
+ B5.add_child(B5c)
1182
+
1183
+ # Problem Analysis children
1184
+ C1 = ThoughtNode('Root Cause Analysis')
1185
+ C2 = ThoughtNode('System Mapping')
1186
+ C3 = ThoughtNode('Data Collection')
1187
+ C4 = ThoughtNode('Impact Assessment')
1188
+ C5 = ThoughtNode('Theoretical Framework')
1189
+ problem_analysis.add_child(C1)
1190
+ problem_analysis.add_child(C2)
1191
+ problem_analysis.add_child(C3)
1192
+ problem_analysis.add_child(C4)
1193
+ problem_analysis.add_child(C5)
1194
+
1195
+ # Root Cause Analysis children
1196
+ C1a = ThoughtNode('5 Whys Technique')
1197
+ C1b = ThoughtNode('Fishbone Diagram')
1198
+ C1c = ThoughtNode('Pareto Analysis')
1199
+ C1.add_child(C1a)
1200
+ C1.add_child(C1b)
1201
+ C1.add_child(C1c)
1202
+
1203
+ # System Mapping children
1204
+ C2a = ThoughtNode('Causal Loop Diagrams')
1205
+ C2b = ThoughtNode('Stock and Flow Models')
1206
+ C2c = ThoughtNode('Network Analysis')
1207
+ C2.add_child(C2a)
1208
+ C2.add_child(C2b)
1209
+ C2.add_child(C2c)
1210
+
1211
+ # Data Collection children
1212
+ C3a = ThoughtNode('Quantitative Data')
1213
+ C3b = ThoughtNode('Qualitative Data')
1214
+ C3c = ThoughtNode('Data Validation')
1215
+ C3.add_child(C3a)
1216
+ C3.add_child(C3b)
1217
+ C3.add_child(C3c)
1218
+
1219
+ # Quantitative Data children
1220
+ C3a1 = ThoughtNode('Surveys and Questionnaires')
1221
+ C3a2 = ThoughtNode('Experimental Data')
1222
+ C3a3 = ThoughtNode('Big Data Analytics')
1223
+ C3a.add_child(C3a1)
1224
+ C3a.add_child(C3a2)
1225
+ C3a.add_child(C3a3)
1226
+
1227
+ # Qualitative Data children
1228
+ C3b1 = ThoughtNode('Interviews')
1229
+ C3b2 = ThoughtNode('Focus Groups')
1230
+ C3b3 = ThoughtNode('Observational Studies')
1231
+ C3b.add_child(C3b1)
1232
+ C3b.add_child(C3b2)
1233
+ C3b.add_child(C3b3)
1234
+
1235
+ # Data Validation children
1236
+ C3c1 = ThoughtNode('Statistical Validation')
1237
+ C3c2 = ThoughtNode('Cross-Validation')
1238
+ C3c3 = ThoughtNode('Expert Review')
1239
+ C3c.add_child(C3c1)
1240
+ C3c.add_child(C3c2)
1241
+ C3c.add_child(C3c3)
1242
+
1243
+ # Impact Assessment children
1244
+ C4a = ThoughtNode('Environmental Impact')
1245
+ C4b = ThoughtNode('Social Impact')
1246
+ C4c = ThoughtNode('Economic Impact')
1247
+ C4.add_child(C4a)
1248
+ C4.add_child(C4b)
1249
+ C4.add_child(C4c)
1250
+
1251
+ # Theoretical Framework children
1252
+ C5a = ThoughtNode('Literature Review')
1253
+ C5b = ThoughtNode('Conceptual Modeling')
1254
+ C5c = ThoughtNode('Hypothesis Formation')
1255
+ C5.add_child(C5a)
1256
+ C5.add_child(C5b)
1257
+ C5.add_child(C5c)
1258
+
1259
+ # Solution Generation children
1260
+ D1 = ThoughtNode('Creative Problem Solving')
1261
+ D2 = ThoughtNode('Analytical Approach')
1262
+ D3 = ThoughtNode('Mathematical Computation')
1263
+ D4 = ThoughtNode('Decision Making')
1264
+ solution_generation.add_child(D1)
1265
+ solution_generation.add_child(D2)
1266
+ solution_generation.add_child(D3)
1267
+ solution_generation.add_child(D4)
1268
+
1269
+ # Action Planning, Resource Allocation, Change Management children (implementation phase)
1270
+ E1 = ThoughtNode('Action Planning')
1271
+ E2 = ThoughtNode('Resource Allocation')
1272
+ E3 = ThoughtNode('Change Management')
1273
+ implementation.add_child(E1)
1274
+ implementation.add_child(E2)
1275
+ implementation.add_child(E3)
1276
+
1277
+ # Verification, Performance Metrics, Feedback Loops, Continuous Improvement children (evaluation phase)
1278
+ F1 = ThoughtNode('Verification')
1279
+ F2 = ThoughtNode('Performance Metrics')
1280
+ F3 = ThoughtNode('Feedback Loops')
1281
+ F4 = ThoughtNode('Continuous Improvement')
1282
+ evaluation_adjustment.add_child(F1)
1283
+ evaluation_adjustment.add_child(F2)
1284
+ evaluation_adjustment.add_child(F3)
1285
+ evaluation_adjustment.add_child(F4)
1286
+
1287
+ # Cross-Cutting Considerations children
1288
+ G = ThoughtNode('Cross-Cutting Considerations')
1289
+ root.add_child(G)
1290
+
1291
+ # Cross-Cutting Considerations children
1292
+ G1 = ThoughtNode('Ethical Framework')
1293
+ G2 = ThoughtNode('Stakeholder Management')
1294
+ G3 = ThoughtNode('Interdisciplinary Connections')
1295
+ G4 = ThoughtNode('Technological Integration')
1296
+ G5 = ThoughtNode('Emotional Intelligence')
1297
+ G6 = ThoughtNode('Collaborative Problem Solving')
1298
+ G7 = ThoughtNode('Computational Considerations') # Assuming H was intended as G7
1299
+ G8 = ThoughtNode('Order of Operations') # Assuming I was intended as G8
1300
+ G9 = ThoughtNode('Critical Thinking') # Assuming J was intended as G9
1301
+ G10 = ThoughtNode('Future Perspective') # Assuming K was intended as G10
1302
+ G11 = ThoughtNode('Learning and Adaptation') # Assuming L was intended as G11
1303
+ G.add_child(G1)
1304
+ G.add_child(G2)
1305
+ G.add_child(G3)
1306
+ G.add_child(G4)
1307
+ G.add_child(G5)
1308
+ G.add_child(G6)
1309
+ G.add_child(G7)
1310
+ G.add_child(G8)
1311
+ G.add_child(G9)
1312
+ G.add_child(G10)
1313
+ G.add_child(G11)
1314
+
1315
+ # Ethical Framework children
1316
+ G1a = ThoughtNode('Value-based Decision Making')
1317
+ G1b = ThoughtNode('Long-term Consequences')
1318
+ G1.add_child(G1a)
1319
+ G1.add_child(G1b)
1320
+
1321
+ # Value-based Decision Making children
1322
+ G1a1 = ThoughtNode('Ethical Theories Application')
1323
+ G1a2 = ThoughtNode('Moral Dilemma Resolution')
1324
+ G1a.add_child(G1a1)
1325
+ G1a.add_child(G1a2)
1326
+
1327
+ # Long-term Consequences children
1328
+ G1b1 = ThoughtNode('Sustainability Assessment')
1329
+ G1b2 = ThoughtNode('Intergenerational Impact')
1330
+ G1b.add_child(G1b1)
1331
+ G1b.add_child(G1b2)
1332
+
1333
+ # Stakeholder Management children
1334
+ G2a = ThoughtNode('Direct Stakeholders')
1335
+ G2b = ThoughtNode('Indirect Stakeholders')
1336
+ G2c = ThoughtNode('Conflicting Interests')
1337
+ G2.add_child(G2a)
1338
+ G2.add_child(G2b)
1339
+ G2.add_child(G2c)
1340
+
1341
+ # Conflicting Interests children
1342
+ G2c1 = ThoughtNode('Negotiation Strategies')
1343
+ G2c2 = ThoughtNode('Conflict Resolution Techniques')
1344
+ G2c.add_child(G2c1)
1345
+ G2c.add_child(G2c2)
1346
+
1347
+ # Interdisciplinary Connections children
1348
+ G3a = ThoughtNode('Related Fields')
1349
+ G3b = ThoughtNode('Cross-disciplinary Impact')
1350
+ G3.add_child(G3a)
1351
+ G3.add_child(G3b)
1352
+
1353
+ # Related Fields children
1354
+ G3a1 = ThoughtNode('Cross-domain Knowledge Transfer')
1355
+ G3a2 = ThoughtNode('Interdisciplinary Collaboration')
1356
+ G3a.add_child(G3a1)
1357
+ G3a.add_child(G3a2)
1358
+
1359
+ # Cross-disciplinary Impact children
1360
+ G3b1 = ThoughtNode('Synergy Identification')
1361
+ G3b2 = ThoughtNode('Holistic Impact Assessment')
1362
+ G3b.add_child(G3b1)
1363
+ G3b.add_child(G3b2)
1364
+
1365
+ # Technological Integration children
1366
+ G4a = ThoughtNode('AI-assisted Problem Solving')
1367
+ G4b = ThoughtNode('Data-driven Insights')
1368
+ G4c = ThoughtNode('Digital Collaboration Tools')
1369
+ G4.add_child(G4a)
1370
+ G4.add_child(G4b)
1371
+ G4.add_child(G4c)
1372
+
1373
+ # AI-assisted Problem Solving children
1374
+ G4a1 = ThoughtNode('Machine Learning Models')
1375
+ G4a2 = ThoughtNode('Natural Language Processing')
1376
+ G4a.add_child(G4a1)
1377
+ G4a.add_child(G4a2)
1378
+
1379
+ # Data-driven Insights children
1380
+ G4b1 = ThoughtNode('Big Data Analytics')
1381
+ G4b2 = ThoughtNode('Predictive Modeling')
1382
+ G4b.add_child(G4b1)
1383
+ G4b.add_child(G4b2)
1384
+
1385
+ # Digital Collaboration Tools children
1386
+ G4c1 = ThoughtNode('Project Management Platforms')
1387
+ G4c2 = ThoughtNode('Virtual Reality Collaboration')
1388
+ G4c.add_child(G4c1)
1389
+ G4c.add_child(G4c2)
1390
+
1391
+ # Emotional Intelligence children
1392
+ G5a = ThoughtNode('Self-Awareness')
1393
+ G5b = ThoughtNode('Empathy')
1394
+ G5c = ThoughtNode('Stress Management')
1395
+ G5.add_child(G5a)
1396
+ G5.add_child(G5b)
1397
+ G5.add_child(G5c)
1398
+
1399
+ # Self-Awareness children
1400
+ G5a1 = ThoughtNode('Emotional Recognition')
1401
+ G5a2 = ThoughtNode('Personal Bias Identification')
1402
+ G5a.add_child(G5a1)
1403
+ G5a.add_child(G5a2)
1404
+
1405
+ # Empathy children
1406
+ G5b1 = ThoughtNode('Perspective Taking')
1407
+ G5b2 = ThoughtNode('Active Listening')
1408
+ G5b.add_child(G5b1)
1409
+ G5b.add_child(G5b2)
1410
+
1411
+ # Stress Management children
1412
+ G5c1 = ThoughtNode('Mindfulness Techniques')
1413
+ G5c2 = ThoughtNode('Resilience Building')
1414
+ G5c.add_child(G5c1)
1415
+ G5c.add_child(G5c2)
1416
+
1417
+ # Collaborative Problem Solving children
1418
+ G6a = ThoughtNode('Team Dynamics')
1419
+ G6b = ThoughtNode('Communication Strategies')
1420
+ G6c = ThoughtNode('Conflict Resolution')
1421
+ G6.add_child(G6a)
1422
+ G6.add_child(G6b)
1423
+ G6.add_child(G6c)
1424
+
1425
+ # Team Dynamics children
1426
+ G6a1 = ThoughtNode('Team Formation Strategies')
1427
+ G6a2 = ThoughtNode('Role Assignment')
1428
+ G6a.add_child(G6a1)
1429
+ G6a.add_child(G6a2)
1430
+
1431
+ # Communication Strategies children
1432
+ G6b1 = ThoughtNode('Clear Messaging')
1433
+ G6b2 = ThoughtNode('Feedback Mechanisms')
1434
+ G6b.add_child(G6b1)
1435
+ G6b.add_child(G6b2)
1436
+
1437
+ # Conflict Resolution children
1438
+ G6c1 = ThoughtNode('Mediation Techniques')
1439
+ G6c2 = ThoughtNode('Consensus Building')
1440
+ G6c.add_child(G6c1)
1441
+ G6c.add_child(G6c2)
1442
+
1443
+ # Computational Considerations children
1444
+ G7a = ThoughtNode('CPU Operations')
1445
+ G7b = ThoughtNode('GPU Parallelization')
1446
+ G7c = ThoughtNode('Floating-Point Precision')
1447
+ G7.add_child(G7a)
1448
+ G7.add_child(G7b)
1449
+ G7.add_child(G7c)
1450
+
1451
+ # CPU Operations children
1452
+ G7a1 = ThoughtNode('Instruction Set Architecture')
1453
+ G7a2 = ThoughtNode('Pipelining and Parallelism')
1454
+ G7a.add_child(G7a1)
1455
+ G7a.add_child(G7a2)
1456
+
1457
+ # GPU Parallelization children
1458
+ G7b1 = ThoughtNode('CUDA Programming')
1459
+ G7b2 = ThoughtNode('OpenCL Framework')
1460
+ G7b.add_child(G7b1)
1461
+ G7b.add_child(G7b2)
1462
+
1463
+ # Floating-Point Precision children
1464
+ G7c1 = ThoughtNode('IEEE 754 Standard')
1465
+ G7c2 = ThoughtNode('Error Propagation Analysis')
1466
+ G7c.add_child(G7c1)
1467
+ G7c.add_child(G7c2)
1468
+
1469
+ # Order of Operations children
1470
+ G8a = ThoughtNode('Parentheses')
1471
+ G8b = ThoughtNode('Exponents')
1472
+ G8c = ThoughtNode('Multiplication and Division')
1473
+ G8d = ThoughtNode('Addition and Subtraction')
1474
+ G8.add_child(G8a)
1475
+ G8.add_child(G8b)
1476
+ G8.add_child(G8c)
1477
+ G8.add_child(G8d)
1478
+
1479
+ # Critical Thinking children
1480
+ G9a = ThoughtNode('Assumptions Questioning')
1481
+ G9b = ThoughtNode('Bias Recognition')
1482
+ G9.add_child(G9a)
1483
+ G9.add_child(G9b)
1484
+
1485
+ # Assumptions Questioning children
1486
+ G9a1 = ThoughtNode('Socratic Questioning')
1487
+ G9a2 = ThoughtNode('Devil\'s Advocate Approach')
1488
+ G9a.add_child(G9a1)
1489
+ G9a.add_child(G9a2)
1490
+
1491
+ # Bias Recognition children
1492
+ G9b1 = ThoughtNode('Cognitive Bias Identification')
1493
+ G9b2 = ThoughtNode('Debiasing Techniques')
1494
+ G9b.add_child(G9b1)
1495
+ G9b.add_child(G9b2)
1496
+
1497
+ # Future Perspective children
1498
+ G10a = ThoughtNode('Short-term Projections')
1499
+ G10b = ThoughtNode('Long-term Scenarios')
1500
+ G10c = ThoughtNode('Potential Impacts')
1501
+ G10.add_child(G10a)
1502
+ G10.add_child(G10b)
1503
+ G10.add_child(G10c)
1504
+
1505
+ # Short-term Projections children
1506
+ G10a1 = ThoughtNode('Trend Analysis')
1507
+ G10a2 = ThoughtNode('Scenario Planning')
1508
+ G10a.add_child(G10a1)
1509
+ G10a.add_child(G10a2)
1510
+
1511
+ # Long-term Scenarios children
1512
+ G10b1 = ThoughtNode('Futures Wheel')
1513
+ G10b2 = ThoughtNode('Backcasting')
1514
+ G10b.add_child(G10b1)
1515
+ G10b.add_child(G10b2)
1516
+
1517
+ # Potential Impacts children
1518
+ G10c1 = ThoughtNode('Risk Assessment')
1519
+ G10c2 = ThoughtNode('Opportunity Identification')
1520
+ G10c.add_child(G10c1)
1521
+ G10c.add_child(G10c2)
1522
+
1523
+ # Learning and Adaptation children
1524
+ G11a = ThoughtNode('Reflective Practice')
1525
+ G11b = ThoughtNode('Knowledge Transfer')
1526
+ G11c = ThoughtNode('Adaptive Problem Solving')
1527
+ G11.add_child(G11a)
1528
+ G11.add_child(G11b)
1529
+ G11.add_child(G11c)
1530
+
1531
+ # Reflective Practice children
1532
+ G11a1 = ThoughtNode('After Action Review')
1533
+ G11a2 = ThoughtNode('Learning Journals')
1534
+ G11a.add_child(G11a1)
1535
+ G11a.add_child(G11a2)
1536
+
1537
+ # Knowledge Transfer children
1538
+ G11b1 = ThoughtNode('Best Practice Documentation')
1539
+ G11b2 = ThoughtNode('Mentoring Programs')
1540
+ G11b.add_child(G11b1)
1541
+ G11b.add_child(G11b2)
1542
+
1543
+ # Adaptive Problem Solving children
1544
+ G11c1 = ThoughtNode('Iterative Approaches')
1545
+ G11c2 = ThoughtNode('Flexibility in Methodology')
1546
+ G11c.add_child(G11c1)
1547
+ G11c.add_child(G11c2)
1548
+
1549
+ return root
1550
+
1551
+ def traverse_tree(node, action_list):
1552
+ if node.name not in action_list:
1553
+ action_list.append(node.name)
1554
+ for child in node.children:
1555
+ traverse_tree(child, action_list)
1556
+
1557
+
1558
+
1559
+ def infer(query, world_model_components, root_thought_node, tokenizer, max_length=2000, inference_mode='world_model', beam_size=5, n_tokens_predict=3, mcts_iterations=10, exploration_constant=1.414):
1560
+
1561
+
1562
+ """
1563
+ Perform inference given a query, utilizing the Tree of Thought and MCTS with multi-token beam search.
1564
+
1565
+ Args:
1566
+ query (str): The input query or prompt.
1567
+ world_model_components (tuple): Tuple containing the model components.
1568
+ root_thought_node (ThoughtNode): The root node of the Tree of Thought.
1569
+ tokenizer (transformers.PreTrainedTokenizer): The tokenizer used.
1570
+ max_length (int): Maximum length for the generated sequence.
1571
+ inference_mode (str): Inference mode ('world_model', 'without_world_model', 'world_model_tree_of_thought')
1572
+ beam_size (int): Size of the beam for beam search
1573
+ n_tokens_predict (int): Number of tokens to predict at each step
1574
+
1575
+ Returns:
1576
+ List[str] or str: The sequence of actions (thoughts) selected or generated text.
1577
+ """
1578
+ representation_network, dynamics_network, prediction_network, action_encoder, ppo_agent, model_transformer = world_model_components
1579
+
1580
+ # Tokenize and encode the query
1581
+ input_ids = tokenizer.encode(query, return_tensors='pt').to(device)
1582
+ attention_mask = (input_ids != tokenizer.pad_token_id).long()
1583
+
1584
+ if inference_mode == 'without_world_model':
1585
+ # Directly use the transformer model to generate text with beam search
1586
+ with torch.no_grad():
1587
+ generated_sequences = model_transformer.generate_with_beam_search(
1588
+ src=input_ids,
1589
+ tokenizer=tokenizer,
1590
+ beam_size=beam_size,
1591
+ max_length=max_length,
1592
+ n_tokens_predict=n_tokens_predict,
1593
+ temperature=args.temperature
1594
+ )
1595
+ best_sequence, best_score = generated_sequences[0]
1596
+ generated_text = tokenizer.decode(best_sequence[0], skip_special_tokens=True)
1597
+ return generated_text
1598
+
1599
+ else:
1600
+ # Use the world model components
1601
+ with torch.no_grad():
1602
+ transformer_output = model_transformer(input_ids, input_ids)
1603
+ # Get the initial state representation
1604
+ initial_representation = representation_network(transformer_output) # Shape: (batch_size=1, seq_len, state_dim)
1605
+ initial_representation = initial_representation[:, -1, :].unsqueeze(1) # Shape: (batch_size=1, 1, state_dim)
1606
+ initial_state = State(
1607
+ representation=initial_representation,
1608
+ dynamics_network=dynamics_network,
1609
+ action_encoder=action_encoder,
1610
+ thought_node=root_thought_node
1611
+ )
1612
+ if inference_mode == 'world_model_tree_of_thought':
1613
+ # Use MCTS with Tree of Thought and multi-token beam search
1614
+ mcts = MCTS(prediction_network, dynamics_network, action_encoder, num_iterations=mcts_iterations, exploration_constant=exploration_constant)
1615
+
1616
+ current_state = initial_state
1617
+ thought_sequence = []
1618
+
1619
+ for _ in range(max_length // n_tokens_predict):
1620
+ best_actions = mcts.search_with_beam(current_state)
1621
+
1622
+ thought_sequence.extend(best_actions)
1623
+
1624
+ # Apply the best actions to get the next state
1625
+ for action in best_actions:
1626
+ current_state = current_state.apply_action(action)
1627
+
1628
+ # Check if we've reached a leaf node (no further actions)
1629
+ if len(current_state.thought_node.children) == 0:
1630
+ break
1631
+
1632
+ return thought_sequence
1633
+ else:
1634
+ # Use the world model without Tree of Thought, but with multi-token beam search
1635
+ beam = [(initial_state, 0.0, torch.zeros(1, device=device), torch.zeros(1, device=device))] # (state, score, cum_entropy, cum_variance)
1636
+
1637
+ for _ in range(max_length // n_tokens_predict):
1638
+ all_candidates = []
1639
+ for state, score, cum_entropy, cum_variance in beam:
1640
+ policy_logits, _ = prediction_network(state.representation)
1641
+ probs = F.softmax(policy_logits / args.temperature, dim=-1)
1642
+ entropy = -torch.sum(probs * torch.log(probs + 1e-9), dim=-1)
1643
+ variance = torch.var(probs, dim=-1)
1644
+
1645
+ topk_probs, topk_indices = torch.topk(probs, k=beam_size, dim=-1)
1646
+
1647
+ for i in range(beam_size ** n_tokens_predict):
1648
+ indices = [i // (beam_size ** j) % beam_size for j in range(n_tokens_predict)]
1649
+ new_actions = [index_to_action[topk_indices[0, j, indices[j]].item()] for j in range(n_tokens_predict)]
1650
+ new_score = score + torch.sum(torch.log(topk_probs[0, range(n_tokens_predict), indices]))
1651
+ new_entropy = cum_entropy + torch.sum(entropy[0, indices])
1652
+ new_variance = cum_variance + torch.sum(variance[0, indices])
1653
+
1654
+ new_state = state
1655
+ for action in new_actions:
1656
+ new_state = new_state.apply_action(action)
1657
+
1658
+ all_candidates.append((new_state, new_score, new_entropy, new_variance, new_actions))
1659
+
1660
+ # Select top beam_size candidates
1661
+ beam = sorted(all_candidates, key=lambda x: x[1] - 0.1 * x[2] + 0.05 * x[3], reverse=True)[:beam_size]
1662
+
1663
+ # Accumulate actions
1664
+ if not thought_sequence:
1665
+ thought_sequence = [b[4] for b in beam]
1666
+ else:
1667
+ for i, b in enumerate(beam):
1668
+ thought_sequence[i].extend(b[4])
1669
+
1670
+ # Return the top sequence
1671
+ return thought_sequence[0]
1672
+
1673
+
1674
+ def train_epoch_world_model(world_model_components, train_loader, optimizer, scheduler, scaler, args, model_transformer, state_dim, embed_dim, input_dim):
1675
+ representation_network, dynamics_network, prediction_network, action_encoder, ppo_agent, _ = world_model_components
1676
+ representation_network.train()
1677
+ dynamics_network.train()
1678
+ prediction_network.train()
1679
+ action_encoder.train()
1680
+ ppo_agent.policy_network.train()
1681
+
1682
+ total_loss = 0.0
1683
+ optimizer.zero_grad()
1684
+ print(f"Starting World Model training epoch with {len(train_loader)} batches...")
1685
+
1686
+ for i, batch in enumerate(train_loader):
1687
+ print(f"Processing batch {i+1}/{len(train_loader)}...")
1688
+
1689
+ # Move batches to the device
1690
+ src_batch = batch['input_ids'].to(device)
1691
+ tgt_batch = batch['labels'].to(device)
1692
+
1693
+ with torch.amp.autocast(device_type='cuda'):
1694
+ print("Forward pass through Transformer (frozen)...")
1695
+ with torch.no_grad():
1696
+ transformer_output = model_transformer(src_batch, tgt_batch[:, :-1])
1697
+
1698
+ # World Model - Representation
1699
+ state_representation = representation_network(transformer_output)
1700
+
1701
+ # For simplicity, let's assume true actions are provided (e.g., next tokens)
1702
+ true_actions = tgt_batch[:, :-1]
1703
+ action_sequences = true_actions
1704
+
1705
+ # Get action embeddings
1706
+ action_embeddings = action_encoder(action_sequences)
1707
+
1708
+ # Apply dynamics network
1709
+ predicted_next_state_batch = dynamics_network(state_representation, action_embeddings)
1710
+
1711
+ # Prediction Network - Policy logits and value
1712
+ policy_logits, value_estimates = prediction_network(predicted_next_state_batch)
1713
+
1714
+ # Define true_policy and true_value as placeholders on the GPU
1715
+ true_policy = F.one_hot(true_actions, num_classes=input_dim).float()
1716
+ true_value = torch.zeros_like(value_estimates).to(device)
1717
+
1718
+ # Compute individual losses
1719
+ ppo_loss = ppo_agent.compute_loss(
1720
+ state_representation,
1721
+ torch.zeros_like(true_actions, dtype=torch.float32).to(device),
1722
+ true_actions,
1723
+ torch.zeros_like(value_estimates, dtype=torch.float32).to(device),
1724
+ torch.zeros_like(value_estimates, dtype=torch.float32).to(device)
1725
+ )
1726
+
1727
+ info_nce = InfoNCE_Loss()(
1728
+ state_representation.reshape(-1, state_dim),
1729
+ F.dropout(state_representation.reshape(-1, state_dim), p=0.1, training=True)
1730
+ )
1731
+
1732
+
1733
+ covariance = CovarianceRegularization()(predicted_next_state_batch.view(-1, predicted_next_state_batch.size(-1)))
1734
+ dynamics_loss = DynamicsPerformanceLoss()(state_representation, predicted_next_state_batch)
1735
+
1736
+ perturbed_next_state = predicted_next_state_batch + torch.randn_like(predicted_next_state_batch) * 0.01
1737
+ thought_loss = ThoughtConsistencyLoss()(predicted_next_state_batch, perturbed_next_state)
1738
+
1739
+ pv_loss = PolicyValueJointLoss()(policy_logits, true_policy, value_estimates.squeeze(-1), true_value.squeeze(-1))
1740
+ action_diversity = ActionDiversityReward()(action_embeddings.view(-1, embed_dim))
1741
+
1742
+ mcts_best_values = torch.zeros(true_actions.size(0)).to(device)
1743
+ etv = ExpectedThoughtValueLoss()(mcts_best_values)
1744
+
1745
+ visit_counts = torch.ones(true_actions.size(0), policy_logits.size(-1)).to(device)
1746
+ exploration = ExplorationRegularization()(visit_counts)
1747
+
1748
+ old_policy = F.softmax(policy_logits.detach(), dim=-1)
1749
+ new_policy = F.softmax(policy_logits, dim=-1)
1750
+ kl_loss = KL_DivergenceLoss()(old_policy, new_policy)
1751
+
1752
+ # Total Loss
1753
+ loss = (
1754
+ ppo_loss +
1755
+ info_nce +
1756
+ covariance +
1757
+ dynamics_loss +
1758
+ thought_loss +
1759
+ pv_loss +
1760
+ action_diversity +
1761
+ etv +
1762
+ exploration +
1763
+ kl_loss
1764
+ )
1765
+ loss = loss / args.accumulation_steps
1766
+
1767
+ print("Backward pass...")
1768
+ scaler.scale(loss).backward()
1769
+
1770
+ if (i + 1) % args.accumulation_steps == 0 or (i + 1) == len(train_loader):
1771
+ print("Gradient clipping...")
1772
+ scaler.unscale_(optimizer)
1773
+ torch.nn.utils.clip_grad_norm_(
1774
+ [param for group in optimizer.param_groups for param in group['params']],
1775
+ args.max_grad_norm
1776
+ )
1777
+
1778
+ print("Optimizer step...")
1779
+ scaler.step(optimizer)
1780
+ scaler.update()
1781
+
1782
+ print("Zeroing gradients...")
1783
+ optimizer.zero_grad()
1784
+
1785
+ print("Updating learning rate...")
1786
+ scheduler.step()
1787
+
1788
+ total_loss += loss.item() * args.accumulation_steps
1789
+
1790
+ # Print individual losses and total loss for this batch
1791
+ print(f"Batch {i+1} completed. Losses:")
1792
+ print(f" PPO Loss: {ppo_loss.item():.4f}")
1793
+ print(f" InfoNCE Loss: {info_nce.item():.4f}")
1794
+ print(f" Covariance Loss: {covariance.item():.4f}")
1795
+ print(f" Dynamics Loss: {dynamics_loss.item():.4f}")
1796
+ print(f" Thought Consistency Loss: {thought_loss.item():.4f}")
1797
+ print(f" Policy-Value Loss: {pv_loss.item():.4f}")
1798
+ print(f" Action Diversity Loss: {action_diversity.item():.4f}")
1799
+ print(f" Expected Thought Value Loss: {etv.item():.4f}")
1800
+ print(f" Exploration Loss: {exploration.item():.4f}")
1801
+ print(f" KL Divergence Loss: {kl_loss.item():.4f}")
1802
+ print(f" Total Loss: {loss.item():.4f}")
1803
+
1804
+ avg_loss = total_loss / len(train_loader)
1805
+ print(f"World Model training epoch completed. Average loss: {avg_loss:.4f}")
1806
+ return avg_loss
1807
+
1808
+ def train_epoch_language_model(model, train_loader, optimizer, scheduler, scaler, args):
1809
+ model.train()
1810
+ total_loss = 0.0
1811
+ optimizer.zero_grad()
1812
+ print(f"Starting Language Model training epoch with {len(train_loader)} batches...")
1813
+
1814
+ for i, batch in enumerate(train_loader):
1815
+ input_ids = batch['input_ids'].to(device)
1816
+ labels = batch['labels'].to(device)
1817
+
1818
+ with autocast():
1819
+ outputs = model(input_ids, input_ids)
1820
+ logits = outputs.view(-1, outputs.size(-1))
1821
+ labels = labels.view(-1)
1822
+ loss = F.cross_entropy(logits, labels, ignore_index=model.embedding.padding_idx)
1823
+ loss = loss / args.accumulation_steps
1824
+
1825
+ scaler.scale(loss).backward()
1826
+
1827
+ if (i + 1) % args.accumulation_steps == 0 or (i + 1) == len(train_loader):
1828
+ scaler.unscale_(optimizer)
1829
+ torch.nn.utils.clip_grad_norm_(
1830
+ [param for group in optimizer.param_groups for param in group['params']],
1831
+ args.max_grad_norm
1832
+ )
1833
+ scaler.step(optimizer)
1834
+ scaler.update()
1835
+ optimizer.zero_grad()
1836
+ scheduler.step()
1837
+
1838
+ total_loss += loss.item() * args.accumulation_steps
1839
+ print(f"Batch {i + 1} completed. Current loss: {loss.item():.4f}")
1840
+
1841
+ avg_loss = total_loss / len(train_loader)
1842
+ print(f"Language Model training epoch completed. Average loss: {avg_loss:.4f}")
1843
+ return avg_loss
1844
+
1845
+
1846
+ def train_custom_data_epoch_world_model(world_model_components, train_loader, optimizer, scheduler, scaler, args, model_transformer, state_dim, embed_dim, input_dim):
1847
+ representation_network, dynamics_network, prediction_network, action_encoder, ppo_agent, _ = world_model_components
1848
+ representation_network.train()
1849
+ dynamics_network.train()
1850
+ prediction_network.train()
1851
+ action_encoder.train()
1852
+ ppo_agent.policy_network.train()
1853
+
1854
+ total_loss = 0.0
1855
+ optimizer.zero_grad()
1856
+ print(f"Starting World Model training epoch with {len(train_loader)} batches...")
1857
+
1858
+ for i, batch in enumerate(train_loader):
1859
+ print(f"Processing batch {i+1}/{len(train_loader)}...")
1860
+
1861
+ # Move batches to the device
1862
+ input_ids = batch['input_ids'].to(device)
1863
+ attention_mask = batch['attention_mask'].to(device)
1864
+ episode_reward = batch['episode_reward'].to(device)
1865
+ loss_value = batch['loss'].to(device)
1866
+ cosine_similarity = batch['cosine_similarity'].to(device)
1867
+ rag_performance = batch['rag_performance'].to(device)
1868
+ ranking_model_performance = batch['ranking_model_performance'].to(device)
1869
+
1870
+ with torch.amp.autocast(device_type='cuda'):
1871
+ print("Forward pass through Transformer (frozen)...")
1872
+ with torch.no_grad():
1873
+ transformer_output = model_transformer(input_ids, input_ids)
1874
+
1875
+ # World Model - Representation
1876
+ state_representation = representation_network(transformer_output)
1877
+ print(f"State representation shape: {state_representation.shape}")
1878
+
1879
+ # For simplicity, let's assume true actions are provided (e.g., next tokens)
1880
+ true_actions = input_ids[:, 1:] # Shift input_ids by 1 to get next tokens
1881
+ print(f"True actions shape: {true_actions.shape}")
1882
+ action_sequences = true_actions
1883
+
1884
+ # Get action embeddings
1885
+ action_embeddings = action_encoder(action_sequences)
1886
+ print(f"Action embeddings shape: {action_embeddings.shape}")
1887
+
1888
+ # Ensure state_representation and action_embeddings have the same sequence length
1889
+ min_seq_len = min(state_representation.size(1), action_embeddings.size(1))
1890
+ state_representation = state_representation[:, :min_seq_len, :]
1891
+ action_embeddings = action_embeddings[:, :min_seq_len, :]
1892
+
1893
+ print(f"Adjusted state representation shape: {state_representation.shape}")
1894
+ print(f"Adjusted action embeddings shape: {action_embeddings.shape}")
1895
+
1896
+ # Apply dynamics network
1897
+ predicted_next_state_batch = dynamics_network(state_representation, action_embeddings)
1898
+ print(f"Predicted next state batch shape: {predicted_next_state_batch.shape}")
1899
+
1900
+ # Prediction Network - Policy logits and value
1901
+ policy_logits, value_estimates = prediction_network(predicted_next_state_batch)
1902
+
1903
+ # Adjust true_actions to match the sequence length
1904
+ true_actions = true_actions[:, :min_seq_len]
1905
+
1906
+ # Define true_policy and true_value
1907
+ true_policy = F.one_hot(true_actions, num_classes=input_dim).float()
1908
+ true_value = episode_reward.unsqueeze(1).expand(-1, min_seq_len) # Expand to match sequence length
1909
+
1910
+ # Compute individual losses
1911
+ info_nce = InfoNCE_Loss()(
1912
+ state_representation.reshape(-1, state_dim),
1913
+ F.dropout(state_representation.reshape(-1, state_dim), p=0.1, training=True)
1914
+ )
1915
+
1916
+ covariance = CovarianceRegularization()(predicted_next_state_batch.view(-1, predicted_next_state_batch.size(-1)))
1917
+ dynamics_loss = DynamicsPerformanceLoss()(state_representation, predicted_next_state_batch)
1918
+
1919
+ perturbed_next_state = predicted_next_state_batch + torch.randn_like(predicted_next_state_batch) * 0.01
1920
+ thought_loss = ThoughtConsistencyLoss()(predicted_next_state_batch, perturbed_next_state)
1921
+
1922
+ pv_loss = PolicyValueJointLoss()(policy_logits, true_policy, value_estimates.squeeze(-1), true_value.squeeze(-1))
1923
+ action_diversity = ActionDiversityReward()(action_embeddings.view(-1, embed_dim))
1924
+
1925
+ mcts_best_values = torch.zeros(true_actions.size(0)).to(device)
1926
+ etv = ExpectedThoughtValueLoss()(mcts_best_values)
1927
+
1928
+ visit_counts = torch.ones(true_actions.size(0), policy_logits.size(-1)).to(device)
1929
+ exploration = ExplorationRegularization()(visit_counts)
1930
+
1931
+ old_policy = F.softmax(policy_logits.detach(), dim=-1)
1932
+ new_policy = F.softmax(policy_logits, dim=-1)
1933
+ kl_loss = KL_DivergenceLoss()(old_policy, new_policy)
1934
+
1935
+ # Compute mean value estimates over the sequence length
1936
+ value_estimates_mean = value_estimates.squeeze(-1).mean(dim=1) # Shape: [batch_size]
1937
+
1938
+ # Add new loss components
1939
+ rag_loss = F.mse_loss(value_estimates_mean, rag_performance)
1940
+ ranking_loss = F.mse_loss(value_estimates_mean, ranking_model_performance)
1941
+ cosine_similarity_loss = 1 - cosine_similarity.mean() # Maximize cosine similarity
1942
+
1943
+ # Total Loss
1944
+ loss = (
1945
+ info_nce +
1946
+ covariance +
1947
+ dynamics_loss +
1948
+ thought_loss +
1949
+ pv_loss +
1950
+ action_diversity +
1951
+ etv +
1952
+ exploration +
1953
+ kl_loss +
1954
+ rag_loss +
1955
+ ranking_loss +
1956
+ cosine_similarity_loss
1957
+ )
1958
+ loss = loss / args.accumulation_steps
1959
+
1960
+ print("Backward pass...")
1961
+ scaler.scale(loss).backward()
1962
+
1963
+ if (i + 1) % args.accumulation_steps == 0 or (i + 1) == len(train_loader):
1964
+ print("Gradient clipping...")
1965
+ scaler.unscale_(optimizer)
1966
+ torch.nn.utils.clip_grad_norm_(
1967
+ [param for group in optimizer.param_groups for param in group['params']],
1968
+ args.max_grad_norm
1969
+ )
1970
+
1971
+ print("Optimizer step...")
1972
+ scaler.step(optimizer)
1973
+ scaler.update()
1974
+
1975
+ print("Zeroing gradients...")
1976
+ optimizer.zero_grad()
1977
+
1978
+ print("Updating learning rate...")
1979
+ scheduler.step()
1980
+
1981
+ # Print individual losses and total loss for this batch
1982
+ print(f"Batch {i+1} completed. Losses:")
1983
+ print(f" InfoNCE Loss: {info_nce.item():.4f}")
1984
+ print(f" Covariance Loss: {covariance.item():.4f}")
1985
+ print(f" Dynamics Loss: {dynamics_loss.item():.4f}")
1986
+ print(f" Thought Consistency Loss: {thought_loss.item():.4f}")
1987
+ print(f" Policy-Value Loss: {pv_loss.item():.4f}")
1988
+ print(f" Action Diversity Loss: {action_diversity.item():.4f}")
1989
+ print(f" Expected Thought Value Loss: {etv.item():.4f}")
1990
+ print(f" Exploration Loss: {exploration.item():.4f}")
1991
+ print(f" KL Divergence Loss: {kl_loss.item():.4f}")
1992
+ print(f" RAG Loss: {rag_loss.item():.4f}")
1993
+ print(f" Ranking Loss: {ranking_loss.item():.4f}")
1994
+ print(f" Cosine Similarity Loss: {cosine_similarity_loss.item():.4f}")
1995
+ print(f" Total Loss: {loss.item():.4f}")
1996
+
1997
+ avg_loss = total_loss / len(train_loader)
1998
+ print(f"World Model training epoch completed. Average loss: {avg_loss:.4f}")
1999
+ return avg_loss
2000
+
2001
+
2002
+ def main():
2003
+ args = parse_args()
2004
+ print("Arguments parsed successfully.")
2005
+
2006
+ # Create save directory
2007
+ os.makedirs(args.save_dir, exist_ok=True)
2008
+ print(f"Save directory created: {args.save_dir}")
2009
+
2010
+ # Load tokenizer
2011
+ print("Loading tokenizer...")
2012
+ tokenizer = AutoTokenizer.from_pretrained(args.model_name)
2013
+ if tokenizer.pad_token is None:
2014
+ tokenizer.pad_token = tokenizer.eos_token
2015
+ print("Tokenizer loaded successfully.")
2016
+
2017
+ # Define padding_idx and input dimension based on tokenizer
2018
+ padding_idx = tokenizer.pad_token_id
2019
+ input_dim = len(tokenizer)
2020
+
2021
+
2022
+ # Initialize the Transformer model on GPU
2023
+ print("Initializing Transformer model...")
2024
+ model_transformer = Transformer(
2025
+ input_dim=input_dim,
2026
+ d_model=128,
2027
+ num_heads=4,
2028
+ num_layers=4,
2029
+ d_ff=256,
2030
+ num_experts=2,
2031
+ output_dim=input_dim,
2032
+ dropout=0.1,
2033
+ top_k=2
2034
+ ).to(device)
2035
+ model_transformer.train()
2036
+ print("Transformer model initialized on device.")
2037
+
2038
+ # Define model parameters (adjusted for speed)
2039
+ d_model = 32
2040
+ state_dim = 32
2041
+ action_dim = d_model
2042
+ hidden_dim = 64
2043
+ vocab_dim = input_dim
2044
+ embed_dim = d_model
2045
+
2046
+ # Define World Model components
2047
+ representation_network = RepresentationNetwork(vocab_dim, d_model, state_dim).to(device)
2048
+ dynamics_network = DynamicsNetwork(state_dim, action_dim, hidden_dim).to(device)
2049
+ prediction_network = PredictionNetwork(state_dim, input_dim, 1).to(device)
2050
+ action_encoder = ActionEncoder(input_dim, action_dim).to(device)
2051
+
2052
+ # Initialize PPO Agent
2053
+ ppo_agent = PPOAgent(
2054
+ policy_network=prediction_network,
2055
+ optimizer=optim.AdamW(prediction_network.parameters(), lr=args.learning_rate),
2056
+ clip_epsilon=0.2,
2057
+ entropy_coef=0.01,
2058
+ value_coef=0.5
2059
+ )
2060
+
2061
+ # Bundle World Model components
2062
+ world_model_components = (representation_network, dynamics_network, prediction_network, action_encoder, ppo_agent, model_transformer)
2063
+
2064
+ print(f"Current mode: {args.mode}")
2065
+ if args.mode == 'train':
2066
+ print("Loading and preprocessing data...")
2067
+ if args.use_custom_data:
2068
+ custom_data = load_custom_data_from_files(args.custom_data_paths)
2069
+ processed_data = preprocess_custom_data(custom_data)
2070
+ train_loader, eval_loader = load_custom_data(args, tokenizer, processed_data)
2071
+ print("Custom data loaded and preprocessed successfully.")
2072
+ else:
2073
+ train_loader, eval_loader = load_data(args, tokenizer)
2074
+ print("Default data loaded and preprocessed successfully.")
2075
+
2076
+ # Optimizer and Scheduler
2077
+ optimizer = optim.AdamW(
2078
+ list(representation_network.parameters()) +
2079
+ list(dynamics_network.parameters()) +
2080
+ list(prediction_network.parameters()) +
2081
+ list(action_encoder.parameters()),
2082
+ lr=args.learning_rate, weight_decay=args.weight_decay
2083
+ ) if args.train_mode == 'world_model' else optim.AdamW(model_transformer.parameters(), lr=args.learning_rate)
2084
+ scheduler = CosineAnnealingLR(optimizer, T_max=args.num_epochs)
2085
+ scaler = GradScaler()
2086
+
2087
+ print(f"Starting {args.train_mode} training...")
2088
+
2089
+ for epoch in range(args.num_epochs):
2090
+ if args.train_mode == 'world_model':
2091
+ if args.use_custom_data:
2092
+ avg_loss = train_custom_data_epoch_world_model(
2093
+ world_model_components,
2094
+ train_loader,
2095
+ optimizer,
2096
+ scheduler,
2097
+ scaler,
2098
+ args,
2099
+ model_transformer,
2100
+ state_dim,
2101
+ embed_dim,
2102
+ input_dim
2103
+ )
2104
+ else:
2105
+ avg_loss = train_epoch_world_model(
2106
+ world_model_components,
2107
+ train_loader,
2108
+ optimizer,
2109
+ scheduler,
2110
+ scaler,
2111
+ args,
2112
+ model_transformer,
2113
+ state_dim,
2114
+ embed_dim,
2115
+ input_dim
2116
+ )
2117
+ else:
2118
+ avg_loss = train_epoch_language_model(
2119
+ model_transformer,
2120
+ train_loader,
2121
+ optimizer,
2122
+ scheduler,
2123
+ scaler,
2124
+ args
2125
+ )
2126
+
2127
+ print(f"{args.train_mode.capitalize()} training epoch {epoch + 1} completed. Average loss: {avg_loss:.4f}")
2128
+
2129
+ # Save models
2130
+ if args.train_mode == 'world_model':
2131
+ save_all_models(model_transformer, representation_network, dynamics_network, prediction_network, action_encoder, args.save_dir, epoch + 1)
2132
+ print(f"Models saved for epoch {epoch + 1}")
2133
+ else:
2134
+ torch.save(model_transformer.state_dict(), os.path.join(args.save_dir, f'language_model_epoch_{epoch + 1}.pt'))
2135
+ print(f"Language model saved for epoch {epoch + 1}")
2136
+
2137
+ print("Training completed.")
2138
+
2139
+ elif args.mode == 'inference':
2140
+ print("Entering inference mode...")
2141
+ # Build Tree of Thought if needed
2142
+ print("Building Tree of Thought...")
2143
+ tree_root = build_tree_of_thought()
2144
+ print("Tree of Thought built successfully.")
2145
+
2146
+ # Generate action list
2147
+ print("Generating action list...")
2148
+ action_list = []
2149
+ traverse_tree(tree_root, action_list)
2150
+ print(f"Action list generated. Total actions: {len(action_list)}")
2151
+
2152
+ # Create mappings
2153
+ global action_to_index, index_to_action
2154
+ action_to_index = {action: idx for idx, action in enumerate(action_list)}
2155
+ index_to_action = {idx: action for action, idx in action_to_index.items()}
2156
+ action_vocab_size = len(action_list)
2157
+ print(f"Action mappings created. Vocabulary size: {action_vocab_size}")
2158
+
2159
+ # Initialize or load models based on the load_model argument
2160
+ if args.load_model:
2161
+ print(f"Loading saved model from {args.load_model}")
2162
+ # Load the saved models
2163
+ model_transformer.load_state_dict(torch.load(os.path.join(args.load_model, 'transformer_model.pt')))
2164
+ representation_network.load_state_dict(torch.load(os.path.join(args.load_model, 'representation_network.pt')))
2165
+ dynamics_network.load_state_dict(torch.load(os.path.join(args.load_model, 'dynamics_network.pt')))
2166
+
2167
+ # Load prediction network and adjust its size if necessary
2168
+ saved_state_dict = torch.load(os.path.join(args.load_model, 'prediction_network.pt'))
2169
+ saved_vocab_size = saved_state_dict['policy_head.weight'].size(0)
2170
+ if saved_vocab_size != action_vocab_size:
2171
+ print(f"Adjusting prediction network size from {saved_vocab_size} to {action_vocab_size}")
2172
+ prediction_network = PredictionNetwork(state_dim, saved_vocab_size, 1).to(device)
2173
+ prediction_network.load_state_dict(saved_state_dict)
2174
+ prediction_network.policy_head = nn.Linear(prediction_network.state_dim, action_vocab_size).to(device)
2175
+ else:
2176
+ prediction_network = PredictionNetwork(state_dim, action_vocab_size, 1).to(device)
2177
+ prediction_network.load_state_dict(saved_state_dict)
2178
+
2179
+ action_encoder.load_state_dict(torch.load(os.path.join(args.load_model, 'action_encoder.pt')))
2180
+ else:
2181
+ print("Using newly initialized models")
2182
+
2183
+ # Prepare the components
2184
+ world_model_components = (representation_network, dynamics_network, prediction_network, action_encoder, ppo_agent, model_transformer)
2185
+
2186
+ print("Starting inference loop...")
2187
+ while True:
2188
+ if args.query:
2189
+ query = args.query
2190
+ args.query = None # Reset query for next iteration
2191
+ else:
2192
+ query = input("Please enter your query (or type 'exit' to quit): ")
2193
+ if query.lower() == 'exit':
2194
+ break
2195
+
2196
+ print(f"Processing query: {query}")
2197
+ result = infer(query, world_model_components, tree_root, tokenizer,
2198
+ max_length=args.max_length,
2199
+ inference_mode=args.inference_mode,
2200
+ beam_size=args.beam_size,
2201
+ n_tokens_predict=args.n_tokens_predict,
2202
+ mcts_iterations=args.mcts_iterations,
2203
+ exploration_constant=args.mcts_exploration_constant)
2204
+
2205
+
2206
+ if args.inference_mode == 'without_world_model':
2207
+ print("Generated Text:")
2208
+ print(result)
2209
+ else:
2210
+ print("Generated Thought Sequence:")
2211
+ for thought in result:
2212
+ print(thought)
2213
+
2214
+ print("\n") # Add a newline for better readability between queries
2215
+
2216
+ print("Inference completed.")
2217
+
2218
+ else:
2219
+ print(f"Invalid mode: {args.mode}. Please choose 'train' or 'inference'.")
2220
+ if __name__ == '__main__':
2221
+ sys.argv = [
2222
+ 'lightbulb_2.py',
2223
+ '--mode', 'inference',
2224
+ '--train_mode', 'world_model', # Set 'world_model' or 'language_model' depending on the training mode
2225
+ '--dataset_name', 'wikitext', # Specify the Hugging Face dataset (e.g., 'wikitext')
2226
+ '--dataset_config', 'wikitext-2-raw-v1', # Use if you need a specific config of the dataset
2227
+ '--num_epochs', '10',
2228
+ '--batch_size', '4',
2229
+ '--accumulation_steps', '1',
2230
+ '--max_grad_norm', '1.0',
2231
+ '--weight_decay', '0.01',
2232
+ '--learning_rate', '1e-4',
2233
+ '--max_length', '512',
2234
+ '--save_dir', './trained_models',
2235
+ # Uncomment the following line to use custom data instead of a Hugging Face dataset
2236
+ #'--use_custom_data',
2237
+ '--custom_data_paths', '/content/drive/MyDrive/lightbulb/knowledge_base.json',
2238
+ '--custom_data_paths', '/content/drive/MyDrive/lightbulb/rag_cache.json',
2239
+ '--custom_data_paths', '/content/drive/MyDrive/lightbulb/llm_training_data/llm_training_data.jsonl'
2240
+ ]
2241
+
2242
+ # Parse the arguments and run the main training function
2243
+ args = parse_args()
2244
+
2245
+ # Check which data source to use
2246
+ if args.use_custom_data:
2247
+ print("Training with custom data from paths:")
2248
+ for path in args.custom_data_paths:
2249
+ print(f" - {path}")
2250
+ else:
2251
+ print(f"Training with dataset '{args.dataset_name}' from Hugging Face Datasets")
2252
+
2253
+ main()
2254
+