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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import os
|
| 3 |
+
import json
|
| 4 |
+
from typing import Any, Dict, Optional, List
|
| 5 |
+
|
| 6 |
+
import joblib
|
| 7 |
+
from transformers import PreTrainedModel
|
| 8 |
+
|
| 9 |
+
from .configuration_knn import KNNConfig
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class KNNModel(PreTrainedModel):
|
| 13 |
+
"""
|
| 14 |
+
A tiny wrapper so an sklearn KNN (joblib) can be saved/loaded with
|
| 15 |
+
the transformers save_pretrained / from_pretrained pattern.
|
| 16 |
+
|
| 17 |
+
Notes:
|
| 18 |
+
- We persist the sklearn object as `model.joblib` inside the folder.
|
| 19 |
+
- Loading from the Hub via `transformers` will require
|
| 20 |
+
`trust_remote_code=True` or using this module locally.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
config_class = KNNConfig
|
| 24 |
+
base_model_prefix = "knn"
|
| 25 |
+
|
| 26 |
+
def __init__(self, config: KNNConfig, model: Optional[Any] = None, models: Optional[List] = None):
|
| 27 |
+
super().__init__(config)
|
| 28 |
+
# self.knn is the actual sklearn KNN object (e.g., sklearn.neighbors.KNeighborsClassifier)
|
| 29 |
+
# for single models
|
| 30 |
+
self.knn = model
|
| 31 |
+
# self.models is a list of sklearn KNN objects for ensemble models
|
| 32 |
+
self.models = models or []
|
| 33 |
+
self.is_ensemble = config.is_ensemble or len(self.models) > 1
|
| 34 |
+
|
| 35 |
+
def forward(self, X, **kwargs):
|
| 36 |
+
"""Return predictions for an input array-like X.
|
| 37 |
+
|
| 38 |
+
For ensemble models, uses the first model's predictions.
|
| 39 |
+
(You can implement voting/averaging logic here if desired)
|
| 40 |
+
|
| 41 |
+
This is intentionally simple; you can adapt to return ModelOutput
|
| 42 |
+
structured objects if desired.
|
| 43 |
+
"""
|
| 44 |
+
if self.is_ensemble and self.models:
|
| 45 |
+
# Use first model for now; could implement ensemble voting
|
| 46 |
+
return self.models[0].predict(X)
|
| 47 |
+
elif self.knn is not None:
|
| 48 |
+
return self.knn.predict(X)
|
| 49 |
+
else:
|
| 50 |
+
raise ValueError("Model not loaded. Call from_pretrained or load a joblib model first.")
|
| 51 |
+
|
| 52 |
+
def save_pretrained(self, save_directory: str, **kwargs) -> None:
|
| 53 |
+
"""
|
| 54 |
+
Save only the config and the sklearn object(s).
|
| 55 |
+
|
| 56 |
+
We intentionally avoid calling the parent `save_pretrained` because the
|
| 57 |
+
transformers implementation expects a PyTorch model (and tries to infer
|
| 58 |
+
a `dtype` from model tensors), which fails for non-torch objects and
|
| 59 |
+
raises the IndexError seen in CI/when running locally. Instead we use
|
| 60 |
+
the config's `save_pretrained` method and persist the sklearn object
|
| 61 |
+
as `model.joblib` (or multiple files for ensembles).
|
| 62 |
+
"""
|
| 63 |
+
os.makedirs(save_directory, exist_ok=True)
|
| 64 |
+
# save config.json (PretrainedConfig handles this)
|
| 65 |
+
self.config.save_pretrained(save_directory)
|
| 66 |
+
|
| 67 |
+
# persist sklearn object(s) as joblib
|
| 68 |
+
if self.is_ensemble and self.models:
|
| 69 |
+
# Save each ensemble member with its original filename
|
| 70 |
+
for i, (member_name, model_obj) in enumerate(zip(self.config.ensemble_members, self.models)):
|
| 71 |
+
out_path = os.path.join(save_directory, member_name)
|
| 72 |
+
os.makedirs(os.path.dirname(out_path), exist_ok=True)
|
| 73 |
+
joblib.dump(model_obj, out_path)
|
| 74 |
+
elif self.knn is not None:
|
| 75 |
+
out_path = os.path.join(save_directory, "model.joblib")
|
| 76 |
+
joblib.dump(self.knn, out_path)
|
| 77 |
+
|
| 78 |
+
@classmethod
|
| 79 |
+
def from_pretrained(cls, pretrained_model_name_or_path: str, *model_args, **kwargs):
|
| 80 |
+
"""
|
| 81 |
+
Load a KNN model with optional variant selection.
|
| 82 |
+
|
| 83 |
+
Supports two modes:
|
| 84 |
+
1. Direct loading: loads model.joblib from the specified path/repo
|
| 85 |
+
2. Variant selection: specify parameters to auto-select a model variant
|
| 86 |
+
|
| 87 |
+
For ensemble models (7T-21T, Synthetic), automatically loads all sub-models.
|
| 88 |
+
|
| 89 |
+
Args:
|
| 90 |
+
pretrained_model_name_or_path: Local path or HF Hub repo ID
|
| 91 |
+
data_source: Optional. One of: "7T", "21T", "7T-21T", "Synthetic"
|
| 92 |
+
k_neighbors: Optional. 1 or 3
|
| 93 |
+
metric: Optional. "euclidean" or "manhattan"
|
| 94 |
+
training_version: Optional. For single models only, ignored for ensembles
|
| 95 |
+
variant: Optional. Direct variant name (e.g., "knn_21T_k1_euclidean")
|
| 96 |
+
|
| 97 |
+
Examples:
|
| 98 |
+
# Load default best model
|
| 99 |
+
model = KNNModel.from_pretrained("pcdslab/dom-knn-models")
|
| 100 |
+
|
| 101 |
+
# Load specific variant by parameters
|
| 102 |
+
model = KNNModel.from_pretrained(
|
| 103 |
+
"pcdslab/dom-knn-models",
|
| 104 |
+
data_source="7T-21T", # This is an ensemble!
|
| 105 |
+
k_neighbors=1,
|
| 106 |
+
metric="euclidean"
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
# Load by variant name
|
| 110 |
+
model = KNNModel.from_pretrained(
|
| 111 |
+
"pcdslab/dom-knn-models",
|
| 112 |
+
variant="knn_21T_k3_manhattan"
|
| 113 |
+
)
|
| 114 |
+
"""
|
| 115 |
+
# Extract variant selection parameters
|
| 116 |
+
data_source = kwargs.pop("data_source", None)
|
| 117 |
+
k_neighbors = kwargs.pop("k_neighbors", None)
|
| 118 |
+
metric = kwargs.pop("metric", None)
|
| 119 |
+
training_version = kwargs.pop("training_version", None)
|
| 120 |
+
variant = kwargs.pop("variant", None)
|
| 121 |
+
|
| 122 |
+
# Determine if this is an ensemble model
|
| 123 |
+
is_ensemble = data_source in ["7T-21T", "Synthetic"] if data_source else False
|
| 124 |
+
|
| 125 |
+
# load config using parent machinery (handles repo id or local path)
|
| 126 |
+
config = cls.config_class.from_pretrained(pretrained_model_name_or_path, **kwargs)
|
| 127 |
+
|
| 128 |
+
# Update config with variant info if provided
|
| 129 |
+
if k_neighbors is not None:
|
| 130 |
+
config.n_neighbors = k_neighbors
|
| 131 |
+
if metric is not None:
|
| 132 |
+
config.metric = metric
|
| 133 |
+
if data_source is not None:
|
| 134 |
+
config.data_source = data_source
|
| 135 |
+
if training_version is not None:
|
| 136 |
+
config.training_version = training_version
|
| 137 |
+
|
| 138 |
+
if is_ensemble:
|
| 139 |
+
# Load ensemble model (multiple joblib files)
|
| 140 |
+
model_filenames = cls._resolve_ensemble_filenames(
|
| 141 |
+
pretrained_model_name_or_path,
|
| 142 |
+
variant=variant,
|
| 143 |
+
data_source=data_source,
|
| 144 |
+
k_neighbors=k_neighbors,
|
| 145 |
+
metric=metric,
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
config.is_ensemble = True
|
| 149 |
+
config.ensemble_members = model_filenames
|
| 150 |
+
|
| 151 |
+
models = []
|
| 152 |
+
for model_filename in model_filenames:
|
| 153 |
+
model_file = os.path.join(pretrained_model_name_or_path, model_filename)
|
| 154 |
+
if os.path.exists(model_file):
|
| 155 |
+
knn = joblib.load(model_file)
|
| 156 |
+
else:
|
| 157 |
+
# try to download from hub
|
| 158 |
+
try:
|
| 159 |
+
from huggingface_hub import hf_hub_download
|
| 160 |
+
repo_id = pretrained_model_name_or_path
|
| 161 |
+
model_path = hf_hub_download(
|
| 162 |
+
repo_id=repo_id,
|
| 163 |
+
filename=model_filename,
|
| 164 |
+
**kwargs.get("hub_kwargs", {})
|
| 165 |
+
)
|
| 166 |
+
knn = joblib.load(model_path)
|
| 167 |
+
except Exception as exc:
|
| 168 |
+
raise RuntimeError(
|
| 169 |
+
f"Could not locate or download {model_filename} for {pretrained_model_name_or_path}: {exc}"
|
| 170 |
+
)
|
| 171 |
+
models.append(knn)
|
| 172 |
+
|
| 173 |
+
inst = cls(config=config, models=models)
|
| 174 |
+
return inst
|
| 175 |
+
else:
|
| 176 |
+
# Load single model
|
| 177 |
+
model_filename = cls._resolve_model_filename(
|
| 178 |
+
pretrained_model_name_or_path,
|
| 179 |
+
variant=variant,
|
| 180 |
+
data_source=data_source,
|
| 181 |
+
k_neighbors=k_neighbors,
|
| 182 |
+
metric=metric,
|
| 183 |
+
training_version=training_version,
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
config.is_ensemble = False
|
| 187 |
+
|
| 188 |
+
# Attempt to resolve model file
|
| 189 |
+
model_file = os.path.join(pretrained_model_name_or_path, model_filename)
|
| 190 |
+
if os.path.exists(model_file):
|
| 191 |
+
knn = joblib.load(model_file)
|
| 192 |
+
else:
|
| 193 |
+
# try to download from hub
|
| 194 |
+
try:
|
| 195 |
+
from huggingface_hub import hf_hub_download
|
| 196 |
+
|
| 197 |
+
repo_id = pretrained_model_name_or_path
|
| 198 |
+
model_path = hf_hub_download(
|
| 199 |
+
repo_id=repo_id,
|
| 200 |
+
filename=model_filename,
|
| 201 |
+
**kwargs.get("hub_kwargs", {})
|
| 202 |
+
)
|
| 203 |
+
knn = joblib.load(model_path)
|
| 204 |
+
except Exception as exc:
|
| 205 |
+
raise RuntimeError(
|
| 206 |
+
f"Could not locate or download {model_filename} for {pretrained_model_name_or_path}: {exc}"
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
inst = cls(config=config, model=knn)
|
| 210 |
+
return inst
|
| 211 |
+
|
| 212 |
+
@staticmethod
|
| 213 |
+
def _resolve_model_filename(
|
| 214 |
+
pretrained_model_name_or_path: str,
|
| 215 |
+
variant: Optional[str] = None,
|
| 216 |
+
data_source: Optional[str] = None,
|
| 217 |
+
k_neighbors: Optional[int] = None,
|
| 218 |
+
metric: Optional[str] = None,
|
| 219 |
+
training_version: Optional[str] = None,
|
| 220 |
+
) -> str:
|
| 221 |
+
"""
|
| 222 |
+
Resolve the model filename based on variant parameters.
|
| 223 |
+
|
| 224 |
+
Returns:
|
| 225 |
+
Filename of the .joblib model to load (e.g., "models/knn_21T_k1_euclidean.joblib")
|
| 226 |
+
"""
|
| 227 |
+
# If direct variant name provided, use it
|
| 228 |
+
if variant:
|
| 229 |
+
# Ensure .joblib extension
|
| 230 |
+
if not variant.endswith(".joblib"):
|
| 231 |
+
variant = f"{variant}.joblib"
|
| 232 |
+
# Check if it needs models/ prefix
|
| 233 |
+
if not variant.startswith("models/"):
|
| 234 |
+
return f"models/{variant}"
|
| 235 |
+
return variant
|
| 236 |
+
|
| 237 |
+
# If no parameters provided, use default (best performing model)
|
| 238 |
+
if not any([data_source, k_neighbors, metric, training_version]):
|
| 239 |
+
return "models/knn_21T_k1_euclidean.joblib"
|
| 240 |
+
|
| 241 |
+
# Try to load model index to find matching variant
|
| 242 |
+
try:
|
| 243 |
+
index_path = os.path.join(pretrained_model_name_or_path, "model_index.json")
|
| 244 |
+
if os.path.exists(index_path):
|
| 245 |
+
with open(index_path, "r") as f:
|
| 246 |
+
index = json.load(f)
|
| 247 |
+
else:
|
| 248 |
+
# Try to download from hub
|
| 249 |
+
from huggingface_hub import hf_hub_download
|
| 250 |
+
index_path = hf_hub_download(
|
| 251 |
+
repo_id=pretrained_model_name_or_path,
|
| 252 |
+
filename="model_index.json"
|
| 253 |
+
)
|
| 254 |
+
with open(index_path, "r") as f:
|
| 255 |
+
index = json.load(f)
|
| 256 |
+
|
| 257 |
+
# Search for matching variant
|
| 258 |
+
for variant_name, variant_info in index.get("variants", {}).items():
|
| 259 |
+
matches = True
|
| 260 |
+
if data_source and variant_info.get("data_source") != data_source:
|
| 261 |
+
matches = False
|
| 262 |
+
if k_neighbors and variant_info.get("k_neighbors") != k_neighbors:
|
| 263 |
+
matches = False
|
| 264 |
+
if metric and variant_info.get("metric").lower() != metric.lower():
|
| 265 |
+
matches = False
|
| 266 |
+
if training_version and variant_info.get("training_version") != training_version:
|
| 267 |
+
matches = False
|
| 268 |
+
|
| 269 |
+
if matches:
|
| 270 |
+
return variant_info["filename"]
|
| 271 |
+
|
| 272 |
+
# No match found
|
| 273 |
+
raise ValueError(
|
| 274 |
+
f"No model variant found matching: data_source={data_source}, "
|
| 275 |
+
f"k_neighbors={k_neighbors}, metric={metric}, training_version={training_version}"
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
except Exception as e:
|
| 279 |
+
# Fallback: construct filename from parameters
|
| 280 |
+
if not data_source or not k_neighbors or not metric:
|
| 281 |
+
raise ValueError(
|
| 282 |
+
"Could not load model_index.json and insufficient parameters provided. "
|
| 283 |
+
"Please specify: data_source, k_neighbors, and metric"
|
| 284 |
+
) from e
|
| 285 |
+
|
| 286 |
+
# Construct filename
|
| 287 |
+
ds = data_source.replace("-", "") # "7T-21T" -> "7T21T"
|
| 288 |
+
version_suffix = f"_{training_version}" if training_version else ""
|
| 289 |
+
filename = f"models/knn_{ds}_k{k_neighbors}_{metric.lower()}{version_suffix}.joblib"
|
| 290 |
+
return filename
|
| 291 |
+
|
| 292 |
+
@staticmethod
|
| 293 |
+
def _resolve_ensemble_filenames(
|
| 294 |
+
pretrained_model_name_or_path: str,
|
| 295 |
+
variant: Optional[str] = None,
|
| 296 |
+
data_source: Optional[str] = None,
|
| 297 |
+
k_neighbors: Optional[int] = None,
|
| 298 |
+
metric: Optional[str] = None,
|
| 299 |
+
) -> List[str]:
|
| 300 |
+
"""
|
| 301 |
+
Resolve ensemble model filenames (multiple .joblib files for one logical model).
|
| 302 |
+
|
| 303 |
+
For 7T-21T: returns 2 filenames (ver2 and ver3)
|
| 304 |
+
For Synthetic: returns 3 filenames (ver2, ver3, synthetic_data)
|
| 305 |
+
|
| 306 |
+
Returns:
|
| 307 |
+
List of filenames to load
|
| 308 |
+
"""
|
| 309 |
+
if not data_source:
|
| 310 |
+
raise ValueError("data_source is required for ensemble models")
|
| 311 |
+
|
| 312 |
+
if data_source not in ["7T-21T", "Synthetic"]:
|
| 313 |
+
raise ValueError(f"data_source '{data_source}' is not an ensemble model")
|
| 314 |
+
|
| 315 |
+
if not k_neighbors or not metric:
|
| 316 |
+
raise ValueError("k_neighbors and metric are required for ensemble models")
|
| 317 |
+
|
| 318 |
+
# Define ensemble members for each type
|
| 319 |
+
if data_source == "7T-21T":
|
| 320 |
+
training_versions = ["DOM_training_set_ver2", "DOM_training_set_ver3"]
|
| 321 |
+
elif data_source == "Synthetic":
|
| 322 |
+
training_versions = ["DOM_training_set_ver2", "DOM_training_set_ver3", "synthetic_data"]
|
| 323 |
+
else:
|
| 324 |
+
raise ValueError(f"Unknown ensemble type: {data_source}")
|
| 325 |
+
|
| 326 |
+
# Construct filenames based on original naming pattern
|
| 327 |
+
# Pattern: knn_model_Model-{data_source}_K{k}_{Metric}_{training_version}.joblib
|
| 328 |
+
metric_name = metric.capitalize() # "euclidean" -> "Euclidean"
|
| 329 |
+
filenames = []
|
| 330 |
+
for version in training_versions:
|
| 331 |
+
filename = f"models/knn_model_Model-{data_source}_K{k_neighbors}_{metric_name}_{version}.joblib"
|
| 332 |
+
filenames.append(filename)
|
| 333 |
+
|
| 334 |
+
return filenames
|
| 335 |
+
|