Spaces:
Sleeping
Sleeping
Delete src/models/load_model.py
Browse files- src/models/load_model.py +0 -253
src/models/load_model.py
DELETED
|
@@ -1,253 +0,0 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import logging
|
| 3 |
-
import torch
|
| 4 |
-
from pathlib import Path
|
| 5 |
-
from tqdm import tqdm
|
| 6 |
-
from peft import LoraConfig, get_peft_model, PeftModel
|
| 7 |
-
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 8 |
-
from torch.utils.data import DataLoader, Dataset
|
| 9 |
-
|
| 10 |
-
os.environ["PYTORCH_MPS_HIGH_WATERMARK_RATIO"] = "0.0"
|
| 11 |
-
|
| 12 |
-
logger = logging.getLogger(__name__)
|
| 13 |
-
|
| 14 |
-
class SpiderDataset(Dataset):
|
| 15 |
-
"""Formats Spider JSON data into causal LM training examples (Question -> MongoDB Query)."""
|
| 16 |
-
|
| 17 |
-
def __init__(self, data, tokenizer, max_length=512):
|
| 18 |
-
self.data = data
|
| 19 |
-
self.tokenizer = tokenizer
|
| 20 |
-
self.max_length = max_length
|
| 21 |
-
|
| 22 |
-
def __len__(self):
|
| 23 |
-
return len(self.data)
|
| 24 |
-
|
| 25 |
-
def __getitem__(self, idx):
|
| 26 |
-
item = self.data[idx]
|
| 27 |
-
question = item.get("question", "")
|
| 28 |
-
mongodb_query = item.get("generated_mongodb_query", "")
|
| 29 |
-
|
| 30 |
-
# Handle if stored as a list
|
| 31 |
-
if isinstance(mongodb_query, list) and len(mongodb_query) > 0:
|
| 32 |
-
mongodb_query = mongodb_query[0]
|
| 33 |
-
|
| 34 |
-
prompt = f"### Task: Generate MongoDB Query (MQL)\n### Question:\n{question}\n\n### MongoDB Query:\n"
|
| 35 |
-
|
| 36 |
-
prompt_enc = self.tokenizer(prompt, truncation=True, max_length=self.max_length, return_tensors="pt")
|
| 37 |
-
completion_enc = self.tokenizer(mongodb_query, truncation=True, max_length=self.max_length, return_tensors="pt")
|
| 38 |
-
|
| 39 |
-
input_ids = torch.cat([prompt_enc.input_ids[0], completion_enc.input_ids[0]], dim=0)
|
| 40 |
-
attention_mask = torch.cat([prompt_enc.attention_mask[0], completion_enc.attention_mask[0]], dim=0)
|
| 41 |
-
|
| 42 |
-
prompt_len = prompt_enc.input_ids.shape[1]
|
| 43 |
-
labels = torch.cat([torch.full((prompt_len,), -100, dtype=torch.long), completion_enc.input_ids[0]], dim=0)
|
| 44 |
-
|
| 45 |
-
return {
|
| 46 |
-
"input_ids": input_ids,
|
| 47 |
-
"attention_mask": attention_mask,
|
| 48 |
-
"labels": labels
|
| 49 |
-
}
|
| 50 |
-
|
| 51 |
-
class ModelLoader:
|
| 52 |
-
def __init__(self, config, device_override=None):
|
| 53 |
-
self.config = config
|
| 54 |
-
self.device = device_override or self._detect_device()
|
| 55 |
-
if self.device == "cuda":
|
| 56 |
-
self.dtype = torch.float16
|
| 57 |
-
elif self.device == "mps":
|
| 58 |
-
self.dtype = torch.float16
|
| 59 |
-
else:
|
| 60 |
-
self.dtype = torch.float32
|
| 61 |
-
self.tokenizer = None
|
| 62 |
-
self.base_model = None
|
| 63 |
-
self.lora_model = None
|
| 64 |
-
|
| 65 |
-
logger.info(f"🖥️ Initialized ModelLoader | Device: {self.device} | Dtype: {self.dtype}")
|
| 66 |
-
|
| 67 |
-
def _detect_device(self):
|
| 68 |
-
if torch.cuda.is_available():
|
| 69 |
-
return "cuda"
|
| 70 |
-
if hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
|
| 71 |
-
return "mps"
|
| 72 |
-
return "cpu"
|
| 73 |
-
|
| 74 |
-
def load_tokenizer(self):
|
| 75 |
-
model_name = getattr(self.config, "model_name", "Qwen/Qwen2.5-Coder-0.5B-Instruct")
|
| 76 |
-
logger.info(f"🔄 Loading tokenizer: {model_name}")
|
| 77 |
-
self.tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
|
| 78 |
-
if self.tokenizer.pad_token is None:
|
| 79 |
-
self.tokenizer.pad_token = self.tokenizer.eos_token
|
| 80 |
-
return self.tokenizer
|
| 81 |
-
|
| 82 |
-
def load_base_model(self):
|
| 83 |
-
model_name = getattr(self.config, "model_name", "Qwen/Qwen2.5-Coder-0.5B-Instruct")
|
| 84 |
-
logger.info(f"🔄 Loading base model: {model_name}")
|
| 85 |
-
|
| 86 |
-
if self.device == "cuda":
|
| 87 |
-
self.base_model = AutoModelForCausalLM.from_pretrained(
|
| 88 |
-
model_name,
|
| 89 |
-
torch_dtype=self.dtype,
|
| 90 |
-
trust_remote_code=True,
|
| 91 |
-
low_cpu_mem_usage=True,
|
| 92 |
-
device_map="auto"
|
| 93 |
-
)
|
| 94 |
-
else:
|
| 95 |
-
self.base_model = AutoModelForCausalLM.from_pretrained(
|
| 96 |
-
model_name,
|
| 97 |
-
torch_dtype=self.dtype,
|
| 98 |
-
trust_remote_code=True,
|
| 99 |
-
low_cpu_mem_usage=True
|
| 100 |
-
)
|
| 101 |
-
self.base_model.to(self.device)
|
| 102 |
-
|
| 103 |
-
self.base_model.eval()
|
| 104 |
-
return self.base_model
|
| 105 |
-
|
| 106 |
-
def setup_lora(self, trainable_fraction=1.0, r=16, alpha=32, dropout=0.05):
|
| 107 |
-
if self.base_model is None:
|
| 108 |
-
self.load_base_model()
|
| 109 |
-
|
| 110 |
-
target_modules = ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]
|
| 111 |
-
|
| 112 |
-
peft_config = LoraConfig(
|
| 113 |
-
r=r,
|
| 114 |
-
lora_alpha=alpha,
|
| 115 |
-
target_modules=target_modules,
|
| 116 |
-
lora_dropout=dropout,
|
| 117 |
-
bias="none",
|
| 118 |
-
task_type="CAUSAL_LM"
|
| 119 |
-
)
|
| 120 |
-
|
| 121 |
-
self.lora_model = get_peft_model(self.base_model, peft_config)
|
| 122 |
-
|
| 123 |
-
if trainable_fraction < 1.0:
|
| 124 |
-
self._apply_trainable_fraction(trainable_fraction)
|
| 125 |
-
else:
|
| 126 |
-
logger.info("✅ LoRA configured with 100% trainable parameters.")
|
| 127 |
-
|
| 128 |
-
self.lora_model.print_trainable_parameters()
|
| 129 |
-
return self.lora_model
|
| 130 |
-
|
| 131 |
-
def _apply_trainable_fraction(self, fraction):
|
| 132 |
-
lora_params = [(n, p) for n, p in self.lora_model.named_parameters() if "lora_" in n and p.requires_grad]
|
| 133 |
-
total_lora = len(lora_params)
|
| 134 |
-
num_to_freeze = int(total_lora * (1.0 - fraction))
|
| 135 |
-
|
| 136 |
-
if num_to_freeze > 0:
|
| 137 |
-
for i, (name, param) in enumerate(lora_params):
|
| 138 |
-
if i < num_to_freeze:
|
| 139 |
-
param.requires_grad = False
|
| 140 |
-
|
| 141 |
-
trainable_count = sum(1 for p in self.lora_model.parameters() if p.requires_grad)
|
| 142 |
-
logger.info(f"🔒 Froze {num_to_freeze}/{total_lora} LoRA parameters. Remaining trainable: {trainable_count} ({fraction*100}%).")
|
| 143 |
-
|
| 144 |
-
def autodetect_saved_model(self, output_dir):
|
| 145 |
-
output_dir = Path(output_dir)
|
| 146 |
-
if output_dir.exists() and (output_dir / "adapter_config.json").exists():
|
| 147 |
-
logger.info(f"✅ Found saved LoRA adapter at {output_dir}. Loading...")
|
| 148 |
-
if self.base_model is None:
|
| 149 |
-
self.load_base_model()
|
| 150 |
-
self.lora_model = PeftModel.from_pretrained(self.base_model, str(output_dir))
|
| 151 |
-
self.lora_model.to(self.device)
|
| 152 |
-
self.lora_model.eval()
|
| 153 |
-
return self.lora_model
|
| 154 |
-
logger.info(f"ℹ️ No saved adapter found at {output_dir}.")
|
| 155 |
-
return None
|
| 156 |
-
|
| 157 |
-
def train_lora(self, train_data, output_dir, epochs=3, batch_size=1, grad_accum=4, lr=2e-4, max_length=512):
|
| 158 |
-
lr = float(lr) # Ensure lr is a float to prevent PyTorch optimizer TypeError
|
| 159 |
-
if self.lora_model is None:
|
| 160 |
-
self.setup_lora()
|
| 161 |
-
|
| 162 |
-
dataset = SpiderDataset(train_data, self.tokenizer, max_length)
|
| 163 |
-
|
| 164 |
-
def collate_fn(batch):
|
| 165 |
-
max_len = max(len(b["input_ids"]) for b in batch)
|
| 166 |
-
input_ids, attention_mask, labels = [], [], []
|
| 167 |
-
pad_id = self.tokenizer.pad_token_id
|
| 168 |
-
|
| 169 |
-
for b in batch:
|
| 170 |
-
pad_len = max_len - len(b["input_ids"])
|
| 171 |
-
input_ids.append(b["input_ids"].tolist() + [pad_id] * pad_len)
|
| 172 |
-
attention_mask.append(b["attention_mask"].tolist() + [0] * pad_len)
|
| 173 |
-
labels.append(b["labels"].tolist() + [-100] * pad_len)
|
| 174 |
-
|
| 175 |
-
return {
|
| 176 |
-
"input_ids": torch.tensor(input_ids, dtype=torch.long).to(self.device),
|
| 177 |
-
"attention_mask": torch.tensor(attention_mask, dtype=torch.long).to(self.device),
|
| 178 |
-
"labels": torch.tensor(labels, dtype=torch.long).to(self.device)
|
| 179 |
-
}
|
| 180 |
-
|
| 181 |
-
loader = DataLoader(dataset, batch_size=batch_size, shuffle=True, collate_fn=collate_fn)
|
| 182 |
-
|
| 183 |
-
optimizer = torch.optim.AdamW(
|
| 184 |
-
filter(lambda p: p.requires_grad, self.lora_model.parameters()),
|
| 185 |
-
lr=lr
|
| 186 |
-
)
|
| 187 |
-
|
| 188 |
-
self.lora_model.train()
|
| 189 |
-
|
| 190 |
-
logger.info(f"🚀 Starting LoRA training | Device: {self.device} | Epochs: {epochs} | Batch: {batch_size} | Grad Accum: {grad_accum} | LR: {lr}")
|
| 191 |
-
|
| 192 |
-
for epoch in range(epochs):
|
| 193 |
-
epoch_loss = 0.0
|
| 194 |
-
progress_bar = tqdm(loader, desc=f"Epoch {epoch+1}/{epochs}", leave=False)
|
| 195 |
-
|
| 196 |
-
optimizer.zero_grad()
|
| 197 |
-
|
| 198 |
-
for step, batch in enumerate(progress_bar):
|
| 199 |
-
outputs = self.lora_model(**batch)
|
| 200 |
-
loss = outputs.loss / grad_accum
|
| 201 |
-
loss.backward()
|
| 202 |
-
epoch_loss += loss.item() * grad_accum
|
| 203 |
-
|
| 204 |
-
if (step + 1) % grad_accum == 0:
|
| 205 |
-
optimizer.step()
|
| 206 |
-
optimizer.zero_grad()
|
| 207 |
-
|
| 208 |
-
progress_bar.set_postfix({"loss": f"{loss.item() * grad_accum:.4f}"})
|
| 209 |
-
|
| 210 |
-
# Clear MPS cache periodically to prevent memory leaks on Mac
|
| 211 |
-
if self.device == "mps" and (step + 1) % 10 == 0:
|
| 212 |
-
torch.mps.empty_cache()
|
| 213 |
-
|
| 214 |
-
optimizer.step()
|
| 215 |
-
optimizer.zero_grad()
|
| 216 |
-
|
| 217 |
-
avg_loss = epoch_loss / len(loader)
|
| 218 |
-
logger.info(f"✅ Epoch {epoch+1} completed | Avg Loss: {avg_loss:.4f}")
|
| 219 |
-
|
| 220 |
-
output_dir = Path(output_dir)
|
| 221 |
-
output_dir.mkdir(parents=True, exist_ok=True)
|
| 222 |
-
self.lora_model.save_pretrained(str(output_dir))
|
| 223 |
-
self.tokenizer.save_pretrained(str(output_dir))
|
| 224 |
-
logger.info(f"💾 LoRA adapter saved to {output_dir}")
|
| 225 |
-
|
| 226 |
-
self.lora_model.eval()
|
| 227 |
-
return self.lora_model
|
| 228 |
-
|
| 229 |
-
def load_models(self, lora_path=None):
|
| 230 |
-
"""Returns a dictionary of models and the tokenizer."""
|
| 231 |
-
if self.tokenizer is None:
|
| 232 |
-
self.load_tokenizer()
|
| 233 |
-
if self.base_model is None:
|
| 234 |
-
self.load_base_model()
|
| 235 |
-
|
| 236 |
-
models = {"base": self.base_model, "lora": None}
|
| 237 |
-
|
| 238 |
-
if self.lora_model is not None:
|
| 239 |
-
logger.info("Reusing already-loaded LoRA model in memory.")
|
| 240 |
-
models["lora"] = self.lora_model
|
| 241 |
-
elif lora_path:
|
| 242 |
-
lora_path = Path(lora_path)
|
| 243 |
-
if lora_path.exists() and (lora_path / "adapter_config.json").exists():
|
| 244 |
-
logger.info(f"Loading LoRA model from {lora_path}")
|
| 245 |
-
self.lora_model = PeftModel.from_pretrained(self.base_model, str(lora_path))
|
| 246 |
-
self.lora_model.to(self.device)
|
| 247 |
-
self.lora_model.eval()
|
| 248 |
-
models["lora"] = self.lora_model
|
| 249 |
-
else:
|
| 250 |
-
logger.warning(f"LoRA path {lora_path} does not exist or is invalid. Returning base model as 'lora'.")
|
| 251 |
-
models["lora"] = self.base_model
|
| 252 |
-
|
| 253 |
-
return models, self.tokenizer
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|