File size: 9,328 Bytes
c4785c5
48f0e60
c4785c5
 
 
 
 
 
 
48f0e60
c4785c5
b63994d
e785830
 
48f0e60
c4785c5
7abbd62
78b85e8
 
 
 
 
 
 
 
c4785c5
 
 
 
e039ec3
 
c4785c5
48f0e60
c4785c5
 
 
582cd6b
c4785c5
5b01886
325d2d0
c4785c5
1e0b293
 
 
 
 
 
 
 
 
 
 
 
 
5c05368
 
52bdc02
 
 
 
 
5c05368
 
1e0b293
c4785c5
 
 
 
 
 
b63994d
c4785c5
48f0e60
be580d6
f03d4f8
48f0e60
325d2d0
d4a6b93
48f0e60
c4785c5
5b4ec54
5af07d9
c4785c5
1f3825f
c4785c5
 
 
 
 
48f0e60
f9596a0
 
356573e
 
c4785c5
356573e
325d2d0
356573e
834ad70
 
 
 
356573e
325d2d0
01ec808
 
 
 
 
 
 
 
 
 
 
 
 
 
834ad70
325d2d0
 
 
 
 
 
f9596a0
325d2d0
f9596a0
 
325d2d0
f9596a0
7050cb6
45d6e50
325d2d0
45d6e50
 
 
325d2d0
45d6e50
 
 
 
 
1f3825f
 
 
 
 
 
325d2d0
e785830
 
 
 
be580d6
 
 
e785830
be580d6
 
 
 
 
 
 
 
e785830
 
 
 
01ec808
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
325d2d0
 
 
48f0e60
 
c4785c5
f9596a0
01ec808
 
 
 
48f0e60
c4785c5
1f3825f
 
580eff8
 
 
 
 
 
1f3825f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e785830
 
3ed7a55
 
e785830
 
3ed7a55
 
 
 
 
e785830
3ed7a55
 
e785830
 
3ed7a55
c4785c5
325d2d0
e785830
 
f9596a0
325d2d0
f9596a0
 
325d2d0
f9596a0
 
 
 
 
48f0e60
 
c4785c5
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
#!/usr/bin/env python3
import torch
from torch.utils.data import DataLoader
from transformers import (
    AutoTokenizer,
    TrainingArguments,
    Trainer,
    default_data_collator,
)
from datasets import load_dataset
from myolmoe import MyOlmoeForCausalLM, OlmoeConfig
import os
from transformers import TrainerCallback
import subprocess

def main():
    print("Starting my COOL OLMoE training script for small experts")
    # Load config - first try from local file, then from pretrained
    config_path = os.path.join("myolmoe", "config.json")
    if os.path.exists(config_path):
        config = OlmoeConfig.from_json_file(config_path)
    else:
        config = OlmoeConfig.from_pretrained("myolmoe")
    
    # Load model
    model = MyOlmoeForCausalLM.from_pretrained(
        "myolmoe",
        config=config,
        torch_dtype=torch.bfloat16,
        device_map="auto",
        ignore_mismatched_sizes=True
    )
    
    # Load tokenizer
    tokenizer = AutoTokenizer.from_pretrained("myolmoe")
    tokenizer.pad_token = tokenizer.eos_token
    
    # Load dataset
    dataset = load_dataset("allenai/tulu-v2-sft-mixture", split="train")
    
    def tokenize_function(examples):
        texts = []
        for message_list in examples["messages"]:
            formatted = ""
            for msg in message_list:
                role = msg["role"]
                content = msg["content"]
                if role == "user":
                    formatted += f"User: {content}\n"
                elif role == "assistant":
                    formatted += f"Assistant: {content}\n"
                else:
                    formatted += f"{role.capitalize()}: {content}\n"
            texts.append(formatted)

        tokenized = tokenizer(
            texts,
            truncation=True,
            max_length=4096,
            padding="max_length"
        )
        tokenized["labels"] = tokenized["input_ids"].copy()
        return tokenized

    tokenized_dataset = dataset.map(
        tokenize_function,
        batched=True,
        remove_columns=dataset.column_names,
        num_proc=4
    )
    
    # Training arguments
    training_args = TrainingArguments(
        output_dir="./checkpoints",
        per_device_train_batch_size=2,
        gradient_accumulation_steps=8,
        learning_rate=1e-4,
        num_train_epochs=3,
        logging_dir="./logs",
        logging_steps=10,
        save_steps=20,
        save_total_limit=1,
        bf16=True,
        gradient_checkpointing=False,  # Disabled for now
        report_to="tensorboard",
        optim="adamw_torch",
        lr_scheduler_type="cosine",
        warmup_ratio=0.1,
        max_grad_norm=1.0,
    )
    
    # Freeze all parameters first
    for param in model.parameters():
        param.requires_grad = False
    
    # Unfreeze only the small experts and their gating networks
    trainable_params = []
    for name, param in model.named_parameters():
        if (
            "small_experts" in name or
            "small_gate" in name
        ):
            param.requires_grad = True
            trainable_params.append(name)
    ### ADDED: Check if small experts were found
    if trainable_params:
        print(f"[INFO] Found {len(trainable_params)} small_expert/small_gate parameters.")
    else:
        print("[WARNING] No small_expert or small_gate parameters found in model!")

    # Verify gradient requirements
    unfrozen = [name for name, param in model.named_parameters() if param.requires_grad]
    if unfrozen:
        print(f"[INFO] {len(unfrozen)} parameters are unfrozen and trainable.")
        for name in unfrozen:
            print(f"   - {name}")
    else:
        print("[ERROR] No parameters were unfrozen! Training will not update anything.")

    print(f"Total trainable parameters: {len(trainable_params)}")
    
    # Verify gradient requirements
    for name, param in model.named_parameters():
        if param.requires_grad:
            print(f"Parameter {name} requires grad: {param.requires_grad}")

    # Custom data collator
    def data_collator(features):
        batch = default_data_collator(features)
        batch["output_router_logits"] = True
        return batch

    # Fixed CustomTrainer class that handles all possible arguments
    class CustomTrainer(Trainer):
        def compute_loss(self, model, inputs, return_outputs=False, **kwargs):
            # Remove any unexpected arguments
            inputs = {k: v for k, v in inputs.items() if k not in ['num_items_in_batch']}
            
            # Ensure we're in training mode
            model.train()
            
            # Forward pass with gradients
            with torch.set_grad_enabled(True):
                outputs = model(**inputs)
                loss = outputs.loss
                
                if not loss.requires_grad:
                    raise RuntimeError("Loss doesn't require gradients. Check model parameters.")
                
                return (loss, outputs) if return_outputs else loss
            
    class GitPushCallback(TrainerCallback):
        def on_save(self, args, state, control, **kwargs):
            try:
                print("Saving checkpoint to Git repo...")
                
                # Add all changes (you can scope this to ./checkpoints/ if desired)
                subprocess.run(["git", "add", "."], check=True)

                # Skip commit if no changes
                result = subprocess.run(["git", "diff", "--cached", "--quiet"])
                if result.returncode == 0:
                    print("No changes to commit.")
                    return

                subprocess.run(["git", "commit", "-m", f'Checkpoint at step {state.global_step}'], check=True)
                subprocess.run(["git", "push"], check=True)
                print("Checkpoint pushed successfully.")
            except subprocess.CalledProcessError as e:
                print(f"Git push failed: {e}")
    class SmallExpertSaveCallback(TrainerCallback):
        def __init__(self, model, trainable_params):
            self.model = model
            self.trainable_params = trainable_params

        def on_save(self, args, state, control, **kwargs):
            # Define save path inside the checkpoint dir
            checkpoint_dir = os.path.join(args.output_dir, f"checkpoint-{state.global_step}")
            small_expert_path = os.path.join(checkpoint_dir, "small_experts_and_gates.bin")

            small_expert_state_dict = {
                name: param for name, param in self.model.named_parameters()
                if name in self.trainable_params
            }

            if small_expert_state_dict:
                os.makedirs(checkpoint_dir, exist_ok=True)
                torch.save(small_expert_state_dict, small_expert_path)
                print(f"[INFO] Saved {len(small_expert_state_dict)} small_expert/small_gate parameters "
                    f"to {small_expert_path}")
            else:
                print("[ERROR] No small_expert or small_gate parameters found to save!")

    # Initialize trainer
    trainer = CustomTrainer(
        model=model,
        args=training_args,
        train_dataset=tokenized_dataset,
        data_collator=data_collator,
        callbacks=[
            GitPushCallback(),
            SmallExpertSaveCallback(model, trainable_params)
        ]
    )
    
    # Test forward/backward pass before training
    print("Testing gradient flow...")
    test_loader = DataLoader(tokenized_dataset, batch_size=1, collate_fn=data_collator)
    test_batch = next(iter(test_loader))
    
    # Move batch to model's device
    device = next(model.parameters()).device
    test_batch = {k: v.to(device) if isinstance(v, torch.Tensor) else v for k, v in test_batch.items()}
    
    model.train()
    outputs = model(**test_batch)
    loss = outputs.loss
    print(f"Initial loss: {loss.item()}")
    
    loss.backward()
    print("Gradients computed successfully")
    
    # Check which parameters received gradients
    for name, param in model.named_parameters():
        if param.grad is not None:
            print(f"Parameter {name} received gradients")
    
    # Reset gradients
    model.zero_grad()

    # Check for existing checkpoint
    import re

    checkpoint_dir = None
    if os.path.isdir(training_args.output_dir):
        checkpoints = [
            os.path.join(training_args.output_dir, d)
            for d in os.listdir(training_args.output_dir)
            if re.match(r"checkpoint-\d+", d)
        ]
        if checkpoints:
            # Extract step numbers and find the highest
            checkpoint_dir = max(checkpoints, key=lambda x: int(x.split('-')[-1]))
            print(f"Resuming from checkpoint: {checkpoint_dir}")


    # Train
    print("Starting training...")
    trainer.train(resume_from_checkpoint=checkpoint_dir)

    # Save only the small experts and gates
    print("Saving small experts and gates...")
    small_expert_state_dict = {
        name: param for name, param in model.named_parameters()
        if name in trainable_params
    }
    
    os.makedirs("./final_model", exist_ok=True)
    torch.save(small_expert_state_dict, "./final_model/small_experts_and_gates.bin")
    config.save_pretrained("./final_model")

if __name__ == "__main__":
    main()