Colby commited on
Commit
93bc661
Β·
verified Β·
1 Parent(s): 7dbf428

Upload finetune_soc.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. finetune_soc.py +148 -0
finetune_soc.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # "datasets>=2.0.0",
10
+ # "trackio",
11
+ # ]
12
+ # ///
13
+
14
+ """
15
+ Fine-tune swiss-ai/Apertus-8B-2509 on marcodsn/SOC-2508 (Synthetic Online Conversations).
16
+
17
+ Preserves the full multi-participant chat structure: each conversation is formatted
18
+ as ChatML with custom roles (persona usernames) rather than collapsing to user/assistant.
19
+ Loss is computed on ALL tokens so the model learns every participant's voice.
20
+ """
21
+
22
+ import trackio
23
+ from datasets import load_dataset
24
+ from peft import LoraConfig
25
+ from transformers import AutoTokenizer
26
+ from trl import SFTConfig, SFTTrainer
27
+
28
+ MODEL_ID = "swiss-ai/Apertus-8B-2509"
29
+ DATASET_ID = "marcodsn/SOC-2508"
30
+ OUTPUT_REPO = "Colby/apertus-8b-soc"
31
+
32
+ print("πŸ“¦ Loading tokenizer...")
33
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
34
+
35
+ print("πŸ“¦ Loading dataset...")
36
+ dataset = load_dataset(DATASET_ID, split="train")
37
+ print(f"βœ… Loaded {len(dataset)} conversations")
38
+
39
+
40
+ def format_conversation(example):
41
+ """
42
+ Convert a SOC conversation to a ChatML text string for training.
43
+
44
+ Structure:
45
+ - system turn: full persona bios, relationship, and situation context
46
+ - one turn per chat_parts entry, role = sender's username, content = all messages joined
47
+
48
+ Using apply_chat_template + dataset_text_field trains on all tokens (all participants),
49
+ which is correct for multi-participant chat β€” there is no single "assistant" role.
50
+ """
51
+ exp = example["experience"]
52
+ p1, p2 = exp["persona1"], exp["persona2"]
53
+ id_to_username = {
54
+ p1["id"]: p1["username"],
55
+ p2["id"]: p2["username"],
56
+ }
57
+
58
+ system_content = (
59
+ f"Participants:\n"
60
+ f"- {p1['name']} (@{p1['username']}, age {p1['age']}): {p1['background']} "
61
+ f"Chatting style: {p1['chatting_style']}\n"
62
+ f"- {p2['name']} (@{p2['username']}, age {p2['age']}): {p2['background']} "
63
+ f"Chatting style: {p2['chatting_style']}\n"
64
+ f"Relationship: {exp['relationship']}\n"
65
+ f"Situation: {exp['situation']}"
66
+ )
67
+
68
+ messages = [{"role": "system", "content": system_content}]
69
+ for turn in example["chat_parts"]:
70
+ username = id_to_username.get(turn["sender"], turn["sender"])
71
+ content = "\n".join(turn["messages"])
72
+ messages.append({"role": username, "content": content})
73
+
74
+ text = tokenizer.apply_chat_template(
75
+ messages, tokenize=False, add_generation_prompt=False
76
+ )
77
+ return {"text": text}
78
+
79
+
80
+ print("πŸ”€ Formatting conversations to ChatML...")
81
+ dataset = dataset.map(format_conversation, remove_columns=dataset.column_names)
82
+ split = dataset.train_test_split(test_size=0.05, seed=42)
83
+ train_dataset = split["train"]
84
+ eval_dataset = split["test"]
85
+ print(f" Train: {len(train_dataset)} Eval: {len(eval_dataset)}")
86
+
87
+ peft_config = LoraConfig(
88
+ r=16,
89
+ lora_alpha=32,
90
+ lora_dropout=0.05,
91
+ bias="none",
92
+ task_type="CAUSAL_LM",
93
+ target_modules="all-linear",
94
+ )
95
+
96
+ config = SFTConfig(
97
+ # Hub push β€” ephemeral environment, must push or results are lost
98
+ output_dir="apertus-8b-soc",
99
+ push_to_hub=True,
100
+ hub_model_id=OUTPUT_REPO,
101
+ hub_strategy="every_save",
102
+
103
+ # Train on ALL tokens (all participant voices, not just "assistant")
104
+ dataset_text_field="text",
105
+ max_length=2048,
106
+
107
+ # Hyperparameters
108
+ num_train_epochs=2,
109
+ per_device_train_batch_size=2,
110
+ gradient_accumulation_steps=8, # effective batch = 16
111
+ learning_rate=2e-4,
112
+ lr_scheduler_type="cosine",
113
+ warmup_ratio=0.05,
114
+ bf16=True,
115
+ gradient_checkpointing=True,
116
+
117
+ # Checkpointing
118
+ logging_steps=10,
119
+ save_strategy="steps",
120
+ save_steps=100,
121
+ save_total_limit=2,
122
+ eval_strategy="steps",
123
+ eval_steps=100,
124
+
125
+ # Monitoring
126
+ report_to="trackio",
127
+ project="apertus-soc-finetune",
128
+ run_name="apertus-8b-soc-v1",
129
+ )
130
+
131
+ print("🎯 Initializing trainer...")
132
+ trainer = SFTTrainer(
133
+ model=MODEL_ID,
134
+ train_dataset=train_dataset,
135
+ eval_dataset=eval_dataset,
136
+ peft_config=peft_config,
137
+ args=config,
138
+ )
139
+
140
+ print("πŸš€ Starting training...")
141
+ trainer.train()
142
+
143
+ print("πŸ’Ύ Pushing to Hub...")
144
+ trainer.push_to_hub()
145
+ trackio.finish()
146
+
147
+ print(f"βœ… Done! Model at: https://huggingface.co/{OUTPUT_REPO}")
148
+ print(f"πŸ“Š Metrics at: https://huggingface.co/spaces/Colby/trackio")