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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Mind7B: Purpose-trained 7B model for mind-mem memory operations.
|
| 4 |
+
UNSLOTH QLoRA fine-tuning on RunPod A100.
|
| 5 |
+
|
| 6 |
+
Tasks trained:
|
| 7 |
+
- Entity extraction (text → JSON entities)
|
| 8 |
+
- Fact extraction (text → JSON facts)
|
| 9 |
+
- Observation compression (blocks → focused observations)
|
| 10 |
+
- LLM reranking (query + candidates → relevance scores)
|
| 11 |
+
- Governance analysis (evidence assessment)
|
| 12 |
+
- Contradiction detection (block pairs → conflict analysis)
|
| 13 |
+
- Axis-aware retrieval classification
|
| 14 |
+
- Intent classification (9-type router)
|
| 15 |
+
|
| 16 |
+
Base: Qwen/Qwen3.5-7B
|
| 17 |
+
Method: UNSLOTH FastLanguageModel + QLoRA + SFTTrainer
|
| 18 |
+
Output: star-ga/mind7b on HuggingFace (PUBLIC)
|
| 19 |
+
|
| 20 |
+
Run: python3 train_mind7b_runpod.py
|
| 21 |
+
"""
|
| 22 |
+
import os
|
| 23 |
+
os.environ["HF_HOME"] = "/workspace/hf_cache"
|
| 24 |
+
os.environ["TRANSFORMERS_CACHE"] = "/workspace/hf_cache"
|
| 25 |
+
|
| 26 |
+
import subprocess, sys
|
| 27 |
+
subprocess.run([sys.executable, "-m", "pip", "install", "-q",
|
| 28 |
+
"unsloth", "trl", "datasets", "huggingface_hub"], check=True)
|
| 29 |
+
|
| 30 |
+
import json, time, torch
|
| 31 |
+
from huggingface_hub import login, hf_hub_download
|
| 32 |
+
|
| 33 |
+
# === CONFIG ===
|
| 34 |
+
MODEL_NAME = "Qwen/Qwen3.5-7B"
|
| 35 |
+
DATASET_REPO = "star-ga/mind7b-training"
|
| 36 |
+
DATASET_FILE = "mind7b_train.jsonl"
|
| 37 |
+
OUTPUT_DIR = "/workspace/mind7b"
|
| 38 |
+
HF_WRITE_TOKEN = "os.environ["HF_TOKEN"]"
|
| 39 |
+
HF_REPO = "star-ga/mind7b"
|
| 40 |
+
|
| 41 |
+
MAX_SEQ_LENGTH = 1024
|
| 42 |
+
EPOCHS = 3
|
| 43 |
+
LEARNING_RATE = 2e-4
|
| 44 |
+
LORA_RANK = 16
|
| 45 |
+
BATCH_SIZE = 4 # 7B fits larger batches on A100
|
| 46 |
+
GRAD_ACCUM = 4
|
| 47 |
+
|
| 48 |
+
login(token=HF_WRITE_TOKEN, add_to_git_credential=False)
|
| 49 |
+
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
| 50 |
+
|
| 51 |
+
# === GPU INFO ===
|
| 52 |
+
print(f"GPUs: {torch.cuda.device_count()}")
|
| 53 |
+
for i in range(torch.cuda.device_count()):
|
| 54 |
+
name = torch.cuda.get_device_name(i)
|
| 55 |
+
mem = torch.cuda.get_device_properties(i).total_mem / 1e9
|
| 56 |
+
print(f" GPU {i}: {name}, {mem:.1f}GB")
|
| 57 |
+
|
| 58 |
+
# === DOWNLOAD DATASET ===
|
| 59 |
+
print(f"\nDownloading dataset from {DATASET_REPO}...")
|
| 60 |
+
dataset_path = hf_hub_download(
|
| 61 |
+
repo_id=DATASET_REPO,
|
| 62 |
+
filename=DATASET_FILE,
|
| 63 |
+
repo_type="dataset",
|
| 64 |
+
cache_dir="/workspace/hf_cache",
|
| 65 |
+
)
|
| 66 |
+
print(f"Dataset downloaded: {dataset_path}")
|
| 67 |
+
|
| 68 |
+
# === LOAD MODEL (UNSLOTH) ===
|
| 69 |
+
from unsloth import FastLanguageModel
|
| 70 |
+
|
| 71 |
+
print(f"\nLoading {MODEL_NAME} in 4-bit via UNSLOTH...")
|
| 72 |
+
t0 = time.time()
|
| 73 |
+
model, tokenizer = FastLanguageModel.from_pretrained(
|
| 74 |
+
model_name=MODEL_NAME,
|
| 75 |
+
max_seq_length=MAX_SEQ_LENGTH,
|
| 76 |
+
load_in_4bit=True,
|
| 77 |
+
dtype=torch.bfloat16,
|
| 78 |
+
)
|
| 79 |
+
print(f"Loaded in {time.time()-t0:.0f}s")
|
| 80 |
+
|
| 81 |
+
# === LORA ===
|
| 82 |
+
model = FastLanguageModel.get_peft_model(
|
| 83 |
+
model,
|
| 84 |
+
r=LORA_RANK,
|
| 85 |
+
target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
|
| 86 |
+
"gate_proj", "up_proj", "down_proj"],
|
| 87 |
+
lora_alpha=LORA_RANK,
|
| 88 |
+
lora_dropout=0,
|
| 89 |
+
bias="none",
|
| 90 |
+
use_gradient_checkpointing="unsloth",
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
|
| 94 |
+
total = sum(p.numel() for p in model.parameters())
|
| 95 |
+
print(f"LoRA: {trainable:,} trainable / {total:,} total ({trainable/total*100:.2f}%)")
|
| 96 |
+
|
| 97 |
+
# === DATASET ===
|
| 98 |
+
from datasets import Dataset
|
| 99 |
+
|
| 100 |
+
examples = []
|
| 101 |
+
with open(dataset_path) as f:
|
| 102 |
+
for line in f:
|
| 103 |
+
d = json.loads(line)
|
| 104 |
+
if "messages" in d:
|
| 105 |
+
parts = []
|
| 106 |
+
for msg in d["messages"]:
|
| 107 |
+
role = msg["role"]
|
| 108 |
+
content = msg["content"]
|
| 109 |
+
parts.append(f"<|im_start|>{role}\n{content}<|im_end|>")
|
| 110 |
+
text = "\n".join(parts)
|
| 111 |
+
examples.append({"text": text})
|
| 112 |
+
|
| 113 |
+
dataset = Dataset.from_list(examples)
|
| 114 |
+
print(f"Dataset: {len(examples)} examples")
|
| 115 |
+
|
| 116 |
+
# === TRAIN ===
|
| 117 |
+
from trl import SFTTrainer
|
| 118 |
+
from transformers import TrainingArguments
|
| 119 |
+
|
| 120 |
+
tokenizer.model_max_length = MAX_SEQ_LENGTH
|
| 121 |
+
if tokenizer.pad_token is None:
|
| 122 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 123 |
+
|
| 124 |
+
total_steps = len(dataset) * EPOCHS // (BATCH_SIZE * GRAD_ACCUM)
|
| 125 |
+
|
| 126 |
+
training_args = TrainingArguments(
|
| 127 |
+
output_dir=OUTPUT_DIR,
|
| 128 |
+
per_device_train_batch_size=BATCH_SIZE,
|
| 129 |
+
gradient_accumulation_steps=GRAD_ACCUM,
|
| 130 |
+
num_train_epochs=EPOCHS,
|
| 131 |
+
learning_rate=LEARNING_RATE,
|
| 132 |
+
bf16=True,
|
| 133 |
+
logging_steps=5,
|
| 134 |
+
optim="adamw_8bit",
|
| 135 |
+
save_strategy="epoch",
|
| 136 |
+
save_total_limit=2,
|
| 137 |
+
lr_scheduler_type="cosine",
|
| 138 |
+
warmup_steps=10,
|
| 139 |
+
report_to="none",
|
| 140 |
+
gradient_checkpointing=True,
|
| 141 |
+
gradient_checkpointing_kwargs={"use_reentrant": False},
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
trainer = SFTTrainer(
|
| 145 |
+
model=model,
|
| 146 |
+
processing_class=tokenizer,
|
| 147 |
+
train_dataset=dataset,
|
| 148 |
+
args=training_args,
|
| 149 |
+
max_seq_length=MAX_SEQ_LENGTH,
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
print(f"\nTraining Mind7B: {EPOCHS} epochs, {total_steps} steps")
|
| 153 |
+
print(f" rank={LORA_RANK}, lr={LEARNING_RATE}, seq_len={MAX_SEQ_LENGTH}")
|
| 154 |
+
print(f" batch={BATCH_SIZE}, grad_accum={GRAD_ACCUM}")
|
| 155 |
+
t0 = time.time()
|
| 156 |
+
trainer.train()
|
| 157 |
+
elapsed = time.time() - t0
|
| 158 |
+
print(f"\nTraining complete! {elapsed/60:.1f} min")
|
| 159 |
+
|
| 160 |
+
# === SAVE LORA ===
|
| 161 |
+
lora_dir = f"{OUTPUT_DIR}/lora"
|
| 162 |
+
model.save_pretrained(lora_dir)
|
| 163 |
+
tokenizer.save_pretrained(lora_dir)
|
| 164 |
+
print(f"LoRA saved to: {lora_dir}")
|
| 165 |
+
|
| 166 |
+
# === MERGE + SAVE FULL MODEL ===
|
| 167 |
+
print("\nMerging LoRA into base model...")
|
| 168 |
+
merged_dir = f"{OUTPUT_DIR}/merged"
|
| 169 |
+
model.save_pretrained_merged(merged_dir, tokenizer)
|
| 170 |
+
print(f"Merged model saved to: {merged_dir}")
|
| 171 |
+
|
| 172 |
+
# === QUANTIZE TO GGUF (Q4_K_M for RTX 3080) ===
|
| 173 |
+
print("\nQuantizing to GGUF Q4_K_M (for local deployment)...")
|
| 174 |
+
gguf_dir = f"{OUTPUT_DIR}/gguf"
|
| 175 |
+
model.save_pretrained_gguf(gguf_dir, tokenizer, quantization_method="q4_k_m")
|
| 176 |
+
print(f"GGUF saved to: {gguf_dir}")
|
| 177 |
+
|
| 178 |
+
# === PUSH TO HUGGINGFACE ===
|
| 179 |
+
print(f"\nPushing to HuggingFace: {HF_REPO}...")
|
| 180 |
+
try:
|
| 181 |
+
model.push_to_hub(HF_REPO)
|
| 182 |
+
tokenizer.push_to_hub(HF_REPO)
|
| 183 |
+
print(f"LoRA pushed to {HF_REPO}")
|
| 184 |
+
except Exception as e:
|
| 185 |
+
print(f"Push failed: {e}")
|
| 186 |
+
|
| 187 |
+
# Push merged model
|
| 188 |
+
try:
|
| 189 |
+
from huggingface_hub import HfApi
|
| 190 |
+
api = HfApi()
|
| 191 |
+
api.upload_folder(
|
| 192 |
+
folder_path=merged_dir,
|
| 193 |
+
repo_id=HF_REPO,
|
| 194 |
+
path_in_repo="merged",
|
| 195 |
+
)
|
| 196 |
+
print(f"Merged model pushed to {HF_REPO}/merged")
|
| 197 |
+
except Exception as e:
|
| 198 |
+
print(f"Merged push failed: {e}")
|
| 199 |
+
|
| 200 |
+
# Push GGUF
|
| 201 |
+
try:
|
| 202 |
+
import glob
|
| 203 |
+
gguf_files = glob.glob(f"{gguf_dir}/*.gguf")
|
| 204 |
+
for gf in gguf_files:
|
| 205 |
+
api.upload_file(
|
| 206 |
+
path_or_fileobj=gf,
|
| 207 |
+
path_in_repo=os.path.basename(gf),
|
| 208 |
+
repo_id=HF_REPO,
|
| 209 |
+
)
|
| 210 |
+
print(f"GGUF pushed to {HF_REPO}")
|
| 211 |
+
except Exception as e:
|
| 212 |
+
print(f"GGUF push failed: {e}")
|
| 213 |
+
|
| 214 |
+
print(f"""
|
| 215 |
+
+==========================================+
|
| 216 |
+
| Mind7B Training Complete! |
|
| 217 |
+
| Time: {elapsed/60:.0f} min |
|
| 218 |
+
| Examples: {len(examples):<30d}|
|
| 219 |
+
| LoRA: {lora_dir:<34s}|
|
| 220 |
+
| Merged: {merged_dir:<32s}|
|
| 221 |
+
| GGUF: {gguf_dir:<34s}|
|
| 222 |
+
| HF: {HF_REPO:<36s}|
|
| 223 |
+
+==========================================+
|
| 224 |
+
""")
|