debug to train script
Browse files- scripts/train.py +53 -63
scripts/train.py
CHANGED
|
@@ -9,6 +9,7 @@ from tqdm import tqdm
|
|
| 9 |
|
| 10 |
class CustomDataset(Dataset):
|
| 11 |
def __init__(self, tokenizer, dataset_name="allenai/tulu-v2-sft-mixture", max_length=512):
|
|
|
|
| 12 |
self.dataset = load_dataset(dataset_name, split="train") # Use train split
|
| 13 |
self.tokenizer = tokenizer
|
| 14 |
self.max_length = max_length
|
|
@@ -26,6 +27,10 @@ class CustomDataset(Dataset):
|
|
| 26 |
truncation=True,
|
| 27 |
return_tensors="pt"
|
| 28 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
return {
|
| 30 |
"input_ids": encoding["input_ids"].squeeze(),
|
| 31 |
"attention_mask": encoding["attention_mask"].squeeze(),
|
|
@@ -33,84 +38,69 @@ class CustomDataset(Dataset):
|
|
| 33 |
}
|
| 34 |
|
| 35 |
def expand_model_with_small_experts(base_model):
|
| 36 |
-
#
|
| 37 |
config = base_model.config
|
| 38 |
-
config.num_small_experts = 64 # Add 64 small experts
|
| 39 |
-
config.small_expert_intermediate_size = config.intermediate_size // 2 # Half size
|
| 40 |
-
|
| 41 |
-
# Create new model with expanded architecture
|
| 42 |
expanded_model = MyOlmoeForCausalLM(config)
|
| 43 |
|
| 44 |
-
# 1. Copy all non-expert weights exactly
|
| 45 |
base_state_dict = base_model.state_dict()
|
| 46 |
expanded_state_dict = expanded_model.state_dict()
|
| 47 |
|
| 48 |
-
#
|
| 49 |
for name, param in base_state_dict.items():
|
| 50 |
-
if "experts" not in name and "gate" not in name:
|
| 51 |
-
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
-
#
|
| 54 |
for i in range(config.num_experts):
|
| 55 |
-
# Copy expert weights
|
| 56 |
for proj in ['gate_proj', 'up_proj', 'down_proj']:
|
| 57 |
-
|
| 58 |
-
|
|
|
|
| 59 |
if proj == 'down_proj':
|
| 60 |
-
|
| 61 |
-
expanded_state_dict[f'model.layers.{i}.mlp.experts.{i}.{proj}.weight'].copy_(
|
| 62 |
-
orig_weight[:, :config.small_expert_intermediate_size]
|
| 63 |
-
)
|
| 64 |
else:
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
#
|
| 71 |
for i in range(config.num_hidden_layers):
|
| 72 |
gate_key = f'model.layers.{i}.mlp.gate.weight'
|
| 73 |
if gate_key in base_state_dict:
|
| 74 |
original_gate = base_state_dict[gate_key]
|
| 75 |
new_gate = expanded_state_dict[gate_key]
|
| 76 |
-
|
| 77 |
-
# Copy original gate weights for the first 64 experts
|
| 78 |
new_gate[:, :config.num_experts].copy_(original_gate)
|
| 79 |
-
|
| 80 |
-
#
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
# Load the combined state dict into the new model
|
| 88 |
-
expanded_model.load_state_dict(expanded_state_dict, strict=False) # Note strict=False
|
| 89 |
|
| 90 |
return expanded_model
|
| 91 |
|
| 92 |
def main():
|
| 93 |
-
# Load base model (with only 64 experts)
|
| 94 |
model_path = "myolmoe"
|
| 95 |
-
print("Loading base model...")
|
| 96 |
base_model = MyOlmoeForCausalLM.from_pretrained(model_path)
|
| 97 |
|
| 98 |
-
#
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
# Expand model to include small experts
|
| 102 |
-
print("Expanding model with small experts...")
|
| 103 |
model = expand_model_with_small_experts(base_model)
|
| 104 |
|
| 105 |
-
#
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
# Prepare dataset
|
| 109 |
-
print("Preparing dataset...")
|
| 110 |
tokenizer = AutoTokenizer.from_pretrained(model_path)
|
| 111 |
dataset = CustomDataset(tokenizer)
|
| 112 |
-
|
| 113 |
-
#
|
| 114 |
training_args = TrainingArguments(
|
| 115 |
output_dir="./output",
|
| 116 |
per_device_train_batch_size=4,
|
|
@@ -126,20 +116,22 @@ def main():
|
|
| 126 |
gradient_checkpointing=True,
|
| 127 |
report_to="tensorboard"
|
| 128 |
)
|
| 129 |
-
|
| 130 |
-
# Custom trainer to handle expert freezing
|
| 131 |
class MoETrainer(Trainer):
|
| 132 |
def __init__(self, *args, **kwargs):
|
| 133 |
self.freeze_existing = kwargs.pop('freeze_existing_experts', False)
|
| 134 |
super().__init__(*args, **kwargs)
|
| 135 |
-
|
| 136 |
if self.freeze_existing:
|
| 137 |
-
#
|
|
|
|
| 138 |
for name, param in self.model.named_parameters():
|
| 139 |
if "mlp.experts" in name and "small_experts" not in name:
|
| 140 |
param.requires_grad = False
|
| 141 |
-
|
| 142 |
-
|
|
|
|
|
|
|
| 143 |
trainer = MoETrainer(
|
| 144 |
model=model,
|
| 145 |
args=training_args,
|
|
@@ -147,18 +139,16 @@ def main():
|
|
| 147 |
eval_dataset=dataset,
|
| 148 |
freeze_existing_experts=True
|
| 149 |
)
|
| 150 |
-
|
| 151 |
-
#
|
| 152 |
-
print("Starting training...")
|
| 153 |
trainer.train()
|
| 154 |
-
|
| 155 |
-
# Save final model
|
| 156 |
output_dir = "./final_model"
|
| 157 |
os.makedirs(output_dir, exist_ok=True)
|
| 158 |
-
print(f"Saving final model to {output_dir}")
|
| 159 |
model.save_pretrained(output_dir)
|
| 160 |
tokenizer.save_pretrained(output_dir)
|
| 161 |
-
print("Training complete!")
|
| 162 |
|
| 163 |
if __name__ == "__main__":
|
| 164 |
-
main()
|
|
|
|
| 9 |
|
| 10 |
class CustomDataset(Dataset):
|
| 11 |
def __init__(self, tokenizer, dataset_name="allenai/tulu-v2-sft-mixture", max_length=512):
|
| 12 |
+
print(f"# DEBUG: Loading dataset '{dataset_name}' with max length {max_length}")
|
| 13 |
self.dataset = load_dataset(dataset_name, split="train") # Use train split
|
| 14 |
self.tokenizer = tokenizer
|
| 15 |
self.max_length = max_length
|
|
|
|
| 27 |
truncation=True,
|
| 28 |
return_tensors="pt"
|
| 29 |
)
|
| 30 |
+
# DEBUG: Print the first few token IDs for inspection
|
| 31 |
+
if idx == 0:
|
| 32 |
+
print(f"# DEBUG: Sample input text: {text[:100]}")
|
| 33 |
+
print(f"# DEBUG: Tokenized input_ids[:10]: {encoding['input_ids'][0][:10]}")
|
| 34 |
return {
|
| 35 |
"input_ids": encoding["input_ids"].squeeze(),
|
| 36 |
"attention_mask": encoding["attention_mask"].squeeze(),
|
|
|
|
| 38 |
}
|
| 39 |
|
| 40 |
def expand_model_with_small_experts(base_model):
|
| 41 |
+
print("# DEBUG: Expanding model with small experts...")
|
| 42 |
config = base_model.config
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
expanded_model = MyOlmoeForCausalLM(config)
|
| 44 |
|
|
|
|
| 45 |
base_state_dict = base_model.state_dict()
|
| 46 |
expanded_state_dict = expanded_model.state_dict()
|
| 47 |
|
| 48 |
+
print("# DEBUG: Copying non-expert parameters...")
|
| 49 |
for name, param in base_state_dict.items():
|
| 50 |
+
if "experts" not in name and "gate" not in name:
|
| 51 |
+
if name in expanded_state_dict:
|
| 52 |
+
expanded_state_dict[name].copy_(param)
|
| 53 |
+
else:
|
| 54 |
+
print(f"# DEBUG: Skipped non-expert param {name} (not found in expanded model)")
|
| 55 |
|
| 56 |
+
print("# DEBUG: Copying expert weights...")
|
| 57 |
for i in range(config.num_experts):
|
|
|
|
| 58 |
for proj in ['gate_proj', 'up_proj', 'down_proj']:
|
| 59 |
+
key = f'model.layers.{i}.mlp.experts.{i}.{proj}.weight'
|
| 60 |
+
if key in base_state_dict:
|
| 61 |
+
orig_weight = base_state_dict[key]
|
| 62 |
if proj == 'down_proj':
|
| 63 |
+
expanded_state_dict[key].copy_(orig_weight[:, :config.small_expert_intermediate_size])
|
|
|
|
|
|
|
|
|
|
| 64 |
else:
|
| 65 |
+
expanded_state_dict[key].copy_(orig_weight[:config.small_expert_intermediate_size])
|
| 66 |
+
print(f"# DEBUG: Copied {proj} weights for expert {i}")
|
| 67 |
+
else:
|
| 68 |
+
print(f"# DEBUG: Missing {key} in base model")
|
| 69 |
+
|
| 70 |
+
print("# DEBUG: Expanding and initializing gate weights...")
|
| 71 |
for i in range(config.num_hidden_layers):
|
| 72 |
gate_key = f'model.layers.{i}.mlp.gate.weight'
|
| 73 |
if gate_key in base_state_dict:
|
| 74 |
original_gate = base_state_dict[gate_key]
|
| 75 |
new_gate = expanded_state_dict[gate_key]
|
|
|
|
|
|
|
| 76 |
new_gate[:, :config.num_experts].copy_(original_gate)
|
| 77 |
+
torch.nn.init.normal_(new_gate[:, config.num_experts:], mean=0.0, std=config.initializer_range * 0.1)
|
| 78 |
+
print(f"# DEBUG: Initialized gate for layer {i}")
|
| 79 |
+
else:
|
| 80 |
+
print(f"# DEBUG: Missing gate weight {gate_key}")
|
| 81 |
+
|
| 82 |
+
print("# DEBUG: Loading expanded state dict into model...")
|
| 83 |
+
expanded_model.load_state_dict(expanded_state_dict, strict=False)
|
|
|
|
|
|
|
|
|
|
| 84 |
|
| 85 |
return expanded_model
|
| 86 |
|
| 87 |
def main():
|
|
|
|
| 88 |
model_path = "myolmoe"
|
| 89 |
+
print("# DEBUG: Loading base model...")
|
| 90 |
base_model = MyOlmoeForCausalLM.from_pretrained(model_path)
|
| 91 |
|
| 92 |
+
print(f"# DEBUG: Base model has {base_model.config.num_experts} experts")
|
| 93 |
+
|
| 94 |
+
print("# DEBUG: Calling expand_model_with_small_experts()...")
|
|
|
|
|
|
|
| 95 |
model = expand_model_with_small_experts(base_model)
|
| 96 |
|
| 97 |
+
print(f"# DEBUG: Expanded model has {model.config.num_experts} regular experts and {model.config.num_small_experts} small experts")
|
| 98 |
+
|
| 99 |
+
print("# DEBUG: Loading tokenizer and preparing dataset...")
|
|
|
|
|
|
|
| 100 |
tokenizer = AutoTokenizer.from_pretrained(model_path)
|
| 101 |
dataset = CustomDataset(tokenizer)
|
| 102 |
+
|
| 103 |
+
print("# DEBUG: Setting up training arguments...")
|
| 104 |
training_args = TrainingArguments(
|
| 105 |
output_dir="./output",
|
| 106 |
per_device_train_batch_size=4,
|
|
|
|
| 116 |
gradient_checkpointing=True,
|
| 117 |
report_to="tensorboard"
|
| 118 |
)
|
| 119 |
+
|
|
|
|
| 120 |
class MoETrainer(Trainer):
|
| 121 |
def __init__(self, *args, **kwargs):
|
| 122 |
self.freeze_existing = kwargs.pop('freeze_existing_experts', False)
|
| 123 |
super().__init__(*args, **kwargs)
|
| 124 |
+
|
| 125 |
if self.freeze_existing:
|
| 126 |
+
print("# DEBUG: Freezing original expert parameters...")
|
| 127 |
+
frozen_count = 0
|
| 128 |
for name, param in self.model.named_parameters():
|
| 129 |
if "mlp.experts" in name and "small_experts" not in name:
|
| 130 |
param.requires_grad = False
|
| 131 |
+
frozen_count += 1
|
| 132 |
+
print(f"# DEBUG: Total frozen expert parameters: {frozen_count}")
|
| 133 |
+
|
| 134 |
+
print("# DEBUG: Initializing trainer...")
|
| 135 |
trainer = MoETrainer(
|
| 136 |
model=model,
|
| 137 |
args=training_args,
|
|
|
|
| 139 |
eval_dataset=dataset,
|
| 140 |
freeze_existing_experts=True
|
| 141 |
)
|
| 142 |
+
|
| 143 |
+
print("# DEBUG: Starting training...")
|
|
|
|
| 144 |
trainer.train()
|
| 145 |
+
|
|
|
|
| 146 |
output_dir = "./final_model"
|
| 147 |
os.makedirs(output_dir, exist_ok=True)
|
| 148 |
+
print(f"# DEBUG: Saving final model to {output_dir}...")
|
| 149 |
model.save_pretrained(output_dir)
|
| 150 |
tokenizer.save_pretrained(output_dir)
|
| 151 |
+
print("# DEBUG: Training complete!")
|
| 152 |
|
| 153 |
if __name__ == "__main__":
|
| 154 |
+
main()
|