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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Background training for CogNet - resumes from checkpoint, trains N steps, saves."""
|
| 3 |
+
import sys, os, time, math, random, json
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
| 7 |
+
from cognet_1b import CogNet1B
|
| 8 |
+
from infer import CharTokenizer
|
| 9 |
+
|
| 10 |
+
CKPT_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'checkpoints')
|
| 11 |
+
N_STEPS = int(sys.argv[1]) if len(sys.argv) > 1 else 500
|
| 12 |
+
LOG_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'train_bg.log')
|
| 13 |
+
|
| 14 |
+
def log(msg):
|
| 15 |
+
with open(LOG_FILE, 'a') as f:
|
| 16 |
+
f.write(f'[{time.strftime("%H:%M:%S")}] {msg}\n')
|
| 17 |
+
print(msg, flush=True)
|
| 18 |
+
|
| 19 |
+
# Generate training data from diverse text
|
| 20 |
+
def make_training_data(tokenizer):
|
| 21 |
+
texts = []
|
| 22 |
+
# English texts
|
| 23 |
+
for _ in range(200):
|
| 24 |
+
texts.append("The quick brown fox jumps over the lazy dog. ")
|
| 25 |
+
texts.append("In the beginning there was the word and the word was good. ")
|
| 26 |
+
texts.append("Science tells us that the universe is vast and beautiful. ")
|
| 27 |
+
texts.append("Once upon a time there lived a king who ruled over a great kingdom. ")
|
| 28 |
+
texts.append("Knowledge is power and understanding is the key to wisdom. ")
|
| 29 |
+
texts.append("CogNet is a non-transformer language model with cognitive routing. ")
|
| 30 |
+
texts.append("The model processes sequences in linear time making it efficient. ")
|
| 31 |
+
texts.append("It has hierarchical memory with working episodic and semantic slots. ")
|
| 32 |
+
texts.append("This design enables contextual information without quadratic costs. ")
|
| 33 |
+
texts.append("The future of artificial intelligence is bright and full of possibilities. ")
|
| 34 |
+
texts.append("In the depth of winter I finally learned that within me there lay an invincible summer. ")
|
| 35 |
+
texts.append("The architecture consists of six adaptive computation blocks. ")
|
| 36 |
+
texts.append("Memory is organized in three tiers for efficient processing. ")
|
| 37 |
+
texts.append("CogNet replaces self-attention with O(n) cognitive routing. ")
|
| 38 |
+
texts.append("The model was trained on a CPU only machine demonstrating novel architectures. ")
|
| 39 |
+
texts.append("Hello world this is a test of the CogNet language model. ")
|
| 40 |
+
texts.append("The king sat on his throne and looked out over his kingdom with pride. ")
|
| 41 |
+
texts.append("A journey of a thousand miles begins with a single step forward. ")
|
| 42 |
+
texts.append("To be or not to be that is the question that puzzles many minds. ")
|
| 43 |
+
texts.append("The sun rose over the mountains casting long shadows across the valley. ")
|
| 44 |
+
# French texts
|
| 45 |
+
for _ in range(100):
|
| 46 |
+
texts.append("Bonjour le monde est beau et la science est merveilleuse. ")
|
| 47 |
+
texts.append("Le futur de l'intelligence artificielle est prometteur. ")
|
| 48 |
+
texts.append("Dans le profondeur de l'hiver j'ai appris qu'en moi habitait un été invincible. ")
|
| 49 |
+
texts.append("Le roi siégeait sur son trône et regardait son royaume avec fierté. ")
|
| 50 |
+
texts.append("La connaissance est le pouvoir et la compréhension est la clé de la sagesse. ")
|
| 51 |
+
texts.append("CogNet est un modèle de langage non-transformateur avec routage cognitif. ")
|
| 52 |
+
texts.append("Une voyage de mille lieues commence par un seul pas en avant. ")
|
| 53 |
+
texts.append("Le soleil s'est levé sur les montagnes projetant de longues ombres. ")
|
| 54 |
+
texts.append("La liberté est le droit de faire tout ce que les lois permettent. ")
|
| 55 |
+
texts.append("La musique est le langage universel de l'humanité toute entière. ")
|
| 56 |
+
|
| 57 |
+
all_text = ''.join(texts)
|
| 58 |
+
ids = tokenizer.encode(all_text)
|
| 59 |
+
return torch.tensor(ids, dtype=torch.long)
|
| 60 |
+
|
| 61 |
+
# Load tokenizer
|
| 62 |
+
tokenizer = CharTokenizer.load(os.path.join(CKPT_DIR, 'tokenizer_v3.json'))
|
| 63 |
+
log(f'Tokenizer: {tokenizer.vocab_size} chars')
|
| 64 |
+
|
| 65 |
+
# Create model
|
| 66 |
+
model = CogNet1B(vocab_size=tokenizer.vocab_size, hidden_dim=512, num_blocks=6,
|
| 67 |
+
num_channels=6, channel_dim=128, ff_dim=1024, routing_iters=1,
|
| 68 |
+
max_adaptive_steps=2, max_seq_len=192, working_slots=32,
|
| 69 |
+
episodic_slots=64, semantic_slots=128, key_dim=256, dropout=0.1)
|
| 70 |
+
|
| 71 |
+
# Resume from checkpoint
|
| 72 |
+
start_step = 0
|
| 73 |
+
best_val = float('inf')
|
| 74 |
+
ckpt_path = os.path.join(CKPT_DIR, 'cognet_best.pt')
|
| 75 |
+
if os.path.exists(ckpt_path):
|
| 76 |
+
ckpt = torch.load(ckpt_path, map_location='cpu', weights_only=False)
|
| 77 |
+
state = ckpt['model_state_dict']
|
| 78 |
+
fp16_state = {k: v.float() if v.dtype == torch.float16 else v for k, v in state.items()}
|
| 79 |
+
model.load_state_dict(fp16_state)
|
| 80 |
+
start_step = ckpt.get('metrics', {}).get('step', 0)
|
| 81 |
+
best_val = ckpt.get('metrics', {}).get('val_loss', float('inf'))
|
| 82 |
+
log(f'Resumed from step {start_step}, best_val={best_val:.4f}')
|
| 83 |
+
|
| 84 |
+
# Training data
|
| 85 |
+
train_ids = make_training_data(tokenizer)
|
| 86 |
+
log(f'Training data: {len(train_ids):,} tokens')
|
| 87 |
+
|
| 88 |
+
# Optimizer
|
| 89 |
+
optimizer = torch.optim.AdamW(model.parameters(), lr=5e-4, weight_decay=0.01, betas=(0.9, 0.95))
|
| 90 |
+
COSINE_END = 10000
|
| 91 |
+
|
| 92 |
+
def lr_lambda(step):
|
| 93 |
+
s = step + start_step
|
| 94 |
+
if s < 200: return s / 200
|
| 95 |
+
if s >= COSINE_END: return 0.05
|
| 96 |
+
return 0.5 * (1.0 + math.cos(math.pi * (s - 200) / max(COSINE_END - 200, 1)))
|
| 97 |
+
|
| 98 |
+
scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda)
|
| 99 |
+
criterion = nn.CrossEntropyLoss(ignore_index=0)
|
| 100 |
+
|
| 101 |
+
# Train
|
| 102 |
+
model.train()
|
| 103 |
+
SEQ_LEN, BS = 128, 2
|
| 104 |
+
running_loss = 0.0
|
| 105 |
+
max_start = len(train_ids) - SEQ_LEN - 1
|
| 106 |
+
t0 = time.time()
|
| 107 |
+
|
| 108 |
+
log(f'Starting training: {N_STEPS} steps from step {start_step}')
|
| 109 |
+
|
| 110 |
+
for step in range(1, N_STEPS + 1):
|
| 111 |
+
optimizer.zero_grad(set_to_none=True)
|
| 112 |
+
acc = 0.0
|
| 113 |
+
for _ in range(4): # gradient accumulation
|
| 114 |
+
starts = torch.randint(0, max_start, (BS,))
|
| 115 |
+
x = torch.stack([train_ids[s:s+SEQ_LEN] for s in starts])
|
| 116 |
+
y = torch.stack([train_ids[s+1:s+SEQ_LEN+1] for s in starts])
|
| 117 |
+
out = model(x)
|
| 118 |
+
loss = criterion(out['logits'].view(-1, out['logits'].size(-1)), y.view(-1))
|
| 119 |
+
(loss / 4).backward()
|
| 120 |
+
acc += loss.item()
|
| 121 |
+
del out, loss, x, y
|
| 122 |
+
|
| 123 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
| 124 |
+
optimizer.step()
|
| 125 |
+
scheduler.step()
|
| 126 |
+
running_loss += acc
|
| 127 |
+
gs = step + start_step
|
| 128 |
+
|
| 129 |
+
if step % 25 == 0:
|
| 130 |
+
avg = running_loss / 25
|
| 131 |
+
ppl = math.exp(min(avg, 20))
|
| 132 |
+
lr = scheduler.get_last_lr()[0]
|
| 133 |
+
elapsed = time.time() - t0
|
| 134 |
+
spm = step / (elapsed / 60) if elapsed > 0 else 0
|
| 135 |
+
log(f'Step {gs:>5d} | Loss: {avg:.4f} | PPL: {ppl:.1f} | LR: {lr:.6f} | {spm:.1f} steps/min')
|
| 136 |
+
running_loss = 0.0
|
| 137 |
+
|
| 138 |
+
# Save checkpoint every 200 steps
|
| 139 |
+
if step % 200 == 0:
|
| 140 |
+
# Quick eval
|
| 141 |
+
model.eval()
|
| 142 |
+
val_loss = 0.0
|
| 143 |
+
with torch.no_grad():
|
| 144 |
+
for _ in range(5):
|
| 145 |
+
s = torch.randint(0, max_start, (BS,))
|
| 146 |
+
x = torch.stack([train_ids[si:si+SEQ_LEN] for si in s])
|
| 147 |
+
y = torch.stack([train_ids[si+1:si+SEQ_LEN+1] for si in s])
|
| 148 |
+
out = model(x)
|
| 149 |
+
val_loss += criterion(out['logits'].view(-1, out['logits'].size(-1)), y.view(-1)).item()
|
| 150 |
+
val_loss /= 5
|
| 151 |
+
|
| 152 |
+
is_best = val_loss < best_val
|
| 153 |
+
if is_best:
|
| 154 |
+
best_val = val_loss
|
| 155 |
+
|
| 156 |
+
val_ppl = math.exp(min(val_loss, 20))
|
| 157 |
+
params = sum(p.numel() for p in model.parameters())
|
| 158 |
+
|
| 159 |
+
torch.save({
|
| 160 |
+
'model_state_dict': model.state_dict(),
|
| 161 |
+
'vocab_size': tokenizer.vocab_size,
|
| 162 |
+
'hidden_dim': 512,
|
| 163 |
+
'num_blocks': 6,
|
| 164 |
+
'max_seq_len': 192,
|
| 165 |
+
'tokenizer_vocab_size': tokenizer.vocab_size,
|
| 166 |
+
'metrics': {'step': gs, 'val_loss': val_loss, 'val_ppl': val_ppl, 'total_params': params},
|
| 167 |
+
}, ckpt_path)
|
| 168 |
+
|
| 169 |
+
log(f'Checkpoint saved: step={gs}, val_loss={val_loss:.4f}, val_ppl={val_ppl:.2f} {"NEW BEST!" if is_best else ""}')
|
| 170 |
+
model.train()
|
| 171 |
+
|
| 172 |
+
# Final save
|
| 173 |
+
gs = start_step + N_STEPS
|
| 174 |
+
model.eval()
|
| 175 |
+
params = sum(p.numel() for p in model.parameters())
|
| 176 |
+
torch.save({
|
| 177 |
+
'model_state_dict': model.state_dict(),
|
| 178 |
+
'vocab_size': tokenizer.vocab_size,
|
| 179 |
+
'hidden_dim': 512,
|
| 180 |
+
'num_blocks': 6,
|
| 181 |
+
'max_seq_len': 192,
|
| 182 |
+
'tokenizer_vocab_size': tokenizer.vocab_size,
|
| 183 |
+
'metrics': {'step': gs, 'total_params': params},
|
| 184 |
+
}, ckpt_path)
|
| 185 |
+
log(f'Done: step {start_step}->{gs} in {time.time()-t0:.0f}s')
|