-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrain_basil_v2.py
More file actions
executable file
·2386 lines (2021 loc) · 103 KB
/
Copy pathtrain_basil_v2.py
File metadata and controls
executable file
·2386 lines (2021 loc) · 103 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# train_basil_v2.py
# Dual-objective training script for Basil with LoRA adapter support.
#
# Supports multiple modes:
# --mode mixed : (DEFAULT) Alternating world/basil with LoRA adapters
# --mode world : Train base model (trunk) on full transcripts only
# --mode basil : Train LoRA adapter on Basil turns only (trunk frozen)
# --mode session : Legacy full-session mode (aliases to world)
# --mode graded : Legacy graded turns mode
# --mode legacy : Legacy conversation logs mode [legacy]
# --mode combined : Legacy combined mode [legacy]
#
# Trunk masking (--mask-mode):
# none : No masking — trunk sees everything
# basil_only : Mask only Basil's output tokens
# basil_and_after : (DEFAULT) Mask Basil + Sophie post-grade + Tutor answer
#
# LoRA epoch cap (--lora-max-epochs):
# If unset, scales linearly with age_band: 0 at band 0, max_epochs at band 7.
# Manual override available for experiments.
import os
import json
import time
import math
import argparse
import torch
from datetime import datetime
from transformers import AutoTokenizer, AutoModelForCausalLM
from torch.utils.data import Dataset, DataLoader, random_split
from torch.optim.lr_scheduler import LambdaLR
from torch.cuda.amp import autocast, GradScaler
from peft import LoraConfig, get_peft_model, PeftModel
from config import (
LOG_DIR, MODELS_DIR,
TRAIN_MIN_SCORE, MIN_TRAINING_WEIGHT,
score_to_weight, score_to_weight_basil_policy, get_basil_model_name,
RECENCY_HALF_LIFE_TRAIN_RUNS_GRADED, RECENCY_HALF_LIFE_TRAIN_RUNS_LEGACY,
MIN_RECENCY_WEIGHT, LEGACY_WEIGHT_MULT, recency_weight,
LORA_RANK, LORA_ALPHA, LORA_DROPOUT, LORA_TARGET_MODULES,
LORA_ADAPTER_NAME, LORA_ADAPTER_SUBDIR,
LORA_ACTIVATION_AGE_BAND,
BASIL_POLICY_SCORE_WEIGHTS_TABLE, TRUNK_WEIGHT_DIVISOR,
lora_max_epochs_for_age_band,
)
from utils.scoring import average_entropy
from memory_manager import update_metrics_after_training, load_basil_assessment, load_metrics
from metrics_manager import record_training_attempt, load_rolling_metrics
# === CONFIG ===
MAX_AGE_DAYS = 365
ENTROPY_THRESHOLD = 8
# Block size fixed at model's n_positions limit (1024 for GPT-2)
# Full sessions (~3-5K tokens) use sliding window with stride = block_size // 2
BLOCK_SIZE_BY_AGE_BAND = {
0: 1024, 1: 1024, 2: 1024, 3: 1024,
4: 1024, 5: 1024, 6: 1024, 7: 1024,
}
# STRIDE removed - computed as block_size // 2 inside dataset classes
# --- Batching (target: 32-64 sequences per optimizer step = 32k-64k tokens) ---
# A100 40GB: batch_size=2, grad_accum=16 -> effective 32 sequences
# A100 80GB / H100: batch_size=4, grad_accum=16 -> effective 64 sequences
BATCH_SIZE = 4 # Microbatch size (adjust down if OOM)
ACCUMULATION_STEPS = 16 # Effective batch = BATCH_SIZE * ACCUMULATION_STEPS
# --- Learning Rate ---
PEAK_LR = 1e-4 # For training from scratch (random init)
CONTINUE_PEAK_LR = 3e-5 # For continued training (model already partially trained)
LORA_PEAK_LR = 3e-5 # LoRA adapter LR — lower than trunk because alpha/rank amplifies updates
LORA_CONTINUE_LR = 1e-5 # LoRA LR for continued training
MIN_LR = 1e-5 # 10% of PEAK_LR for cosine floor
WARMUP_RATIO = 0.03 # 3% of total steps for linear warmup
GRAD_CLIP_NORM = 1.0 # Gradient clipping
# --- Training limits ---
MAX_TRAIN_TIME = 12 * 3600 # 12 hours in seconds
MAX_EPOCHS = 100
# --- Validation-based early stopping ---
VAL_SPLIT_RATIO = 0.05 # 5% held out for validation
EVAL_EVERY_STEPS = 500 # Evaluate validation loss every N optimizer steps
EARLY_STOP_MIN_DELTA = 0.005 # Stop if val loss doesn't improve by at least this
EARLY_STOP_PATIENCE = 8 # Number of evals without improvement before stopping
# --- Val loss floor (global safety net) ---
# Single global floor to catch extreme memorization. Patience-based early
# stopping (EARLY_STOP_PATIENCE) is the primary guard against overfitting;
# this floor is a last-resort safety net only.
VAL_LOSS_FLOOR_BY_AGE_BAND = {band: 0.5 for band in range(8)}
# Legacy (deprecated, kept for reference)
_LEGACY_MIN_LOSS_DELTA = 0.1
_LEGACY_EARLY_LOSS_THRESHOLD = 2.4
# =============================================================================
# DATA LOADING
# =============================================================================
def _parse_session_key_from_filename(fname: str) -> str:
"""
Extract a sortable session key from a log filename.
Supports formats:
- log_YYYYMMDD_HHMMSS.jsonl -> "YYYYMMDD_HHMMSS"
- session_YYYYMMDD_HHMMSS_graded.jsonl -> "YYYYMMDD_HHMMSS"
- day_NNN.jsonl -> "day_NNN" (numeric sort handled separately)
Returns the session key string for sorting.
"""
if fname.startswith("log_"):
# log_YYYYMMDD_HHMMSS.jsonl or log_YYYYMMDD_HHMMSS_graded.jsonl
parts = fname.replace(".jsonl", "").replace("_graded", "").replace("_structured", "")
return parts.replace("log_", "")
elif fname.startswith("session_"):
# session_YYYYMMDD_HHMMSS_graded.jsonl
parts = fname.replace(".jsonl", "").replace("_graded", "").replace("_structured", "")
return parts.replace("session_", "")
elif fname.startswith("day_"):
# day_NNN.jsonl - pad for lexicographic sorting
day_num = fname.replace("day_", "").replace(".jsonl", "")
return f"day_{int(day_num):06d}"
else:
# Fallback: use filename as-is
return fname
def _parse_turn(turn: dict, session_key: str, min_score: float) -> dict:
"""
Parse a single graded turn record into a training example.
Returns a dict suitable for training, or None if the turn should be skipped.
"""
# Skip identity probe entries (logged for analysis only)
if turn.get("type") == "identity_probe":
return None
# Skip wrapup turns (not for training)
if turn.get("type") == "wrapup":
return None
# Extract score and weight
grade = turn.get("grade", {})
score = grade.get("score", 0)
weight = turn.get("weight", score_to_weight(score))
if score < min_score:
return None
# Build training example
# Context: what Basil saw before responding
context_parts = []
# Phase B.1: Tutor teaching paragraph
if turn.get("tutor_teaching"):
context_parts.append(f"Tutor: {turn['tutor_teaching']}")
# Phase B.2: Sophie reaction to teaching
if turn.get("sophie_reaction"):
context_parts.append(f"Sophie: {turn['sophie_reaction']}")
# Phase B.3: Task delivery (naturalized form)
task = turn.get("task_spec", {})
task_text = task.get("task_text", "")
asker = task.get("asker", "tutor")
if task_text:
if asker == "sophie":
context_parts.append(f"Sophie: Basil, {task_text}")
else:
context_parts.append(f"Tutor: Basil, {task_text}")
context = "\n".join(context_parts)
basil_output = turn.get("basil", "")
# Phase E: Sophie's post-grade response (encouragement + question)
sophie_post_grade = turn.get("sophie", "")
# Phase F: Tutor answers Sophie's question
tutor_answer = turn.get("tutor_answer", "")
if not basil_output.strip():
return None
return {
"context": context,
"basil_output": basil_output,
"sophie_post_grade": sophie_post_grade,
"tutor_answer": tutor_answer,
"weight": weight,
"task_category": turn.get("task_category", "unknown"),
"score": score,
"session_key": session_key,
}
def load_graded_turns(min_score: float = None) -> list:
"""
Load graded turns from Bootstrap Basil log files.
Supports two file formats:
- Legacy per-session: session_YYYYMMDD_HHMMSS_graded.jsonl
- Batch-level: batch_YYYYMMDD_HHMMSS_graded.jsonl
(each record has an embedded "session_id" field)
Returns list of dicts with keys: context, basil_output, sophie_post_grade,
tutor_answer, weight, task_category, score, session_key (for recency ordering)
"""
min_score = min_score if min_score is not None else TRAIN_MIN_SCORE
graded_turns = []
if not os.path.exists(LOG_DIR):
return graded_turns
for fname in sorted(os.listdir(LOG_DIR)):
if not fname.endswith("_graded.jsonl"):
continue
filepath = os.path.join(LOG_DIR, fname)
if fname.startswith("batch_"):
# Batch-level file: session_id is embedded in each record
try:
with open(filepath, "r") as f:
for line in f:
turn = json.loads(line)
# Derive session_key from embedded session_id
session_key = turn.get("session_id", _parse_session_key_from_filename(fname))
parsed = _parse_turn(turn, session_key, min_score)
if parsed:
graded_turns.append(parsed)
except Exception as e:
print(f"[!] Error loading {fname}: {e}")
continue
elif fname.startswith("session_"):
# Legacy per-session file: session_key from filename
session_key = _parse_session_key_from_filename(fname)
try:
with open(filepath, "r") as f:
for line in f:
turn = json.loads(line)
parsed = _parse_turn(turn, session_key, min_score)
if parsed:
graded_turns.append(parsed)
except Exception as e:
print(f"[!] Error loading {fname}: {e}")
continue
return graded_turns
def load_legacy_logs() -> list:
"""
Load traditional conversation logs with entropy filtering.
Returns list of (filename, lines, session_key) tuples.
"""
selected_logs = []
if not os.path.exists(LOG_DIR):
return selected_logs
today = datetime.now().timetuple().tm_yday
for fname in sorted(os.listdir(LOG_DIR)):
# Skip graded files and non-jsonl
if fname.endswith("_graded.jsonl") or fname.endswith("_structured.jsonl"):
continue
if not fname.endswith(".jsonl"):
continue
# Parse date from filename
try:
if fname.startswith("day_"):
day_num = int(fname.split("_")[1].split(".")[0])
age = today - day_num
elif fname.startswith("log_"):
log_date_str = fname.split("_")[1]
log_date = datetime.strptime(log_date_str, "%Y%m%d")
today_date = datetime.today()
age = (today_date - log_date).days
elif fname.startswith("session_"):
# New session format: session_YYYYMMDD_HHMMSS_structured.jsonl
continue # Skip, we use graded files for these
else:
print(f"[!] Skipping unrecognized file format: {fname}")
continue
except Exception as e:
print(f"[!] Error parsing filename {fname}: {e}")
continue
filepath = os.path.join(LOG_DIR, fname)
with open(filepath, "r") as f:
lines = [json.loads(line) for line in f]
# Filter out identity_probe entries (logged for analysis only, not training)
lines = [line for line in lines if line.get("type") != "identity_probe"]
# Filter by entropy
basil_lines = [line["text"] for line in lines if line.get("speaker") == "Basil"]
entropy = average_entropy(basil_lines)
session_key = _parse_session_key_from_filename(fname)
if age == 0:
print(f"[+] Including today's log: {fname}")
selected_logs.append((fname, lines, session_key))
elif age <= MAX_AGE_DAYS and entropy < ENTROPY_THRESHOLD:
print(f"[+] Including {fname} (entropy {entropy:.2f})")
selected_logs.append((fname, lines, session_key))
else:
print(f"[-] Skipping {fname} (entropy {entropy:.2f}, age {age})")
return selected_logs
def load_session_transcripts() -> list:
"""
Load full session transcripts from *_sessions.jsonl files.
Returns list of session dicts with:
- session_id: str
- text: str (full session transcript)
- basil_spans: list of {"start_char": int, "end_char": int, "score": float}
- session_key: str (for recency weighting)
"""
sessions = []
if not os.path.exists(LOG_DIR):
return sessions
# Group records by session_id
session_data = {} # session_id -> {transcript_lines: [], episodes: []}
for fname in sorted(os.listdir(LOG_DIR)):
if not fname.endswith("_sessions.jsonl"):
continue
filepath = os.path.join(LOG_DIR, fname)
try:
with open(filepath, "r") as f:
for line in f:
record = json.loads(line)
session_id = record.get("session_id")
if not session_id:
continue
if session_id not in session_data:
session_data[session_id] = {
"transcript_lines": [],
"episodes": [],
"session_key": _parse_session_key_from_filename(fname) if fname.startswith("batch_") else session_id
}
record_type = record.get("record_type")
if record_type == "transcript":
# Skip only identity_probe entries (include wrapup)
if record.get("type") == "identity_probe":
continue
session_data[session_id]["transcript_lines"].append(record)
elif record_type == "episode":
session_data[session_id]["episodes"].append(record)
except Exception as e:
print(f"[!] Error loading {fname}: {e}")
continue
# Build session text and identify Basil spans
for session_id, data in session_data.items():
transcript_lines = data["transcript_lines"]
episodes = data["episodes"]
if not transcript_lines:
continue
# Build full session text
text_parts = []
for line in transcript_lines:
speaker = line.get("speaker", "")
text = line.get("text", "")
if speaker and text:
# Strip [WRAPUP] prefix if present
if text.startswith("[WRAPUP]"):
text = text.replace("[WRAPUP]", "", 1).strip()
text_parts.append(f"{speaker}: {text}\n")
full_text = "".join(text_parts)
if not full_text.strip():
continue
# Build Basil span map: find each Basil response in text and map to score.
# Also build episode-local context for LoRA training to avoid contamination
# from previous Basil garbage in multi-episode sessions.
basil_spans = []
for episode in episodes:
basil_output = episode.get("basil_output", "")
grade = episode.get("grade", {})
score = grade.get("score", 0)
if not basil_output:
continue
# Build episode-local context from messages (phases before "C")
# This gives the LoRA clean context without prior Basil garbage.
# Apply same cleaning as inference (_get_episode_transcript) so context matches.
episode_messages = episode.get("messages", [])
episode_context = None
if episode_messages:
from utils.transcript import clean_transcript_for_training
ctx_parts = []
for msg in episode_messages:
if msg.get("phase") == "C":
# Add speaker prefix but stop before Basil's reply
ctx_parts.append("Basil: ")
break
content = clean_transcript_for_training(msg.get("content", ""))
if content:
ctx_parts.append(f"{msg['role']}: {content}\n")
if ctx_parts:
episode_context = "".join(ctx_parts)
# Find Basil response in transcript text
# Look for "Basil: {basil_output}" pattern
search_pattern = f"Basil: {basil_output}"
start_char = full_text.find(search_pattern)
if start_char != -1:
# Found it - mark the span
# Start after "Basil: " prefix
basil_start = start_char + len("Basil: ")
basil_end = basil_start + len(basil_output)
basil_spans.append({
"start_char": basil_start,
"end_char": basil_end,
"score": score,
"episode_context": episode_context,
"basil_reply": basil_output,
})
else:
# Try without "Basil: " prefix (might be in middle of text)
start_char = full_text.find(basil_output)
if start_char != -1:
basil_spans.append({
"start_char": start_char,
"end_char": start_char + len(basil_output),
"score": score,
"episode_context": episode_context,
"basil_reply": basil_output,
})
sessions.append({
"session_id": session_id,
"text": full_text,
"basil_spans": basil_spans,
"session_key": data["session_key"]
})
print(f"[SessionLoader] Loaded {len(sessions)} sessions from *_sessions.jsonl files")
return sessions
# =============================================================================
# LORA SETUP
# =============================================================================
def setup_lora_model(base_model):
"""Wrap a base GPT-2 model with LoRA adapters for Basil-policy training.
Returns the PeftModel wrapper. The base model weights are preserved inside;
LoRA adds small trainable low-rank matrices to attention layers.
"""
lora_config = LoraConfig(
r=LORA_RANK,
lora_alpha=LORA_ALPHA,
lora_dropout=LORA_DROPOUT,
target_modules=LORA_TARGET_MODULES,
bias="none",
task_type="CAUSAL_LM",
)
peft_model = get_peft_model(base_model, lora_config)
trainable_params = sum(p.numel() for p in peft_model.parameters() if p.requires_grad)
all_params = sum(p.numel() for p in peft_model.parameters())
print(f"[LoRA] Adapter configured: rank={LORA_RANK}, alpha={LORA_ALPHA}, dropout={LORA_DROPOUT}")
print(f"[LoRA] Target modules: {LORA_TARGET_MODULES}")
print(f"[LoRA] Trainable params: {trainable_params:,} / {all_params:,} "
f"({100 * trainable_params / all_params:.2f}%)")
return peft_model
def freeze_for_world_training(model):
"""Configure model for World/trunk training: disable LoRA, train base params only."""
if hasattr(model, 'disable_adapter_layers'):
model.disable_adapter_layers()
for name, param in model.named_parameters():
if 'lora_' in name:
param.requires_grad = False
else:
param.requires_grad = True
trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
print(f"[World Mode] Trunk trainable: {trainable:,} params, LoRA frozen/disabled")
def freeze_for_basil_training(model):
"""Configure model for Basil-policy training: enable LoRA, freeze base params."""
if hasattr(model, 'enable_adapter_layers'):
model.enable_adapter_layers()
# Freeze everything first
for param in model.parameters():
param.requires_grad = False
# Unfreeze only LoRA params
for name, param in model.named_parameters():
if 'lora_' in name:
param.requires_grad = True
trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
print(f"[Basil Mode] LoRA trainable: {trainable:,} params, trunk frozen")
def load_model_with_lora(model_path, device=None):
"""Load base model and optionally attach LoRA adapter for generation.
Returns (model, tokenizer). If an adapter exists at
{model_path}/{LORA_ADAPTER_SUBDIR}, it is loaded and enabled.
"""
tokenizer = AutoTokenizer.from_pretrained(model_path)
if tokenizer.pad_token is None:
tokenizer.pad_token = tokenizer.eos_token
base_model = AutoModelForCausalLM.from_pretrained(model_path)
adapter_path = os.path.join(model_path, LORA_ADAPTER_SUBDIR)
if os.path.exists(adapter_path):
print(f"[LoRA] Loading adapter from {adapter_path}")
model = PeftModel.from_pretrained(base_model, adapter_path)
# Ensure adapter is active for generation
if hasattr(model, 'enable_adapter_layers'):
model.enable_adapter_layers()
else:
model = base_model
model.eval()
if device:
model.to(device)
return model, tokenizer
# =============================================================================
# DATASETS
# =============================================================================
def _get_training_boundaries() -> list:
"""
Get chronologically sorted training-run boundary session IDs from metrics.
Each boundary is the session ID (YYYYMMDD_HHMMSS) of the last session that
was generated by the *previous* model version before a training run produced
a new version. This is recorded by the orchestrator in metrics.json via
record_training_attempt().
All sessions with keys <= boundary[i] were generated by model version i.
Sessions with keys > boundary[-1] are from the current (latest) model.
Returns:
Sorted list of boundary session IDs. Empty list on a fresh repo (no
training has occurred yet), in which case all sessions belong to run 0
and get identical recency weight.
"""
metrics = load_metrics()
boundaries = metrics.get("training_run_boundaries", [])
return sorted(boundaries)
def _compute_training_run_for_sessions(session_keys: list) -> dict:
"""
Map each session key to its training run index.
All sessions produced by the same model version (between two training
boundaries) get the same run index. The current (newest) run gets the
highest index.
Boundary semantics: boundary[i] is the *last session generated by model i*.
So:
Run 0: sessions with key <= boundary[0] (original model)
Run 1: sessions with key <= boundary[1] and > boundary[0]
...
Run N: sessions with key > boundary[-1] (current model)
Returns:
dict mapping session_key -> run_index (0 = oldest run, max = current run)
"""
boundaries = _get_training_boundaries()
# If no training has happened yet, all sessions are in run 0
if not boundaries:
return {key: 0 for key in set(session_keys)}
mapping = {}
for key in set(session_keys):
run = 0
for boundary in boundaries:
if key > boundary:
run += 1
else:
break
mapping[key] = run
return mapping
class WeightedGradedDataset(Dataset):
"""
Dataset for graded turns with per-example weights.
Each example is a (context + Basil response) with an associated weight.
Weights include both score-based and recency-based components.
"""
def __init__(self, graded_turns: list, tokenizer, block_size: int = 1024):
self.examples = []
self.weights = []
# Compute training-run mapping for recency weighting.
# All sessions from the same model version get the same weight.
session_keys = [turn["session_key"] for turn in graded_turns]
session_to_run = _compute_training_run_for_sessions(session_keys)
newest_run = max(session_to_run.values()) if session_to_run else 0
num_runs = len(set(session_to_run.values()))
# Track recency weights for debug logging
recency_weights_debug = []
# Pre-compute marker tokens for Basil output boundary detection
# These are used to find where Basil's output starts/ends in tokenized sequences
basil_marker_tokens = tokenizer.encode("\nBasil:", add_special_tokens=False)
sophie_marker_tokens = tokenizer.encode("\nSophie:", add_special_tokens=False)
tutor_marker_tokens = tokenizer.encode("\nTutor:", add_special_tokens=False)
n_basil_masked = 0 # Track how many examples had Basil output masked
for turn in graded_turns:
# Build full episode text in chronological order:
# B.1 Tutor teaching + B.2 Sophie reaction + B.3 Task delivery
# C Basil's attempt
# E Sophie's post-grade response
# F Tutor answers Sophie's question
context = turn["context"]
basil_output = turn["basil_output"]
sophie_post_grade = turn.get("sophie_post_grade", "")
tutor_answer = turn.get("tutor_answer", "")
score = turn["score"]
score_weight = turn["weight"] # Original score-based weight
# Compute recency weight (per training run, not per session)
session_key = turn["session_key"]
run_index = session_to_run.get(session_key, newest_run)
runs_ago = newest_run - run_index
rec_w = recency_weight(runs_ago, RECENCY_HALF_LIFE_TRAIN_RUNS_GRADED)
recency_weights_debug.append(rec_w)
# Final weight = score_weight * recency_weight
final_weight = score_weight * rec_w
# Format as full episode training example
full_text = f"{context}\nBasil: {basil_output}"
if sophie_post_grade:
full_text += f"\nSophie: {sophie_post_grade}"
if tutor_answer:
full_text += f"\nTutor: {tutor_answer}"
# Tokenize
tokenized = tokenizer(
full_text,
return_tensors="pt",
truncation=True,
max_length=block_size,
padding="max_length",
)
input_ids = tokenized["input_ids"].squeeze()
attention_mask = tokenized["attention_mask"].squeeze()
# Create labels: train on full conversation with reward weighting
# The example-level weight handles reinforcement:
# - Score 5 -> weight 1.0 (full signal from entire episode)
# - Score 0 -> weight 0.05 (learns language patterns from context)
labels = input_ids.clone()
# CRITICAL: Mask padding tokens (they shouldn't contribute to loss)
labels[attention_mask == 0] = -100
# BOOTSTRAPPING: When score is 0, mask Basil's output tokens
# This prevents reinforcing gibberish while still learning language
# patterns from the surrounding Tutor/Sophie context
basil_masked = False
if score == 0:
input_list = input_ids.tolist()
content_end = int((attention_mask == 1).sum().item())
marker_len = len(basil_marker_tokens)
# Find "\nBasil:" marker in token sequence
basil_start = -1
for i in range(content_end - marker_len + 1):
if input_list[i:i + marker_len] == basil_marker_tokens:
basil_start = i + marker_len
break
if basil_start != -1:
# Find where Basil's output ends (next speaker or end of content)
basil_end = content_end
for i in range(basil_start, content_end):
# Check for Sophie marker
if (i + len(sophie_marker_tokens) <= content_end and
input_list[i:i + len(sophie_marker_tokens)] == sophie_marker_tokens):
basil_end = i
break
# Check for Tutor marker
if (i + len(tutor_marker_tokens) <= content_end and
input_list[i:i + len(tutor_marker_tokens)] == tutor_marker_tokens):
basil_end = i
break
labels[basil_start:basil_end] = -100
basil_masked = True
n_basil_masked += 1
else:
# Fallback: couldn't find marker, don't mask (still learns from context)
print(f"[GradedDataset] WARNING: '\\nBasil:' marker not found in example "
f"{len(self.examples) + 1}, score=0 output NOT masked")
# Enhanced diagnostics: log first 3 examples
if len(self.examples) < 3:
n_supervised = (labels != -100).sum().item()
n_masked = (labels == -100).sum().item()
n_padding = (attention_mask == 0).sum().item()
n_basil_tokens_masked = n_masked - n_padding
supervised_tokens = tokenizer.decode(labels[labels != -100][:50])
print(f"[GradedDataset] Example {len(self.examples) + 1} diagnostics:")
print(f" Score: {score}, Basil masked: {basil_masked}")
print(f" Full episode phases: B+C{'+E' if sophie_post_grade else ''}{'+F' if tutor_answer else ''}")
print(f" Supervised tokens: {n_supervised} (context + post-Basil phases)")
print(f" Masked tokens: {n_masked} (padding={n_padding}, basil_output={n_basil_tokens_masked})")
print(f" Supervised text preview: {supervised_tokens[:200]}...")
print(f" Example weight: {final_weight:.3f}")
self.examples.append({
"input_ids": input_ids,
"attention_mask": attention_mask,
"labels": labels,
})
self.weights.append(final_weight)
print(f"[GradedDataset] Basil output masked in {n_basil_masked}/{len(self.examples)} examples (score=0)")
# Debug logging for recency stats
num_sessions = len(set(session_keys))
print(f"[GradedDataset] Created {len(self.examples)} weighted examples")
print(f"[GradedDataset] Recency ordering: per training run ({num_runs} runs, {num_sessions} sessions)")
print(f"[GradedDataset] Current run index: {newest_run}")
if recency_weights_debug:
min_rec = min(recency_weights_debug)
max_rec = max(recency_weights_debug)
mean_rec = sum(recency_weights_debug) / len(recency_weights_debug)
print(f"[GradedDataset] Recency weights: min={min_rec:.3f}, max={max_rec:.3f}, mean={mean_rec:.3f}")
if self.weights:
avg_weight = sum(self.weights) / len(self.weights)
print(f"[GradedDataset] Final weights (score*recency): avg={avg_weight:.3f}")
def __len__(self):
return len(self.examples)
def __getitem__(self, i):
example = self.examples[i].copy()
example["weight"] = torch.tensor(self.weights[i], dtype=torch.float32)
return example
class WorldDataset(Dataset):
"""
Dataset for the WORLD/TRUNK training objective.
Standard next-token language model on full session transcripts (Tutor + Sophie +
Story + Basil). Trains the base model to learn language and story structure.
Sliding window with stride = block_size // 2.
mask_mode controls how Basil-related tokens are handled:
"none" : No masking — trunk sees everything at weight 1.0
"basil_only" : Mask only Basil's output tokens (labels=-100)
"basil_and_after": (DEFAULT) Score-weighted masking for Basil output
(Zone A) and Sophie's immediate reaction (Zone B).
Weight = LoRA weight / TRUNK_WEIGHT_DIVISOR.
If weight is 0.0 (low-score garbage), fully masked
(labels=-100). If weight > 0.0, token_weights is set
to the fractional weight and labels are kept.
Everything after Zone B (popquiz, wrap-up, next
episode teaching) stays at full weight (1.0).
age_band is used to look up the score-to-weight mapping from
BASIL_POLICY_SCORE_WEIGHTS_TABLE, ensuring the trunk's rising quality
floor matches the LoRA's.
"""
def __init__(self, sessions: list, tokenizer, block_size: int = 1024,
mask_mode: str = "basil_and_after", age_band: int = 0):
self.examples = []
self.token_weights_list = [] # Per-chunk token weight tensors
self.mask_mode = mask_mode
self.age_band = max(0, min(int(age_band), 7))
# Compute training-run mapping for recency weighting
session_keys = [s["session_key"] for s in sessions]
session_to_run = _compute_training_run_for_sessions(session_keys)
newest_run = max(session_to_run.values()) if session_to_run else 0
num_runs = len(set(session_to_run.values()))
stride = block_size // 2 # 50% overlap between chunks
# Track diagnostics
total_tokens = 0
total_chunks = 0
total_tokens_masked = 0
total_tokens_weighted = 0
for session in sessions:
session_id = session["session_id"]
text = session["text"]
session_key = session["session_key"]
basil_spans = session.get("basil_spans", [])
# Compute recency weight for this session
run_index = session_to_run.get(session_key, newest_run)
runs_ago = newest_run - run_index
recency_w = recency_weight(runs_ago, RECENCY_HALF_LIFE_TRAIN_RUNS_GRADED)
# Tokenize full session (request offset_mapping for masking)
encoding = tokenizer(
text,
add_special_tokens=False,
return_attention_mask=False,
return_offsets_mapping=True,
)
input_ids = encoding["input_ids"]
offsets = encoding.get("offset_mapping", None)
if len(input_ids) == 0:
continue
total_tokens += len(input_ids)
# Start all tokens at weight 1.0; Basil zones will be adjusted below
token_weights = torch.ones(len(input_ids), dtype=torch.float32)
labels = torch.tensor(input_ids, dtype=torch.long)
# --- Mask / weight tokens based on mask_mode ---
if mask_mode != "none" and basil_spans and offsets:
sorted_spans = sorted(basil_spans, key=lambda s: s["start_char"])
for si, span in enumerate(sorted_spans):
score = int(span.get("score", 0))
if mask_mode == "basil_only":
# Simple: mask only Basil's output tokens
zone_a_start = span["start_char"]
zone_a_end = span["end_char"]
for tok_idx, (tok_start, tok_end) in enumerate(offsets):
if tok_end > zone_a_start and tok_start < zone_a_end:
labels[tok_idx] = -100
total_tokens_masked += 1
else:
# basil_and_after: three-zone weighted masking
# Zone A = Basil's output
# Zone B = Sophie's immediate reaction (1st speaker turn after Basil)
# Zone C = everything after Zone B (full weight, not masked)
zone_a_start = span["start_char"]
zone_a_end = span["end_char"]
# Scan forward from Basil's end to find speaker boundaries
speaker_markers = ["\nSophie:", "\nTutor:", "\nBasil:"]
pos = zone_a_end
speakers_found = 0
zone_b_end = len(text) # default: to end of text
while pos < len(text):
found_marker = False
for m in speaker_markers:
if text[pos:pos + len(m)] == m:
speakers_found += 1
if speakers_found == 2:
zone_b_end = pos
found_marker = True
break
pos += len(m)
found_marker = True
break
if zone_b_end < len(text):
break
if not found_marker:
pos += 1
# Compute trunk weight from LoRA table
score_row = BASIL_POLICY_SCORE_WEIGHTS_TABLE.get(
score, BASIL_POLICY_SCORE_WEIGHTS_TABLE[0]
)
lora_w = score_row.get(self.age_band, 0.0)
trunk_w = lora_w / TRUNK_WEIGHT_DIVISOR
# Apply to tokens in Zone A + Zone B
for tok_idx, (tok_start, tok_end) in enumerate(offsets):
if tok_end > zone_a_start and tok_start < zone_b_end:
if trunk_w == 0.0:
labels[tok_idx] = -100
total_tokens_masked += 1
else:
token_weights[tok_idx] = trunk_w
total_tokens_weighted += 1
elif mask_mode != "none" and basil_spans and offsets is None:
# Fallback: tokenizer doesn't support offset_mapping; use token-marker search
basil_marker = tokenizer.encode("\nBasil:", add_special_tokens=False)
sophie_marker = tokenizer.encode("\nSophie:", add_special_tokens=False)
tutor_marker = tokenizer.encode("\nTutor:", add_special_tokens=False)
all_markers = [sophie_marker, tutor_marker, basil_marker]
input_list = input_ids
marker_len = len(basil_marker)
sorted_fb_spans = sorted(basil_spans, key=lambda s: s["start_char"])
span_idx = 0
i = 0
while i < len(input_list) - marker_len + 1:
if input_list[i:i + marker_len] == basil_marker:
zone_a_start = i + marker_len # after "Basil:" marker
if mask_mode == "basil_only":
# Find end of Basil's output (next speaker marker)
zone_a_end_fb = len(input_list)
for j in range(zone_a_start, len(input_list)):
for marker in all_markers:
if (j + len(marker) <= len(input_list) and
input_list[j:j + len(marker)] == marker):
zone_a_end_fb = j
break
if zone_a_end_fb != len(input_list):
break
labels[zone_a_start:zone_a_end_fb] = -100
total_tokens_masked += (zone_a_end_fb - zone_a_start)
i = zone_a_end_fb
else:
# basil_and_after: three-zone weighted masking
# Find Zone A end (1st speaker) and Zone B end (2nd speaker)
speakers_found = 0
zone_b_end_fb = len(input_list)
for j in range(zone_a_start, len(input_list)):
for marker in all_markers:
if (j + len(marker) <= len(input_list) and
input_list[j:j + len(marker)] == marker):
speakers_found += 1
if speakers_found == 2:
zone_b_end_fb = j
break
if zone_b_end_fb != len(input_list):
break
# Look up score from basil_spans (matched by order)
fb_score = 0
if span_idx < len(sorted_fb_spans):
fb_score = int(sorted_fb_spans[span_idx].get("score", 0))
span_idx += 1
score_row = BASIL_POLICY_SCORE_WEIGHTS_TABLE.get(
fb_score, BASIL_POLICY_SCORE_WEIGHTS_TABLE[0]
)
lora_w = score_row.get(self.age_band, 0.0)
trunk_w = lora_w / TRUNK_WEIGHT_DIVISOR
if trunk_w == 0.0:
labels[zone_a_start:zone_b_end_fb] = -100
total_tokens_masked += (zone_b_end_fb - zone_a_start)
else:
for k in range(zone_a_start, zone_b_end_fb):
token_weights[k] = trunk_w
total_tokens_weighted += (zone_b_end_fb - zone_a_start)
i = zone_b_end_fb
else:
i += 1
# Apply recency weight as multiplier
token_weights = token_weights * recency_w
# Sliding window: create chunks with stride