File size: 4,876 Bytes
c4c8fb6
 
 
 
 
 
 
 
 
57eb7f4
c4c8fb6
 
cc40b37
 
c4c8fb6
cc40b37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4c8fb6
 
 
 
 
 
 
 
 
 
 
 
cc40b37
c4c8fb6
 
 
 
 
 
 
 
 
 
51f2279
c4c8fb6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
001ac9b
c4c8fb6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc40b37
c4c8fb6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
001ac9b
cc40b37
c4c8fb6
001ac9b
c4c8fb6
 
 
692759a
 
 
 
c4c8fb6
 
001ac9b
 
c4c8fb6
692759a
c4c8fb6
 
cc40b37
 
c4c8fb6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc40b37
c4c8fb6
 
 
 
 
 
cc40b37
c4c8fb6
 
 
 
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
# /// script
# dependencies = [
#     "trl",
#     "peft",
#     "datasets",
#     "transformers",
#     "accelerate",
#     "torch",
#     "deepspeed",
#     "mpi4py"
# ]
# ///
import time
from transformers import TrainerCallback

class SpeedCallback(TrainerCallback):
    def __init__(self):
        self.last_time = None

    def on_step_begin(self, args, state, control, **kwargs):
        self.last_time = time.time()

    def on_step_end(self, args, state, control, **kwargs):
        if self.last_time is None:
            return

        elapsed = time.time() - self.last_time
        remaining = max(0, state.max_steps - state.global_step)
        eta_min = remaining * elapsed / 60

        print(
            f"[speed] step {state.global_step}/{state.max_steps} | "
            f"{elapsed:.2f}s/step | ETA {eta_min:.1f} min",
            flush=True,
        )
import inspect

import datasets
import trl.experimental.gold as gold
from transformers import AutoTokenizer


# -----------------------------
# Models
# -----------------------------

STUDENT_MODEL = "Qwen/Qwen2.5-0.5B-Instruct"
TEACHER_MODEL = "Qwen/Qwen2.5-Coder-1.5B-Instruct"

OUTPUT_DIR = "gold-code-deepspeed-test"


# -----------------------------
#
# If ZeRO-3 is painfully slow, try this instead:

DS_CONFIG = {
     "zero_optimization": {
         "stage": 2,
         "overlap_comm": True,
         "contiguous_gradients": True,
     },
     "bf16": {
         "enabled": True,
     },
     "train_micro_batch_size_per_gpu": "auto",
     "gradient_accumulation_steps": "auto",
     "gradient_clipping": "auto",
}


# -----------------------------
# Dataset
# -----------------------------

def to_messages(example):
    description = str(example.get("description", "")).strip()

    if not description:
        description = str(example)

    # Keep prompts short at first. code_contests descriptions can be long.
    description = description[:1500]

    return {
        "messages": [
            {
                "role": "system",
                "content": (
                    "You are a careful competitive programming assistant. "
                    "Return only the final correct solution code. "
                    "Do not include markdown or explanations."
                ),
            },
            {
                "role": "user",
                "content": (
                    "Solve this programming problem:\n\n"
                    f"{description}"
                ),
            },
        ]
    }


def main():
    print("Loading tokenizer...")
    tokenizer = AutoTokenizer.from_pretrained(
        STUDENT_MODEL,
        trust_remote_code=True,
    )

    if tokenizer.pad_token is None:
        tokenizer.pad_token = tokenizer.eos_token

    if tokenizer.pad_token_id is None:
        tokenizer.pad_token_id = tokenizer.eos_token_id

    print("Loading dataset...")
    raw = datasets.load_dataset(
        "deepmind/code_contests",
        split="train[:10000]",
    )

    print("Raw columns:", raw.column_names)

    train_dataset = raw.map(
        to_messages,
        remove_columns=raw.column_names,
    )

    print("Processed example:")
    print(train_dataset[0])

    config = gold.GOLDConfig(
        output_dir=OUTPUT_DIR,

        # GOLD generation settings
        temperature=0.8,
        top_p=0.95,
        max_length=512,
        disable_tqdm=True,
        # Training settings
        max_steps=1000,
        per_device_train_batch_size=1,
        gradient_accumulation_steps=4,
        learning_rate=5e-6,
        model_init_kwargs={
            "torch_dtype": "bfloat16",
            "attn_implementation": "sdpa",
        },

        # Logging/saving
        logging_steps=10,
        save_steps=100,
        report_to="none",
        
        # Precision
        bf16=True,
        hub_model_id="moos124/gold-code-deepspeed-testV2",
        push_to_hub=True,
        # DeepSpeed
        deepspeed=DS_CONFIG,
    )

    # TRL versions differ: some use processing_class, some older ones use tokenizer.
    trainer_kwargs = {
        "model": STUDENT_MODEL,
        "teacher_model": TEACHER_MODEL,
        "args": config,
        "train_dataset": train_dataset,
    }

    signature = inspect.signature(gold.GOLDTrainer)

    if "processing_class" in signature.parameters:
        trainer_kwargs["processing_class"] = tokenizer
    elif "tokenizer" in signature.parameters:
        trainer_kwargs["tokenizer"] = tokenizer
    else:
        print("Warning: GOLDTrainer signature has no processing_class/tokenizer parameter.")

    print("Building GOLDTrainer...")
    trainer = gold.GOLDTrainer(**trainer_kwargs)
    trainer.add_callback(SpeedCallback())
    print("Training...")
    trainer.train()

    print("Saving...")
    trainer.save_model(OUTPUT_DIR)
    # Optional push
    trainer.push_to_hub()


if __name__ == "__main__":
    main()