td-builder commited on
Commit
4fbe7a5
·
verified ·
1 Parent(s): 0cb2e84

Upload 163 files

Browse files
Files changed (1) hide show
  1. hugging/td_fuse/selfimprove.py +51 -16
hugging/td_fuse/selfimprove.py CHANGED
@@ -1,19 +1,22 @@
1
  """
2
- TD Self-Improvement v6 — MEGA CYCLE
3
 
4
- v5 fixes + MEGA MODE for cycle 3+:
 
 
 
 
 
 
 
 
5
  - 8000+ training samples (was 3000)
6
  - Priority: code, math, reasoning, creativity (top), then general (second)
7
  - LoRA r=128 (was 64) — maximum reshape capacity
8
  - ALL 36 layers targeted (was 16)
9
- - gradient_checkpointing for speed + VRAM savings
10
- - batch_size 4 (was 2) — 2x faster per step
11
  - Norm unclogging continues from cycle 2
12
-
13
- SPEED OPTIMIZATIONS:
14
- - gradient_checkpointing = True (saves ~40% VRAM, allows bigger batches)
15
- - batch_size 4 + grad_accum 4 = effective batch 16 (same quality, faster)
16
- - Processes 2x more samples per forward pass = ~2x faster wall clock
17
  """
18
 
19
  import torch
@@ -65,14 +68,23 @@ class SelfImproveConfig:
65
 
66
 
67
  def apply_mega_mode(cfg: SelfImproveConfig):
68
- """Crank everything up for mega cycles (3+)."""
69
- print("\n *** MEGA MODE ENABLED ***")
 
 
 
 
 
 
 
 
 
70
  cfg.mega_mode = True
71
  cfg.top_n_layers = 36 # ALL layers — leave nothing behind
72
  cfg.min_improvement_score = 0.0 # Target everything
73
  cfg.lora_r = 128 # Maximum reshape capacity
74
  cfg.lora_alpha = 256 # 2x rank
75
- cfg.train_epochs = 3 # 3 epochs over 8000 samples = plenty
76
  cfg.train_batch = 4 # 2x bigger batch — 2x faster
77
  cfg.train_grad_accum = 4 # Effective batch = 16 (same quality)
78
  cfg.num_train_samples = 8000 # Nearly 3x more data
@@ -83,7 +95,8 @@ def apply_mega_mode(cfg: SelfImproveConfig):
83
  print(f" Layers: ALL {cfg.top_n_layers}")
84
  print(f" Data: {cfg.num_train_samples} samples")
85
  print(f" Batch: {cfg.train_batch} × {cfg.train_grad_accum} = {cfg.train_batch * cfg.train_grad_accum}")
86
- print(f" Speed: gradient_checkpointing + batch 4")
 
87
 
88
 
89
  def auto_detect_model_path() -> Tuple[str, int]:
@@ -679,11 +692,15 @@ def improve_with_lora(model_path: str, target_layers: List[int],
679
  return model_path
680
 
681
  # Load model with OOM guard
 
 
 
682
  print(" Loading model...")
683
  try:
684
  model = AutoModelForImageTextToText.from_pretrained(
685
  model_path, dtype=torch.bfloat16,
686
- device_map="auto", trust_remote_code=True
 
687
  )
688
  except (RuntimeError, Exception) as e:
689
  gc.collect()
@@ -1012,13 +1029,13 @@ def improve_with_lora(model_path: str, target_layers: List[int],
1012
 
1013
  random.shuffle(train_texts)
1014
 
1015
- # Tokenize
1016
  class ImproveDataset(Dataset):
1017
  def __init__(self, texts, tokenizer, max_len=1024):
1018
  self.data = []
1019
  for t in texts:
1020
  e = tokenizer(t, truncation=True, max_length=max_len,
1021
- padding="max_length", return_tensors="pt")
1022
  self.data.append({
1023
  "input_ids": e["input_ids"].squeeze(),
1024
  "attention_mask": e["attention_mask"].squeeze(),
@@ -1070,6 +1087,7 @@ def improve_with_lora(model_path: str, target_layers: List[int],
1070
  gradient_accumulation_steps=cfg.train_grad_accum,
1071
  learning_rate=cfg.learning_rate,
1072
  bf16=True,
 
1073
  gradient_checkpointing=cfg.mega_mode, # Saves ~40% VRAM in mega mode
1074
  logging_steps=max(1, total_steps // 20),
1075
  save_strategy="steps",
@@ -1079,12 +1097,29 @@ def improve_with_lora(model_path: str, target_layers: List[int],
1079
  lr_scheduler_type="cosine",
1080
  optim="adamw_torch",
1081
  report_to="none",
 
 
1082
  )
1083
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1084
  trainer_kwargs = {
1085
  "model": model,
1086
  "processing_class": tokenizer,
1087
  "train_dataset": dataset,
 
1088
  "args": args,
1089
  }
1090
  if optimizer is not None:
 
1
  """
2
+ TD Self-Improvement v7 — SPEED OPTIMIZED MEGA CYCLE
3
 
4
+ v7 speed changes (March 2026):
5
+ - Flash Attention 2: 30-40% faster attention computation
6
+ - TF32 math: ~15-20% faster matrix multiply on Ampere GPUs (A6000)
7
+ - Dynamic padding: pad to longest-in-batch, not fixed 1024 tokens
8
+ - 4 dataloader workers + pin_memory: parallel data loading
9
+ - 2 epochs (was 3): model at 95%+, third epoch had diminishing returns
10
+ - Combined: ~50-60% faster → estimated 3-4 hours per cycle (was 6-7)
11
+
12
+ v6 MEGA MODE (unchanged):
13
  - 8000+ training samples (was 3000)
14
  - Priority: code, math, reasoning, creativity (top), then general (second)
15
  - LoRA r=128 (was 64) — maximum reshape capacity
16
  - ALL 36 layers targeted (was 16)
17
+ - gradient_checkpointing for VRAM savings
18
+ - batch_size 4 + grad_accum 4 = effective batch 16
19
  - Norm unclogging continues from cycle 2
 
 
 
 
 
20
  """
21
 
22
  import torch
 
68
 
69
 
70
  def apply_mega_mode(cfg: SelfImproveConfig):
71
+ """Crank everything up for mega cycles (3+).
72
+
73
+ v7 SPEED optimizations (March 2026):
74
+ - Flash Attention 2: 30-40% faster attention
75
+ - TF32 math: ~15-20% faster matmul on Ampere GPUs
76
+ - Dynamic padding: no wasted compute on short samples
77
+ - 4 dataloader workers: parallel data prep
78
+ - 2 epochs (was 3): model is 95%+, diminishing returns on epoch 3
79
+ Combined: ~50-60% faster → ~3-4 hours per cycle instead of 6-7
80
+ """
81
+ print("\n *** MEGA MODE ENABLED (v7 — speed optimized) ***")
82
  cfg.mega_mode = True
83
  cfg.top_n_layers = 36 # ALL layers — leave nothing behind
84
  cfg.min_improvement_score = 0.0 # Target everything
85
  cfg.lora_r = 128 # Maximum reshape capacity
86
  cfg.lora_alpha = 256 # 2x rank
87
+ cfg.train_epochs = 2 # 2 epochs — model is 95%+, 3rd epoch = diminishing returns
88
  cfg.train_batch = 4 # 2x bigger batch — 2x faster
89
  cfg.train_grad_accum = 4 # Effective batch = 16 (same quality)
90
  cfg.num_train_samples = 8000 # Nearly 3x more data
 
95
  print(f" Layers: ALL {cfg.top_n_layers}")
96
  print(f" Data: {cfg.num_train_samples} samples")
97
  print(f" Batch: {cfg.train_batch} × {cfg.train_grad_accum} = {cfg.train_batch * cfg.train_grad_accum}")
98
+ print(f" Epochs: {cfg.train_epochs} (was 3 — 33% time saved)")
99
+ print(f" Speed: flash_attn2 + tf32 + dynamic_pad + gradient_checkpointing")
100
 
101
 
102
  def auto_detect_model_path() -> Tuple[str, int]:
 
692
  return model_path
693
 
694
  # Load model with OOM guard
695
+ # SPEED: Enable TF32 for ~15-20% faster matmul on Ampere GPUs (A6000)
696
+ torch.backends.cuda.matmul.allow_tf32 = True
697
+ torch.backends.cudnn.allow_tf32 = True
698
  print(" Loading model...")
699
  try:
700
  model = AutoModelForImageTextToText.from_pretrained(
701
  model_path, dtype=torch.bfloat16,
702
+ device_map="auto", trust_remote_code=True,
703
+ attn_implementation="flash_attention_2" # SPEED: 30-40% faster attention
704
  )
705
  except (RuntimeError, Exception) as e:
706
  gc.collect()
 
1029
 
1030
  random.shuffle(train_texts)
1031
 
1032
+ # Tokenize — SPEED: dynamic padding (pad to longest in batch, not fixed 1024)
1033
  class ImproveDataset(Dataset):
1034
  def __init__(self, texts, tokenizer, max_len=1024):
1035
  self.data = []
1036
  for t in texts:
1037
  e = tokenizer(t, truncation=True, max_length=max_len,
1038
+ return_tensors="pt") # No padding here — collator handles it
1039
  self.data.append({
1040
  "input_ids": e["input_ids"].squeeze(),
1041
  "attention_mask": e["attention_mask"].squeeze(),
 
1087
  gradient_accumulation_steps=cfg.train_grad_accum,
1088
  learning_rate=cfg.learning_rate,
1089
  bf16=True,
1090
+ tf32=True, # SPEED: ~15-20% faster on Ampere GPUs
1091
  gradient_checkpointing=cfg.mega_mode, # Saves ~40% VRAM in mega mode
1092
  logging_steps=max(1, total_steps // 20),
1093
  save_strategy="steps",
 
1097
  lr_scheduler_type="cosine",
1098
  optim="adamw_torch",
1099
  report_to="none",
1100
+ dataloader_num_workers=4, # SPEED: parallel data loading
1101
+ dataloader_pin_memory=True, # SPEED: faster CPU→GPU transfer
1102
  )
1103
 
1104
+ # SPEED: Dynamic padding collator — pads to longest in batch, not fixed 1024
1105
+ # Custom because labels need -100 padding (ignore index), not tokenizer pad_id
1106
+ def dynamic_pad_collator(batch):
1107
+ max_len = max(item["input_ids"].size(0) for item in batch)
1108
+ pad_id = tokenizer.pad_token_id if tokenizer.pad_token_id is not None else 0
1109
+ input_ids, attention_mask, labels = [], [], []
1110
+ for item in batch:
1111
+ seq_len = item["input_ids"].size(0)
1112
+ pad_len = max_len - seq_len
1113
+ input_ids.append(torch.cat([item["input_ids"], torch.full((pad_len,), pad_id, dtype=torch.long)]))
1114
+ attention_mask.append(torch.cat([item["attention_mask"], torch.zeros(pad_len, dtype=torch.long)]))
1115
+ labels.append(torch.cat([item["labels"], torch.full((pad_len,), -100, dtype=torch.long)]))
1116
+ return {"input_ids": torch.stack(input_ids), "attention_mask": torch.stack(attention_mask), "labels": torch.stack(labels)}
1117
+
1118
  trainer_kwargs = {
1119
  "model": model,
1120
  "processing_class": tokenizer,
1121
  "train_dataset": dataset,
1122
+ "data_collator": dynamic_pad_collator,
1123
  "args": args,
1124
  }
1125
  if optimizer is not None: