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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Anti-Hero Stage 2: Tool Prediction Training (standalone).
|
| 4 |
+
|
| 5 |
+
Loads the personality LoRA from Hub, then trains tool prediction on top.
|
| 6 |
+
Stage 1 already completed and pushed to lokegud/antihero-personality-lora.
|
| 7 |
+
|
| 8 |
+
Submit via HF Jobs Docker mode with upgraded unsloth+transformers.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import os
|
| 12 |
+
import trackio
|
| 13 |
+
from unsloth import FastLanguageModel
|
| 14 |
+
from trl import SFTTrainer, SFTConfig
|
| 15 |
+
from datasets import load_dataset
|
| 16 |
+
from transformers import DataCollatorForSeq2Seq
|
| 17 |
+
|
| 18 |
+
# ── Config ──────────────────────────────────────────────────────────────
|
| 19 |
+
HF_USER = "lokegud"
|
| 20 |
+
BASE_MODEL = "huihui-ai/Huihui-Qwen3.5-35B-A3B-Claude-4.6-Opus-abliterated"
|
| 21 |
+
PERSONALITY_LORA = f"{HF_USER}/antihero-personality-lora"
|
| 22 |
+
MAX_SEQ_LENGTH = 2048
|
| 23 |
+
|
| 24 |
+
# Stage 2: Tool prediction
|
| 25 |
+
TOOL_DATASET = f"{HF_USER}/antihero-tool-prediction"
|
| 26 |
+
TOOL_EPOCHS = 3 # Reduced from 6: 1724 short examples, 3 epochs sufficient
|
| 27 |
+
TOOL_LR = 1.5e-4
|
| 28 |
+
|
| 29 |
+
# LoRA config
|
| 30 |
+
LORA_R = 32
|
| 31 |
+
LORA_ALPHA = 64
|
| 32 |
+
LORA_DROPOUT = 0.0
|
| 33 |
+
|
| 34 |
+
# Output
|
| 35 |
+
OUTPUT_TOOL = f"{HF_USER}/antihero-tool-lora"
|
| 36 |
+
OUTPUT_MERGED = f"{HF_USER}/antihero-merged"
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def load_model():
|
| 40 |
+
"""Load base model with personality LoRA already applied."""
|
| 41 |
+
print(f"Loading base model: {BASE_MODEL}")
|
| 42 |
+
model, tokenizer = FastLanguageModel.from_pretrained(
|
| 43 |
+
model_name=BASE_MODEL,
|
| 44 |
+
max_seq_length=MAX_SEQ_LENGTH,
|
| 45 |
+
load_in_4bit=False,
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
# Add LoRA adapters
|
| 49 |
+
model = FastLanguageModel.get_peft_model(
|
| 50 |
+
model,
|
| 51 |
+
r=LORA_R,
|
| 52 |
+
lora_alpha=LORA_ALPHA,
|
| 53 |
+
lora_dropout=LORA_DROPOUT,
|
| 54 |
+
bias="none",
|
| 55 |
+
use_gradient_checkpointing="unsloth",
|
| 56 |
+
random_state=42,
|
| 57 |
+
target_modules=[
|
| 58 |
+
"q_proj", "k_proj", "v_proj", "o_proj",
|
| 59 |
+
"gate_proj", "up_proj", "down_proj",
|
| 60 |
+
],
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
# Load personality LoRA weights on top
|
| 64 |
+
print(f"Loading personality LoRA from: {PERSONALITY_LORA}")
|
| 65 |
+
from peft import set_peft_model_state_dict
|
| 66 |
+
from huggingface_hub import hf_hub_download
|
| 67 |
+
import safetensors.torch
|
| 68 |
+
adapter_path = hf_hub_download(PERSONALITY_LORA, "adapter_model.safetensors")
|
| 69 |
+
state_dict = safetensors.torch.load_file(adapter_path)
|
| 70 |
+
set_peft_model_state_dict(model, state_dict)
|
| 71 |
+
print("Personality LoRA weights loaded")
|
| 72 |
+
|
| 73 |
+
model.print_trainable_parameters()
|
| 74 |
+
return model, tokenizer
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def prepare_tool_dataset():
|
| 78 |
+
"""Load and prepare tool prediction dataset."""
|
| 79 |
+
print(f"\nLoading tool prediction dataset: {TOOL_DATASET}")
|
| 80 |
+
ds = load_dataset(TOOL_DATASET, split="train")
|
| 81 |
+
print(f" {len(ds)} examples loaded")
|
| 82 |
+
|
| 83 |
+
def format_tool_example(example):
|
| 84 |
+
context_str = ""
|
| 85 |
+
for msg in example.get("context", []):
|
| 86 |
+
role = msg.get("role", "user")
|
| 87 |
+
content = msg.get("content", "")
|
| 88 |
+
if role == "system":
|
| 89 |
+
continue
|
| 90 |
+
context_str += f"{role}: {content}\n"
|
| 91 |
+
|
| 92 |
+
answer_parts = []
|
| 93 |
+
for tool in example.get("correct_tools", []):
|
| 94 |
+
action_num = tool.get("action", "?")
|
| 95 |
+
tool_name = tool.get("tool", "unknown")
|
| 96 |
+
args = tool.get("args", "")
|
| 97 |
+
if args:
|
| 98 |
+
answer_parts.append(f"ACTION_{action_num}: {tool_name}({args})")
|
| 99 |
+
else:
|
| 100 |
+
answer_parts.append(f"ACTION_{action_num}: {tool_name}")
|
| 101 |
+
|
| 102 |
+
messages = [
|
| 103 |
+
{
|
| 104 |
+
"role": "system",
|
| 105 |
+
"content": example.get("instruction", "Predict the tool used at each [ACTION_N: ___] position."),
|
| 106 |
+
},
|
| 107 |
+
{
|
| 108 |
+
"role": "user",
|
| 109 |
+
"content": (
|
| 110 |
+
f"Conversation context:\n{context_str}\n"
|
| 111 |
+
f"Masked response:\n{example.get('masked_response', '')}\n\n"
|
| 112 |
+
f"Predict the correct tool for each masked action."
|
| 113 |
+
),
|
| 114 |
+
},
|
| 115 |
+
{
|
| 116 |
+
"role": "assistant",
|
| 117 |
+
"content": "\n".join(answer_parts),
|
| 118 |
+
},
|
| 119 |
+
]
|
| 120 |
+
return {"messages": messages}
|
| 121 |
+
|
| 122 |
+
ds = ds.map(format_tool_example, remove_columns=ds.column_names)
|
| 123 |
+
|
| 124 |
+
split = ds.train_test_split(test_size=0.1, seed=42)
|
| 125 |
+
print(f" Train: {len(split['train'])}, Eval: {len(split['test'])}")
|
| 126 |
+
return split["train"], split["test"]
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def main():
|
| 130 |
+
print("=" * 80)
|
| 131 |
+
print("Anti-Hero Stage 2: Tool Prediction Training")
|
| 132 |
+
print("=" * 80)
|
| 133 |
+
|
| 134 |
+
model, tokenizer = load_model()
|
| 135 |
+
train_ds, eval_ds = prepare_tool_dataset()
|
| 136 |
+
|
| 137 |
+
# Extract text tokenizer from VLM processor
|
| 138 |
+
text_tok = getattr(tokenizer, "tokenizer", tokenizer)
|
| 139 |
+
|
| 140 |
+
def tokenize_messages(examples):
|
| 141 |
+
texts = []
|
| 142 |
+
for messages in examples["messages"]:
|
| 143 |
+
text = tokenizer.apply_chat_template(
|
| 144 |
+
messages, tokenize=False, add_generation_prompt=False
|
| 145 |
+
)
|
| 146 |
+
texts.append(text)
|
| 147 |
+
tokenized = text_tok(
|
| 148 |
+
texts,
|
| 149 |
+
truncation=True,
|
| 150 |
+
max_length=MAX_SEQ_LENGTH,
|
| 151 |
+
padding=False,
|
| 152 |
+
return_tensors=None,
|
| 153 |
+
)
|
| 154 |
+
tokenized["labels"] = [list(ids) for ids in tokenized["input_ids"]]
|
| 155 |
+
return tokenized
|
| 156 |
+
|
| 157 |
+
train_ds = train_ds.map(tokenize_messages, batched=True, remove_columns=train_ds.column_names)
|
| 158 |
+
eval_ds = eval_ds.map(tokenize_messages, batched=True, remove_columns=eval_ds.column_names)
|
| 159 |
+
print(f" Tokenized train: {len(train_ds)}, eval: {len(eval_ds)}")
|
| 160 |
+
print(f" Sample length: {len(train_ds[0]['input_ids'])} tokens")
|
| 161 |
+
|
| 162 |
+
config = SFTConfig(
|
| 163 |
+
output_dir="./tool-prediction-sft",
|
| 164 |
+
push_to_hub=True,
|
| 165 |
+
hub_model_id=OUTPUT_TOOL,
|
| 166 |
+
hub_strategy="every_save",
|
| 167 |
+
|
| 168 |
+
num_train_epochs=TOOL_EPOCHS,
|
| 169 |
+
per_device_train_batch_size=2, # Short sequences allow batch=2
|
| 170 |
+
gradient_accumulation_steps=4, # Effective batch = 8 still
|
| 171 |
+
learning_rate=TOOL_LR,
|
| 172 |
+
lr_scheduler_type="cosine",
|
| 173 |
+
warmup_steps=20,
|
| 174 |
+
weight_decay=0.01,
|
| 175 |
+
max_seq_length=MAX_SEQ_LENGTH,
|
| 176 |
+
|
| 177 |
+
logging_steps=10,
|
| 178 |
+
save_strategy="steps",
|
| 179 |
+
save_steps=100,
|
| 180 |
+
save_total_limit=3,
|
| 181 |
+
eval_strategy="no",
|
| 182 |
+
|
| 183 |
+
gradient_checkpointing=True,
|
| 184 |
+
|
| 185 |
+
report_to="trackio",
|
| 186 |
+
project="antihero-training",
|
| 187 |
+
run_name="tool-prediction-sft-stage2",
|
| 188 |
+
|
| 189 |
+
bf16=True,
|
| 190 |
+
seed=42,
|
| 191 |
+
dataloader_pin_memory=True,
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
collator = DataCollatorForSeq2Seq(text_tok, padding=True, pad_to_multiple_of=8)
|
| 195 |
+
|
| 196 |
+
trainer = SFTTrainer(
|
| 197 |
+
model=model,
|
| 198 |
+
tokenizer=tokenizer,
|
| 199 |
+
train_dataset=train_ds,
|
| 200 |
+
eval_dataset=eval_ds,
|
| 201 |
+
data_collator=collator,
|
| 202 |
+
args=config,
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
print("Starting tool-prediction-sft...")
|
| 206 |
+
trainer.train()
|
| 207 |
+
|
| 208 |
+
print("Pushing tool LoRA to Hub...")
|
| 209 |
+
trainer.push_to_hub()
|
| 210 |
+
print(f"Tool LoRA pushed to: {OUTPUT_TOOL}")
|
| 211 |
+
|
| 212 |
+
# Merge and push
|
| 213 |
+
print("Merging LoRA into base model...")
|
| 214 |
+
merged = model.merge_and_unload()
|
| 215 |
+
merged.push_to_hub(OUTPUT_MERGED)
|
| 216 |
+
tokenizer.push_to_hub(OUTPUT_MERGED)
|
| 217 |
+
print(f"Merged model pushed to: {OUTPUT_MERGED}")
|
| 218 |
+
|
| 219 |
+
# GGUF export
|
| 220 |
+
print("Exporting GGUF (Q4_K_M)...")
|
| 221 |
+
model.save_pretrained_gguf("./gguf", tokenizer, quantization_method="q4_k_m")
|
| 222 |
+
from huggingface_hub import HfApi
|
| 223 |
+
api = HfApi()
|
| 224 |
+
api.upload_folder(
|
| 225 |
+
folder_path="./gguf",
|
| 226 |
+
repo_id=f"{HF_USER}/antihero-gguf",
|
| 227 |
+
repo_type="model",
|
| 228 |
+
commit_message="Anti-Hero GGUF Q4_K_M export",
|
| 229 |
+
)
|
| 230 |
+
print(f"GGUF pushed to: {HF_USER}/antihero-gguf")
|
| 231 |
+
|
| 232 |
+
trackio.finish()
|
| 233 |
+
print("\n" + "=" * 80)
|
| 234 |
+
print("TRAINING COMPLETE!")
|
| 235 |
+
print("=" * 80)
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
if __name__ == "__main__":
|
| 239 |
+
main()
|