-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwakeup.py
More file actions
615 lines (564 loc) · 23.6 KB
/
wakeup.py
File metadata and controls
615 lines (564 loc) · 23.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
# CHARIS CAT 2025
# --- ʕっʘ‿ʘʔ⊃ -*- babyllm -*- ⊂ʕʘ‿ʘ૮ʔ ---
# v1.12
import random
# from torch.profiler import profile, record_function, ProfilerActivity
import sys
import threading
import time
import warnings
from datetime import datetime
import torch
from rich.traceback import install
from babyLLM import BABYLLM
from config import *
from phone.babyBot import BABYBOT_TWITCH
from phone.babyBot_discord import *
from school.staffroom.calligraphist import S_OUTPUT
from school.staffroom.counsellor import COUNSELLOR
from school.staffroom.HE_IS_SCRIBE import SCRIBE
from school.staffroom.librarian import LIBRARIAN
from school.staffroom.tutor import TUTOR
from secret import *
from utils.helpers import empty_mps_cache, get_grad_stats
from utils.wakeupUtils import (
append_to_files,
checkLossCheckpoint,
handle_exception,
openingQuestions,
setStartIndex,
)
sys.excepthook = handle_exception
warnings.simplefilter("default") # show all warnings (PyTorch hides some by default)
install(show_locals=True)
torch.autograd.set_detect_anomaly(mode=anomalyDetect, check_nan=debugPrints)
def wakeup(
windowMAX,
dataStride,
passRateSTART,
lrGoal=learningRateGOAL,
trainingDataPairNum=trainingDataPairNumber,
log_A=trainingLogFreq_A,
totalTurnsAwake=0,
totalRuns=0,
first=True,
mode="train",
):
try:
# WAKE UP THE school :)
counsellor = COUNSELLOR(
"babyLLM", _debug=debugPrints, _durations=durationLogging
)
with counsellor.infodump("wakeup") as ʕっʘ‿ʘʔっ:
# OPEN THE LIBRARY :)
if debugPrints:
ʕっʘ‿ʘʔっ("waking the librarian...")
librarian = LIBRARIAN(
_counsellor=counsellor, _baseTokenizerPath=None, _forceRetrain=False
) # _baseTokenizerPath = "brain/vocabCache/2000_20/tokenizer_2000.json", _forceRetrain = True)
try:
librarian.loadTrainingData(trainingFilePath_arr)
except Exception as e:
print(f"[WARN] failed to initialise streaming training data: {e}")
if False:
exit(0)
# if debugPrints: ʕっʘ‿ʘʔっ("opening questions...")
# newStartIndex = openingQuestions(_counsellor = counsellor, _librarian = librarian, _windowMAX = windowMAX, _first = first)
# if debugPrints: ʕっʘ‿ʘʔっ("generating training data pairs...")
# trainingDataPairs = librarian.genTrainingData(_windowMAX = windowMAX, _trainingDataPairNumber = trainingDataPairNum, _startIndex = newStartIndex, _stride = dataStride)
# if debugPrints: print(f"Total trainingDataPairs: {len(trainingDataPairs)}")
if debugPrints:
ʕっʘ‿ʘʔっ("loading chaos agents...")
calligraphist = S_OUTPUT(_counsellor=counsellor)
scribe = SCRIBE(
_counsellor=counsellor,
_calligraphist=calligraphist,
_librarian=librarian,
_numTokensPerStep=windowMAX,
)
# WAKE UP THE BABY :)
if debugPrints:
ʕっʘ‿ʘʔっ("loading babyLLM...")
babyLLM = BABYLLM(
_counsellor=counsellor,
_calligraphist=calligraphist,
_scribe=scribe,
_librarian=librarian,
_device=modelDevice,
_numTokensPerStep=windowMAX,
_first=first,
_learningRateGOAL=lrGoal,
)
babyLLM.model_thread_lock = threading.Lock()
tutor = TUTOR(
_counsellor=counsellor,
_calligraphist=calligraphist,
_scribe=scribe,
_librarian=librarian,
_model=babyLLM,
_model_thread_lock=babyLLM.model_thread_lock,
_device=modelDevice,
_numTokensPerStep=windowMAX,
_dataStride=dataStride,
_first=first,
_lastRunLoss=checkLossCheckpoint(),
_totalTurnsAwake=totalTurnsAwake,
_totalRuns=totalRuns,
_perfectionistPassRateSTART=passRateSTART,
_trainingLogFreq_A=log_A,
)
if mode == "twitch":
print("--- LAUNCHING TWITCH BOT ---")
if debugPrints:
ʕっʘ‿ʘʔっ("starting twitch bot!")
# create a bot instance, pass in the staff etc
babyBot_twitch = BABYBOT_TWITCH(
babyLLM, tutor, librarian, scribe, calligraphist
)
babyLLM.loadModel()
babyLLM.to(modelDevice)
babyBot_twitch.run()
elif mode == "discord":
print("--- LAUNCHING DISCORD BOT ---")
if debugPrints:
ʕっʘ‿ʘʔっ("starting discord bot!")
# create a bot instance, pass in the staff etc
run_discord_bot(
babyLLM,
tutor,
librarian,
scribe,
calligraphist,
SECRETdiscordTokenSECRET,
)
elif mode == "unified":
print("=" * 60)
print("LAUNCHING UNIFIED MULTI-PLATFORM BOT (Discord + Twitch + Web)")
print("=" * 60)
if debugPrints:
ʕっʘ‿ʘʔっ("starting unified multi-platform bot!")
import asyncio
from phone.discord_bot.bot import BABYBOT_DISCORD
# Create bot instance
bot = BABYBOT_DISCORD(
babyLLM=babyLLM,
tutor=tutor,
librarian=librarian,
scribe=scribe,
calligraphist=calligraphist,
discordToken=SECRETdiscordTokenSECRET,
discordChannel=bby_spam_channel_id,
)
async def run_unified():
# Set up bot
await bot.setup_bot()
# Enable Twitch
print("[UNIFIED] Enabling Twitch integration...")
try:
await bot.enable_twitch() # Reads from config.twitch_channels
print(
f"[UNIFIED] Twitch enabled for channels: {twitch_channels}"
)
except Exception as e:
print(f"[ERROR] Failed to enable Twitch: {e}")
import traceback
traceback.print_exc()
print("[UNIFIED] Continuing without Twitch...")
# Enable Web API
print("[UNIFIED] Enabling Web API integration...")
try:
await bot.enable_web(port=4420)
print("[UNIFIED] Web API enabled on http://127.0.0.1:4420")
except Exception as e:
print(f"[ERROR] Failed to enable Web API: {e}")
import traceback
traceback.print_exc()
print("[UNIFIED] Continuing without Web API...")
# Start Discord bot
print("\n[UNIFIED] Starting Discord bot...")
print("=" * 60)
print("UNIFIED MULTI-PLATFORM BOT IS NOW RUNNING")
print("Platforms: Discord + Twitch + Web API")
print("Press Ctrl+C to stop")
print("=" * 60)
# Load model. The optimizer (5GB on disk) loads in a
# background thread so Discord/Twitch/Web setup overlaps
# with optim I/O. Tutor.trainModel calls
# babyLLM.wait_for_optimizer_ready() before stepping.
babyLLM.loadModel(async_optimizer=True)
babyLLM.to(modelDevice)
try:
await bot.start(SECRETdiscordTokenSECRET)
except KeyboardInterrupt:
print("\n[SHUTDOWN] Stopping unified bot...")
finally:
if hasattr(bot, "disable_twitch"):
await bot.disable_twitch()
if hasattr(bot, "disable_web"):
await bot.disable_web()
await bot.close()
print("[SHUTDOWN] Unified bot stopped")
# Run the unified bot
asyncio.run(run_unified())
elif mode == "train":
print("--- STARTING OFFLINE TRAINING ---")
if first == True:
newStartIndex = openingQuestions(
_counsellor=counsellor,
_librarian=librarian,
_windowMAX=windowMAX,
_first=True,
)
else:
newStartIndex = setStartIndex()
if tokenSpeedTest == True:
tokenSpeedTestStart = time.time()
trainingDataPairs = librarian.genTrainingData(
_windowMAX=windowMAX,
_trainingDataPairNumber=trainingDataPairNumber,
_startIndex=newStartIndex,
_stride=trainingDataStride,
)
# START THE LESSONS :)
babyLLM.loadModel()
babyLLM.to(modelDevice)
if debugPrints:
ʕっʘ‿ʘʔっ("starting lessons!")
tutor.trainModel(
_trainingDataPairs=trainingDataPairs,
_epochs=epochs,
_startIndex=newStartIndex,
)
if tokenSpeedTest == True:
tokenSpeedTestEnd = time.time()
thisTestSpeed = tokenSpeedTestEnd - tokenSpeedTestStart
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
tokenSpeedTest_str = f"\n{timestamp}| numTokens: {windowMAX}, speed: {thisTestSpeed:.2f} (tokenAvg: {(thisTestSpeed / windowMAX):.2f}), avgLoss: {tutor.totalAvgLoss:.2f} (delta: {tutor.totalAvgDelta:.2f})"
append_to_files(tokenSpeedTest_str, tokenSpeedTestFilePath)
return (
tutor.totalAvgLoss,
tutor.totalTurns,
tutor.perfectionistPassRate,
tutor.learningRateGOAL,
)
else:
print(f"unknown mode: '{mode}'. Please use 'train' or 'bot'.")
except Exception:
print("[RIP ʕっₓᴥₓʔっ]")
raise
except KeyboardInterrupt: # as k
for name, p in babyLLM.named_parameters():
if p.grad is None:
msg = babyLLM.calligraphist.S_apply("emergency", f"NO GRAD: {name}")
print(f"keyboard interrupt = {msg}")
else:
stats = get_grad_stats(p.grad)
shape = stats["shape"]
norm = stats["norm"]
sparsity = stats["sparsity"]
mean = stats["mean"]
std = stats["std"]
detail = (
f"yes grad: {name} | shape: {shape} | norm: {norm:.4f} | "
f"sparsity: {sparsity:.2%} | mean: {mean:.4f} | std: {std:.4f}"
)
msg = babyLLM.calligraphist.S_apply("almostPerfect", detail)
print(f"keyboard interrupt = {msg}")
if debugPrints:
ʕっʘ‿ʘʔっ("♥keyboardInterrupt")
if tutor.trainingStepCounter:
step = tutor.trainingStepCounter
totalAvgLoss = tutor.totalAvgLoss
totalTurnsAwake += tutor.totalTurns
else:
step = 1
choice = input(
"save, cancel (do not save before exit), restart or interact?"
+ f"\n{userName}: "
).lower()
if choice in ("save", "") or choice.startswith("s"):
if debugPrints:
ʕっʘ‿ʘʔっ("♥choice = s")
babyLLM.saveModel(
_newStartIndex=newStartIndex,
_trainingStepCounter=step,
_totalAvgLoss=totalAvgLoss,
_first=first,
)
print("\nit's rude to interrupt people.. but, bye bye! :)")
elif choice == "cancel" or choice.startswith("c"):
if debugPrints:
ʕっʘ‿ʘʔっ("♥choice = c")
print("\nhey! i wanted to remember that! :(")
elif choice == "interact" or choice.startswith("i"):
if debugPrints:
ʕっʘ‿ʘʔっ("♥choice = i")
babyLLM.saveModel(
_newStartIndex=newStartIndex,
_trainingStepCounter=step,
_totalAvgLoss=totalAvgLoss,
_first=first,
)
import code
print(
"try:\nbabyLLM.stats\nbabyLLM.scheduledSampling\nbabyLLM.memory.memory\nbabyLLM.interneuronNetwork.cerebellum\nbabyLLM.logits.forward(...)\nUse `exit()` to return to terminal.\n"
)
code.interact(local=locals())
elif choice == "restart" or choice.startswith("r"):
if debugPrints:
ʕっʘ‿ʘʔっ("♥choice = r")
babyLLM.saveModel(
_newStartIndex=newStartIndex,
_trainingStepCounter=step,
_totalAvgLoss=totalAvgLoss,
_first=first,
)
print("you spin me right round, babyllm, right round...")
return totalAvgLoss
else:
if debugPrints:
ʕっʘ‿ʘʔっ("♥choice = None")
babyLLM.saveModel(
_newStartIndex=newStartIndex,
_trainingStepCounter=step,
_totalAvgLoss=totalAvgLoss,
_first=first,
)
print("\nuhh... i'm confused, but i saved anyway!")
if modelDevice.type == "mps":
empty_mps_cache()
print("cache emptied")
exit(8)
def main():
windowMAX = numTokensPerStepSTART
dataStride = trainingDataStride
passRateSTART = perfectionistPassRateSTART
totalTurnsAwake = 0
totalRuns = 0
MAINPairNumber = trainingDataPairNumber
logFreq_A = trainingLogFreq_A
learnRateGoal = learningRateGOAL
if len(sys.argv) > 1:
arg = sys.argv[1].lower()
if arg == "bot":
run_mode = "twitch"
elif arg in ("unified", "u", "all"):
run_mode = "unified"
elif arg in ("discord", "d"):
run_mode = "discord"
elif arg in ("twitch", "t"):
run_mode = "twitch"
else:
run_mode = "train"
else:
choice = input(
"run in train mode, [d]iscord, [t]witch, or [u]nified (discord+twitch)? "
).lower()
if choice.startswith("t"):
run_mode = "twitch"
elif choice.startswith("d"):
run_mode = "discord"
elif choice.startswith("u"):
run_mode = "unified"
else:
run_mode = "train"
print(f"Choice {choice} run_mode => {run_mode}")
if run_mode in ["twitch", "discord", "unified"]:
# Bot startup should use the real target pass-rate baseline, not the fresh-training bootstrap value.
# Otherwise daily eval output can look fake-good immediately after startup.
botPassRateStart = perfectionistPassRate
wakeup(windowMAX = windowMAX,
dataStride = dataStride,
totalTurnsAwake = totalTurnsAwake,
totalRuns = totalRuns,
first = False,
passRateSTART = botPassRateStart,
log_A = logFreq_A,
lrGoal = learnRateGoal,
trainingDataPairNum = MAINPairNumber,
mode = run_mode,)
else:
lastRunLoss = checkLossCheckpoint()
# lastRunLoss = 420
firstRun = True
easyStartThresh = 3
# logFreq_A = windowMAXSTART * perfectionistMaxRetries
numWins = 0
winStreak = 0
while windowMAX <= maxTokensPerStep:
print("\n--- STARTING NEW TRAINING LOOP ---")
thisRunLoss, totalTurns, passRateEND, learnRateGoalEND = wakeup(
windowMAX=windowMAX,
dataStride=dataStride,
totalTurnsAwake=totalTurnsAwake,
totalRuns=totalRuns,
first=firstRun,
passRateSTART=passRateSTART,
log_A=logFreq_A,
lrGoal=learnRateGoal,
trainingDataPairNum=MAINPairNumber,
mode="train",
)
# logFreq_A = windowMAX * perfectionistMaxRetries
logFreq_A = trainingLogFreq_A
learnRateGoal = (learnRateGoalEND + learningRateGOAL + learningRateGOAL) / 3
totalRuns += 1
totalTurnsAwake += totalTurns
firstRun = False
easyStart = True
print(
f"BEFORE UPDATE: totalTurnsAwake = {totalTurnsAwake}, thisRunLoss = {thisRunLoss:.2f}, lastRunLoss = {lastRunLoss:.2f}, windowMAX = {windowMAX}, dataStride = {dataStride}, trainingPairNumber = {MAINPairNumber}, numWins = {numWins}, winStreak = {winStreak}"
)
scale = abs(thisRunLoss - lastRunLoss) + 0.01
choice = random.choice(
[
-1,
0,
0,
1,
1,
1,
1,
2,
2,
2,
3,
3,
4,
5,
4,
3,
3,
2,
2,
2,
1,
1,
1,
1,
0,
0,
-1,
]
)
increment = round(choice * (totalRuns / totalTurnsAwake) * scale)
print(
f"increment = {increment} = {choice} * ({totalRuns} / {totalTurnsAwake}) * {scale} = {choice} * {totalRuns / totalTurnsAwake} * {scale}"
)
maxAllowedWindowJump = round(0.2 * (maxTokensPerStep - windowMAX))
maxAllowedStrideJump = round(0.2 * ((windowMAX * 2) - dataStride))
halfWindow = round(windowMAX / 20) + 1
halfStride = round(dataStride / 20) + 1
incrementW = random.choice(
[
(max(1, min((increment + (halfWindow)), maxAllowedWindowJump))),
round(windowMAX * 0.1),
]
)
incrementS = random.choice(
[
(max(1, min((increment + (halfStride)), maxAllowedStrideJump))),
round(dataStride * 0.1),
]
)
if easyStart:
if easyStartThresh > 0:
lastRunLoss = (min(lastRunLoss, thisRunLoss) + lastRunLoss) / 2
easyStartThresh -= totalRuns
else:
easyStart = False
testing = True
if testing:
numWins += 1
winStreak += 1
MAINPairNumber = trainingDataPairNumber
# if winStreak % 2 == 0:
if windowMAX >= 1:
windowInc = random.choice([2, 0.5])
windowMAX *= windowInc
dataStride = max(1, (windowMAX * 0.1))
else:
windowMAX = 1
elif thisRunLoss < lastRunLoss:
numWins += 1
winStreak += 1
if winStreak >= 2:
winStreak -= 1
MAINPairNumber -= choice
if random.choice([True, False]):
print(
f"upping windowMAX from {windowMAX} to {windowMAX + incrementW}"
)
windowMAX += incrementW + incrementW
else:
print(
f"upping dataStride from {dataStride} to {dataStride + incrementS}"
)
dataStride += incrementS + incrementS
else:
windowOrStride = random.choice([True, False])
if winStreak > 0:
winStreak = -1
MAINPairNumber += choice
if windowMAX > incrementW + 1:
if windowOrStride:
print(
f"downing windowMAX from {windowMAX} to {windowMAX - incrementW}"
)
windowMAX -= incrementW
else:
print(f"windowMAX staying at {windowMAX}")
elif dataStride > incrementS + 1:
if not windowOrStride:
print(
f"downing dataStride from {dataStride} to {dataStride - incrementS}"
)
dataStride -= incrementS
else:
print(f"dataStride staying at {dataStride}")
elif dataStride == 1 and windowMAX == 1 or random.random() < 0.001:
random.choice(
[
2,
windowMAX,
dataStride,
(windowMAX * 2),
(dataStride * 2),
winStreak,
totalRuns,
incrementS,
incrementW,
passRateSTART,
passRateEND,
lastRunLoss,
thisRunLoss,
numWins,
maxAllowedWindowJump,
maxAllowedStrideJump,
choice,
scale,
4,
6,
8,
12,
16,
]
)
if random.choice([True, False]):
print(f"bored. windowMAX from {windowMAX} to {2}")
windowMAX = 2
else:
print(f"bored. dataStride from {dataStride} to {2}")
dataStride = 2
windowMAX = round(max(1, min(windowMAX, maxTokensPerStep)))
dataStride = round(max(1, min(dataStride, windowMAX * 0.1)))
if MAINPairNumber < 1:
MAINPairNumber = 2
print(f"normalised: dataStride is {dataStride}, windowMAX is {windowMAX}")
lastRunLoss = thisRunLoss
passRateSTART = passRateEND
print(
f"AFTER UPDATE: totalTurnsAwake = {totalTurnsAwake}, thisRunLoss = {thisRunLoss}, lastRunLoss = {lastRunLoss}, windowMAX = {windowMAX}, dataStride = {dataStride}, trainingPairNumber = {MAINPairNumber}, numWins = {numWins}, winStreak = {winStreak}"
)
if __name__ == "__main__":
main()