|
1 | 1 | from __future__ import annotations |
2 | 2 |
|
| 3 | +from time import time |
3 | 4 | from typing import Optional, Dict, Any |
4 | 5 | import os |
5 | 6 | import shutil |
6 | 7 |
|
7 | 8 | from .experiment import Experiment |
8 | 9 | from .job import Job |
9 | 10 | from . import dirs |
10 | | - |
| 11 | +from .model import Model as ModelService |
11 | 12 |
|
12 | 13 | class Lab: |
13 | 14 | """ |
@@ -177,6 +178,139 @@ def save_checkpoint(self, source_path: str, name: Optional[str] = None) -> str: |
177 | 178 |
|
178 | 179 | return dest |
179 | 180 |
|
| 181 | + def save_model(self, source_path: str, name: Optional[str] = None, architecture: Optional[str] = None, pipeline_tag: Optional[str] = None, parent_model: Optional[str] = None) -> str: |
| 182 | + """ |
| 183 | + Save a model file or directory to the workspace models directory. |
| 184 | + The model will automatically appear in the Model Zoo's Local Models list. |
| 185 | + |
| 186 | + Args: |
| 187 | + source_path: Path to the model file or directory to save |
| 188 | + name: Optional name for the model. If not provided, uses source basename. |
| 189 | + The final model name will be prefixed with the job_id for uniqueness. |
| 190 | + architecture: Optional architecture string. If not provided, will attempt to |
| 191 | + detect from config.json for directory-based models. |
| 192 | + pipeline_tag: Optional pipeline tag. If not provided and parent_model is given, |
| 193 | + will attempt to fetch from parent model on HuggingFace. |
| 194 | + parent_model: Optional parent model name/ID for provenance tracking. |
| 195 | + |
| 196 | + Returns: |
| 197 | + The destination path on disk. |
| 198 | + """ |
| 199 | + self._ensure_initialized() |
| 200 | + if not isinstance(source_path, str) or source_path.strip() == "": |
| 201 | + raise ValueError("source_path must be a non-empty string") |
| 202 | + src = os.path.abspath(source_path) |
| 203 | + if not os.path.exists(src): |
| 204 | + raise FileNotFoundError(f"Model source does not exist: {src}") |
| 205 | + |
| 206 | + job_id = self._job.id # type: ignore[union-attr] |
| 207 | + |
| 208 | + # Determine base name with job_id prefix for uniqueness |
| 209 | + if isinstance(name, str) and name.strip() != "": |
| 210 | + base_name = f"{job_id}_{name}" |
| 211 | + else: |
| 212 | + base_name = f"{job_id}_{os.path.basename(src)}" |
| 213 | + |
| 214 | + # Save to main workspace models directory for Model Zoo visibility |
| 215 | + models_dir = dirs.get_models_dir() |
| 216 | + dest = os.path.join(models_dir, base_name) |
| 217 | + |
| 218 | + # Create parent directories |
| 219 | + os.makedirs(os.path.dirname(dest), exist_ok=True) |
| 220 | + |
| 221 | + # Copy file or directory |
| 222 | + if os.path.isdir(src): |
| 223 | + if os.path.exists(dest): |
| 224 | + shutil.rmtree(dest) |
| 225 | + shutil.copytree(src, dest) |
| 226 | + else: |
| 227 | + shutil.copy2(src, dest) |
| 228 | + |
| 229 | + # Create Model metadata so it appears in Model Zoo |
| 230 | + try: |
| 231 | + model_service = ModelService(base_name) |
| 232 | + |
| 233 | + # Use provided architecture or detect it |
| 234 | + if architecture is None: |
| 235 | + architecture = model_service.detect_architecture(dest) |
| 236 | + |
| 237 | + # Handle pipeline tag logic |
| 238 | + if pipeline_tag is None and parent_model is not None: |
| 239 | + # Try to fetch pipeline tag from parent model |
| 240 | + pipeline_tag = model_service.fetch_pipeline_tag(parent_model) |
| 241 | + # Determine model_filename for single-file models |
| 242 | + model_filename = "" if os.path.isdir(dest) else os.path.basename(dest) |
| 243 | + |
| 244 | + # Prepare json_data with basic info |
| 245 | + json_data = { |
| 246 | + "job_id": job_id, |
| 247 | + "description": f"Model generated by job {job_id}", |
| 248 | + } |
| 249 | + |
| 250 | + # Add pipeline tag to json_data if provided |
| 251 | + if pipeline_tag is not None: |
| 252 | + json_data["pipeline_tag"] = pipeline_tag |
| 253 | + |
| 254 | + # Use the Model class's generate_model_json method to create metadata |
| 255 | + model_service.generate_model_json( |
| 256 | + architecture=architecture, |
| 257 | + model_filename=model_filename, |
| 258 | + json_data=json_data |
| 259 | + ) |
| 260 | + self.log(f"Model saved to Model Zoo as '{base_name}'") |
| 261 | + except Exception as e: |
| 262 | + self.log(f"Warning: Model saved but metadata creation failed: {str(e)}") |
| 263 | + |
| 264 | + # Create provenance data |
| 265 | + try: |
| 266 | + # Create MD5 checksums for all model files |
| 267 | + md5_objects = model_service.create_md5_checksums(dest) |
| 268 | + |
| 269 | + # Prepare provenance metadata from job data |
| 270 | + job_data = self._job.get_job_data() |
| 271 | + |
| 272 | + provenance_metadata = { |
| 273 | + "job_id": job_id, |
| 274 | + "model_name": parent_model or job_data.get("model_name"), |
| 275 | + "model_architecture": architecture, |
| 276 | + "input_model": parent_model, |
| 277 | + "dataset": job_data.get("dataset"), |
| 278 | + "adaptor_name": job_data.get("adaptor_name", None), |
| 279 | + "parameters": job_data.get("_config", {}), |
| 280 | + "start_time": job_data.get("start_time", ""), |
| 281 | + "end_time": time.strftime("%Y-%m-%d %H:%M:%S"), |
| 282 | + "md5_checksums": md5_objects, |
| 283 | + |
| 284 | + |
| 285 | + } |
| 286 | + |
| 287 | + # Create the _tlab_provenance.json file |
| 288 | + provenance_file = model_service.create_provenance_file( |
| 289 | + model_path=dest, |
| 290 | + model_name=base_name, |
| 291 | + model_architecture=architecture, |
| 292 | + md5_objects=md5_objects, |
| 293 | + provenance_data=provenance_metadata |
| 294 | + ) |
| 295 | + self.log(f"Provenance file created at: {provenance_file}") |
| 296 | + except Exception as e: |
| 297 | + self.log(f"Warning: Model saved but provenance creation failed: {str(e)}") |
| 298 | + |
| 299 | + # Track in job_data |
| 300 | + try: |
| 301 | + job_data = self._job.get_job_data() |
| 302 | + model_list = [] |
| 303 | + if isinstance(job_data, dict): |
| 304 | + existing = job_data.get("models", []) |
| 305 | + if isinstance(existing, list): |
| 306 | + model_list = existing |
| 307 | + model_list.append(dest) |
| 308 | + self._job.update_job_data_field("models", model_list) |
| 309 | + except Exception: |
| 310 | + pass |
| 311 | + |
| 312 | + return dest |
| 313 | + |
180 | 314 | def error( |
181 | 315 | self, |
182 | 316 | message: str = "", |
|
0 commit comments