Colby commited on
Commit
5e69421
·
verified ·
1 Parent(s): 5870b4b

Upload finetune_coding.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. finetune_coding.py +270 -0
finetune_coding.py ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # /// script
3
+ # requires-python = ">=3.10"
4
+ # dependencies = [
5
+ # "trl>=0.12.0",
6
+ # "peft>=0.7.0",
7
+ # "transformers>=4.36.0",
8
+ # "accelerate>=0.24.0",
9
+ # "bitsandbytes>=0.41.0",
10
+ # "datasets>=2.0.0",
11
+ # "trackio",
12
+ # "apertus-format @ git+https://github.com/swiss-ai/apertus-format.git",
13
+ # ]
14
+ # ///
15
+
16
+ """
17
+ Fine-tune swiss-ai/Apertus-8B-Instruct-2509 on three agentic coding / reasoning datasets:
18
+ - Roman1111111/claude-opus-4.6-10000x (9.6K — Opus 4.6 reasoning distillation)
19
+ - togethercomputer/CoderForge-Preview (15K sample — agentic coding trajectories)
20
+ - Crownelius/Opus-4.6-Reasoning-3300x (2.2K — reasoning with thinking traces)
21
+
22
+ All data is formatted with the native Apertus chat format via the apertus-format library.
23
+ Thinking/reasoning traces are preserved as THOUGHTS blocks.
24
+ CoderForge tool calls are mapped to Apertus TOOL_CALLS/TOOL_OUTPUTS blocks within a
25
+ single merged assistant turn.
26
+ """
27
+
28
+ import json
29
+ import trackio
30
+ from datasets import load_dataset, concatenate_datasets
31
+ from peft import LoraConfig
32
+ from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
33
+ from trl import SFTConfig, SFTTrainer
34
+ from apertus_format import (
35
+ Message, Conversation, ApertusFormatter,
36
+ AssistantBlock, ToolCall, ToolOutput, BlockType,
37
+ )
38
+
39
+ MODEL_ID = "swiss-ai/Apertus-8B-Instruct-2509"
40
+ OUTPUT_REPO = "Colby/apertus-8b-coding"
41
+ CODERFORGE_SAMPLE = 15_000
42
+
43
+ formatter = ApertusFormatter(enable_thinking=True)
44
+
45
+
46
+ def format_roman(example):
47
+ """Opus 4.6 reasoning dataset: messages list with optional reasoning field."""
48
+ msgs = []
49
+ for msg in example["messages"]:
50
+ role = msg.get("role", "")
51
+ content = msg.get("content", "") or ""
52
+ if role == "system":
53
+ msgs.append(Message.system(content))
54
+ elif role == "user":
55
+ msgs.append(Message.user(content))
56
+ elif role == "assistant":
57
+ reasoning = msg.get("reasoning", "") or ""
58
+ blocks = []
59
+ if reasoning.strip():
60
+ blocks.append(AssistantBlock(type=BlockType.THOUGHTS, text=reasoning))
61
+ blocks.append(AssistantBlock(type=BlockType.RESPONSE, text=content))
62
+ msgs.append(Message.assistant_with_blocks(blocks))
63
+ try:
64
+ return {"text": formatter.format_conversation(Conversation(messages=msgs))}
65
+ except Exception:
66
+ return {"text": None}
67
+
68
+
69
+ def format_coderforge(example):
70
+ """
71
+ CoderForge agentic trajectories: messages is a JSON string in OpenHands format.
72
+ Merges all assistant+tool turns into a single Apertus assistant message with
73
+ interleaved TOOL_CALLS and TOOL_OUTPUTS blocks.
74
+ """
75
+ try:
76
+ raw = json.loads(example["messages"])
77
+ except (json.JSONDecodeError, TypeError):
78
+ return {"text": None}
79
+
80
+ system_msgs = []
81
+ user_msgs = []
82
+ agentic_blocks = []
83
+ agentic_started = False
84
+
85
+ for msg in raw:
86
+ role = msg.get("role", "")
87
+ content = msg.get("content") or ""
88
+ if isinstance(content, list):
89
+ content = " ".join(
90
+ p.get("text", "") for p in content if isinstance(p, dict)
91
+ )
92
+ content = str(content).strip()
93
+
94
+ if role == "system":
95
+ system_msgs.append(Message.system(content))
96
+ elif role == "user" and not agentic_started:
97
+ user_msgs.append(Message.user(content))
98
+ elif role == "assistant":
99
+ agentic_started = True
100
+ tool_calls_raw = msg.get("tool_calls") or []
101
+ if tool_calls_raw:
102
+ calls = [
103
+ ToolCall(
104
+ name=tc["function"]["name"],
105
+ arguments=tc["function"].get("arguments", "{}"),
106
+ )
107
+ for tc in tool_calls_raw
108
+ if "function" in tc
109
+ ]
110
+ if calls:
111
+ agentic_blocks.append(
112
+ AssistantBlock(type=BlockType.TOOL_CALLS, calls=calls)
113
+ )
114
+ if content:
115
+ agentic_blocks.append(
116
+ AssistantBlock(type=BlockType.RESPONSE, text=content)
117
+ )
118
+ elif role == "tool":
119
+ agentic_started = True
120
+ if content:
121
+ agentic_blocks.append(
122
+ AssistantBlock(
123
+ type=BlockType.TOOL_OUTPUTS,
124
+ outputs=[ToolOutput(output=content)],
125
+ )
126
+ )
127
+
128
+ if not agentic_blocks:
129
+ return {"text": None}
130
+
131
+ # If the last block is TOOL_CALLS or TOOL_OUTPUTS (no final text response),
132
+ # the trajectory is still useful — leave it as-is.
133
+ all_msgs = system_msgs + user_msgs + [Message.assistant_with_blocks(agentic_blocks)]
134
+ try:
135
+ return {"text": formatter.format_conversation(Conversation(messages=all_msgs))}
136
+ except Exception:
137
+ return {"text": None}
138
+
139
+
140
+ def format_crownelius(example):
141
+ """Opus 4.6 reasoning dataset: flat problem/thinking/solution columns."""
142
+ problem = (example.get("problem") or "").strip()
143
+ thinking = (example.get("thinking") or "").strip()
144
+ solution = (example.get("solution") or "").strip()
145
+ if not problem or not solution:
146
+ return {"text": None}
147
+ blocks = []
148
+ if thinking:
149
+ blocks.append(AssistantBlock(type=BlockType.THOUGHTS, text=thinking))
150
+ blocks.append(AssistantBlock(type=BlockType.RESPONSE, text=solution))
151
+ msgs = [
152
+ Message.user(problem),
153
+ Message.assistant_with_blocks(blocks),
154
+ ]
155
+ try:
156
+ return {"text": formatter.format_conversation(Conversation(messages=msgs))}
157
+ except Exception:
158
+ return {"text": None}
159
+
160
+
161
+ print("Loading datasets...")
162
+ ds_roman = load_dataset("Roman1111111/claude-opus-4.6-10000x", split="train")
163
+ ds_coderforge = (
164
+ load_dataset(
165
+ "togethercomputer/CoderForge-Preview",
166
+ name="trajectories",
167
+ split="filtered_reward1",
168
+ )
169
+ .shuffle(seed=42)
170
+ .select(range(CODERFORGE_SAMPLE))
171
+ )
172
+ ds_crownelius = load_dataset("Crownelius/Opus-4.6-Reasoning-3300x", split="train")
173
+
174
+ print("Mapping to Apertus format...")
175
+ ds_roman = ds_roman.map(format_roman, remove_columns=ds_roman.column_names)
176
+ ds_coderforge = ds_coderforge.map(
177
+ format_coderforge, remove_columns=ds_coderforge.column_names
178
+ )
179
+ ds_crownelius = ds_crownelius.map(
180
+ format_crownelius, remove_columns=ds_crownelius.column_names
181
+ )
182
+
183
+ ds_roman = ds_roman.filter(lambda x: x["text"] is not None)
184
+ ds_coderforge = ds_coderforge.filter(lambda x: x["text"] is not None)
185
+ ds_crownelius = ds_crownelius.filter(lambda x: x["text"] is not None)
186
+
187
+ print(f" Roman: {len(ds_roman)}")
188
+ print(f" CoderForge: {len(ds_coderforge)}")
189
+ print(f" Crownelius: {len(ds_crownelius)}")
190
+
191
+ combined = concatenate_datasets([ds_roman, ds_coderforge, ds_crownelius]).shuffle(seed=42)
192
+ split = combined.train_test_split(test_size=0.05, seed=42)
193
+ train_dataset = split["train"]
194
+ eval_dataset = split["test"]
195
+ print(f"Total — Train: {len(train_dataset)} Eval: {len(eval_dataset)}")
196
+
197
+ peft_config = LoraConfig(
198
+ r=16,
199
+ lora_alpha=32,
200
+ lora_dropout=0.05,
201
+ bias="none",
202
+ task_type="CAUSAL_LM",
203
+ target_modules="all-linear",
204
+ )
205
+
206
+ config = SFTConfig(
207
+ output_dir="apertus-8b-coding",
208
+ push_to_hub=True,
209
+ hub_model_id=OUTPUT_REPO,
210
+ hub_strategy="every_save",
211
+
212
+ dataset_text_field="text",
213
+ max_length=4096,
214
+
215
+ num_train_epochs=2,
216
+ per_device_train_batch_size=2,
217
+ per_device_eval_batch_size=1,
218
+ gradient_accumulation_steps=8,
219
+ learning_rate=2e-4,
220
+ lr_scheduler_type="cosine",
221
+ warmup_ratio=0.05,
222
+ bf16=True,
223
+ gradient_checkpointing=True,
224
+
225
+ logging_steps=10,
226
+ save_strategy="steps",
227
+ save_steps=100,
228
+ save_total_limit=2,
229
+ eval_strategy="steps",
230
+ eval_steps=100,
231
+
232
+ report_to="trackio",
233
+ project="apertus-coding-finetune",
234
+ run_name="apertus-8b-coding-v1",
235
+ )
236
+
237
+ bnb_config = BitsAndBytesConfig(
238
+ load_in_4bit=True,
239
+ bnb_4bit_quant_type="nf4",
240
+ bnb_4bit_compute_dtype="bfloat16",
241
+ bnb_4bit_use_double_quant=True,
242
+ )
243
+
244
+ print("Loading model and tokenizer...")
245
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
246
+ model = AutoModelForCausalLM.from_pretrained(
247
+ MODEL_ID,
248
+ quantization_config=bnb_config,
249
+ device_map="auto",
250
+ )
251
+
252
+ print("Initializing trainer...")
253
+ trainer = SFTTrainer(
254
+ model=model,
255
+ processing_class=tokenizer,
256
+ train_dataset=train_dataset,
257
+ eval_dataset=eval_dataset,
258
+ peft_config=peft_config,
259
+ args=config,
260
+ )
261
+
262
+ print("Starting training...")
263
+ trainer.train()
264
+
265
+ print("Pushing to Hub...")
266
+ trainer.push_to_hub()
267
+ trackio.finish()
268
+
269
+ print(f"Done! Model at: https://huggingface.co/{OUTPUT_REPO}")
270
+ print(f"Metrics at: https://huggingface.co/spaces/Colby/trackio")