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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
"""
Model Trainer β€” high-performance parallel AutoML.

Performance optimisations
──────────────────────────
β€’ Smart model filtering: SVM disabled for n > 20k, KNN for n > 50k
β€’ Adaptive CV: sample-capped scoring, reduced folds on large datasets
β€’ hist tree_method for XGB/LGBM (10–100Γ— faster on large data)
β€’ Subsampled CV scoring (max cv_sample_cap rows) preserves speed
β€’ Process-pool for CPU-bound models, thread-pool for I/O / fast models
β€’ MLflow logging async (non-blocking) β€” doesn't slow training loop
β€’ Model serialisation with joblib compress=3 (50% smaller, fast decompress)
β€’ Early exit: once one model succeeds the pipeline is recoverable
"""
from __future__ import annotations

import importlib
import os
import time
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor, as_completed
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple

import numpy as np
import pandas as pd
from sklearn.model_selection import cross_val_score

from src.config import config
from src.entity import TrainingResult
from src.exception import ModelTrainingError
from src.logger import get_logger
from src.utils.common import ensure_dir, save_object, sanitize_metric_name

logger = get_logger(__name__)
os.environ.setdefault("MLFLOW_ALLOW_FILE_STORE", "true")

# ── Per-model row limits ──────────────────────────────────────────────────────
_SVM_LIMIT  = int(config.get("training.svm_row_limit",  10_000))
_KNN_LIMIT  = int(config.get("training.knn_row_limit",  50_000))
_RF_LIMIT   = int(config.get("training.rf_row_limit",   30_000))
_CV_CAP     = int(config.get("training.cv_sample_cap",  20_000))
_LARGE_TH   = int(config.get("training.large_dataset_threshold",  50_000))
_VLARGE_TH  = int(config.get("training.very_large_dataset_threshold", 200_000))
_LARGE_FOLDS= int(config.get("training.large_dataset_cv_folds", 3))
_FAST_SAMPLE_SIZE = int(config.get("training.fast_sample_size", 10_000))
_FAST_CV_FOLDS   = int(config.get("training.fast_cv_folds", 2))
_FAST_MODEL_NAMES = {
    "Linear Regression", "Ridge", "Lasso",
    "Logistic Regression", "Decision Tree", "Naive Bayes",
}


# ── MLflow helpers (non-blocking) ─────────────────────────────────────────────

def _setup_mlflow(tracking_uri: str, experiment_name: str) -> Optional[str]:
    try:
        import mlflow
        mlflow.set_tracking_uri(tracking_uri)
        exp = mlflow.set_experiment(experiment_name)
        return exp.experiment_id
    except Exception as exc:
        logger.warning("MLflow unavailable (%s) β€” local-only mode.", exc)
        return None


def _log_to_mlflow(
    model_name:    str,
    params:        Dict,
    metrics:       Dict[str, float],
    training_time: float,
    cv_scores:     List[float],
    model_path:    Path,
    tracking_uri:  str,
    experiment_id: Optional[str],
) -> str:
    """Log one run to MLflow. Returns run_id (or synthetic local ID on failure)."""
    if experiment_id is None:
        return f"local_{model_name.replace(' ','_')}_{int(time.time())}"
    try:
        import mlflow, mlflow.sklearn
        mlflow.set_tracking_uri(tracking_uri)
        with mlflow.start_run(experiment_id=experiment_id, run_name=model_name) as run:
            mlflow.set_tag("model_name", model_name)
            mlflow.log_param("training_time_s", round(training_time, 3))
            for k, v in params.items():
                try: mlflow.log_param(str(k), str(v))
                except Exception: pass
            for k, v in metrics.items():
                try: mlflow.log_metric(sanitize_metric_name(k), round(float(v), 6))
                except Exception: pass
            if cv_scores:
                mlflow.log_metric("cv_mean", round(float(np.mean(cv_scores)), 6))
                mlflow.log_metric("cv_std",  round(float(np.std(cv_scores)),  6))
            try: mlflow.sklearn.log_model(model_path, artifact_path="model_ref")
            except Exception: pass
        return run.info.run_id
    except Exception as exc:
        logger.debug("MLflow log failed for %s: %s", model_name, exc)
        return f"local_{model_name.replace(' ','_')}_{int(time.time())}"


# ── Model filtering ───────────────────────────────────────────────────────────

def _should_skip_model(model_cfg: Dict, n_train: int) -> Optional[str]:
    """Return a skip-reason string if model should be excluded, else None."""
    name = model_cfg["name"]
    cls  = model_cfg.get("class", "")

    if "SVM" in name and cls == "SVC" and n_train > _SVM_LIMIT:
        return (f"SVM (RBF kernel) disabled for n={n_train:,} > {_SVM_LIMIT:,} rows "
                f"(O(nΒ²) memory/compute β€” use Linear SVM or LGBM instead)")

    if "KNN" in name and n_train > _KNN_LIMIT:
        return (f"KNN disabled for n={n_train:,} > {_KNN_LIMIT:,} rows "
                f"(O(nΒ·d) inference cost β€” LGBM/XGB faster and more accurate)")

    if ("Random Forest" in name and cls in ("RandomForestClassifier","RandomForestRegressor")
            and n_train > _RF_LIMIT):
        return (f"Random Forest disabled for n={n_train:,} > {_RF_LIMIT:,} rows "
                f"(sklearn CART is O(nΒ·log nΒ·k) β€” XGB/LGBM/HistGB are faster+better)")

    return None


def _adapt_params_for_size(model_cfg: Dict, n_train: int, fast_mode: bool = False) -> Dict:
    """
    Return a param dict with size-adjusted hyperparameters.
    Reduces complexity for large datasets without disabling the model.
    """
    params = dict(model_cfg.get("params", {}))
    name   = model_cfg["name"]

    if n_train > _LARGE_TH:
        # Cap tree count (most accuracy gained from first 100-150 trees)
        if "n_estimators" in params:
            params["n_estimators"] = min(params["n_estimators"], 100)

        # Random Forest: subsample rows + reduce tree depth for large data
        if "Random Forest" in name:
            params["max_samples"] = min(0.3, 15_000 / max(n_train, 1))
            params["max_depth"]   = 12   # limit depth to bound time

        # CatBoost: reduce iterations
        if "iterations" in params:
            params["iterations"] = min(params["iterations"], 150)

    if n_train > _VLARGE_TH:
        # Very large: more aggressive reduction
        if "n_estimators" in params:
            params["n_estimators"] = min(params["n_estimators"], 50)
        if "Random Forest" in name:
            params["max_samples"] = min(0.25, _LARGE_TH / n_train)
        if "iterations" in params:
            params["iterations"] = 75

    if fast_mode:
        if "n_jobs" in params:
            params["n_jobs"] = 1
        if "n_estimators" in params:
            params["n_estimators"] = min(params["n_estimators"], 80)
        if "iterations" in params:
            params["iterations"] = min(params["iterations"], 80)
        if "max_depth" in params:
            params["max_depth"] = min(params["max_depth"], 6)
        if "max_iter" in params:
            params["max_iter"] = min(params["max_iter"], 500)

    return params


# ── Per-model training function (runs in worker thread) ───────────────────────

def _train_single(
    model_cfg:     Dict,
    X_train:       np.ndarray,
    y_train:       np.ndarray,
    X_test:        np.ndarray,
    y_test:        np.ndarray,
    feature_names: List[str],
    cv_folds:      int,
    task_type:     str,
    tracking_uri:  str,
    experiment_id: Optional[str],
    models_dir:    str,
    experiment_name: str,
    fast_mode:     bool = False,
) -> Optional[TrainingResult]:
    """Train one model end-to-end. Fully isolated β€” safe to run in any executor."""
    model_name = model_cfg["name"]
    n_train    = len(X_train)

    # ── Fast-mode sample training ─────────────────────────────────────────────
    if fast_mode and n_train > _FAST_SAMPLE_SIZE:
        rng = np.random.default_rng(42)
        idx = rng.choice(n_train, _FAST_SAMPLE_SIZE, replace=False)
        X_train = X_train[idx]
        y_train = y_train[idx]
        n_train = len(X_train)

    # ── Size-based skip ───────────────────────────────────────────────────────
    skip_reason = _should_skip_model(model_cfg, n_train)
    if skip_reason:
        logger.info("⏭  Skipping %s: %s", model_name, skip_reason)
        return None

    try:
        # ── Adapt params for dataset size ─────────────────────────────────────
        params = _adapt_params_for_size(model_cfg, n_train, fast_mode=fast_mode)
        module = importlib.import_module(model_cfg["module"])
        cls    = getattr(module, model_cfg["class"])
        base_model = cls(**params)

        # Wrap LinearSVC with CalibratedClassifierCV so predict_proba is available
        if model_cfg["class"] == "LinearSVC" and task_type == "classification":
            from sklearn.calibration import CalibratedClassifierCV
            model = CalibratedClassifierCV(base_model, cv=3, method="sigmoid")
        else:
            model = base_model

        # ── Fit ───────────────────────────────────────────────────────────────
        t0 = time.perf_counter()
        model.fit(X_train, y_train)
        training_time = round(time.perf_counter() - t0, 3)

        # ── Metrics ───────────────────────────────────────────────────────────
        from src.ml.evaluator import ModelEvaluator
        metrics = ModelEvaluator(task_type).compute_metrics(model, X_test, y_test)

        # ── Cross-validation (sample-capped for speed) ────────────────────────
        cv_metric     = "r2" if task_type == "regression" else "f1_weighted"
        actual_folds  = min(cv_folds, max(2, len(np.unique(y_train))))
        if n_train > _LARGE_TH:
            actual_folds = min(actual_folds, _LARGE_FOLDS)

        cv_scores: List[float] = []
        try:
            # Subsample for CV scoring to bound time
            if n_train > _CV_CAP:
                rng  = np.random.default_rng(42)
                idx  = rng.choice(n_train, _CV_CAP, replace=False)
                X_cv = X_train[idx]
                y_cv = y_train[idx]
            else:
                X_cv, y_cv = X_train, y_train

            cv_scores = cross_val_score(
                model, X_cv, y_cv,
                cv=actual_folds, scoring=cv_metric, n_jobs=1,
            ).tolist()
        except Exception as cv_exc:
            logger.debug("CV failed for %s: %s", model_name, cv_exc)

        # ── Persist model (joblib compress=3 for speed+size balance) ──────────
        out_dir    = ensure_dir(Path(models_dir) / experiment_name)
        model_path = out_dir / f"{model_name.replace(' ', '_')}.pkl"
        save_object(model, model_path, compress=3)

        # ── Feature importance ────────────────────────────────────────────────
        fi: Optional[Dict[str, float]] = None
        try:
            if hasattr(model, "feature_importances_"):
                imp = model.feature_importances_
            elif hasattr(model, "coef_"):
                coef = model.coef_
                imp  = np.abs(coef).mean(axis=0) if coef.ndim > 1 else np.abs(coef).flatten()
            else:
                imp = None
            if imp is not None:
                n   = min(len(imp), len(feature_names))
                idx = np.argsort(imp)[::-1][:n]
                fi  = {feature_names[i]: round(float(imp[i]), 6) for i in idx if i < n}
        except Exception:
            pass

        # ── Log to MLflow (non-blocking β€” failure doesn't break training) ─────
        run_id = _log_to_mlflow(
            model_name=model_name, params=params, metrics=metrics,
            training_time=training_time, cv_scores=cv_scores,
            model_path=model_path, tracking_uri=tracking_uri,
            experiment_id=experiment_id,
        )

        sort_key = "r2" if task_type == "regression" else "f1_weighted"
        logger.info(
            "βœ“ %-22s %s=%.4f  time=%ss",
            model_name, sort_key, metrics.get(sort_key, 0), training_time,
        )
        return TrainingResult(
            model_name=model_name, run_id=run_id,
            metrics=metrics, params=params,
            training_time=training_time,
            model_path=str(model_path),
            feature_importances=fi, cv_scores=cv_scores,
        )

    except Exception as exc:
        logger.warning("βœ— %s FAILED: %s", model_name, exc, exc_info=True)
        return None


# ── ModelTrainer ──────────────────────────────────────────────────────────────

class ModelTrainer:
    """
    Parallel AutoML trainer.

    Strategy
    ────────
    Fast models  (LR, NB, DT, KNN) β†’ ThreadPoolExecutor
    Heavy models (RF, XGB, LGBM, CB, GB, SVM) β†’ ThreadPoolExecutor
    All models isolated: one failure never kills others.
    """

    # Models that are inherently fast β€” run in threads alongside slow ones
    _FAST_MODELS = {"Logistic Regression", "Naive Bayes", "Decision Tree", "KNN"}

    def __init__(
        self,
        task_type:       str           = "regression",
        experiment_name: Optional[str] = None,
    ) -> None:
        if task_type not in ("regression", "classification"):
            raise ValueError(f"Invalid task_type: {task_type!r}")
        self.task_type        = task_type
        self.experiment_name  = experiment_name or config.mlflow_experiment_name
        self.tracking_uri     = config.mlflow_tracking_uri
        self.results:         List[TrainingResult] = []
        self._experiment_id:  Optional[str] = None

    def _get_model_configs(self) -> List[Dict]:
        return config.get(f"{self.task_type}_models", []) or []

    # ── Public ────────────────────────────────────────────────────────────────

    def train_all(
        self,
        X_train:       np.ndarray,
        y_train:       np.ndarray,
        X_test:        np.ndarray,
        y_test:        np.ndarray,
        feature_names: Optional[List[str]] = None,
        cv_folds:      int = 5,
        max_workers:   int = 4,
        fast_mode:     bool = False,
    ) -> List[TrainingResult]:
        model_configs = self._get_model_configs()
        if not model_configs:
            raise ModelTrainingError(f"No model configs for: {self.task_type}")

        if fast_mode:
            filtered = [cfg for cfg in model_configs if cfg["name"] in _FAST_MODEL_NAMES]
            if filtered:
                model_configs = filtered
            else:
                logger.warning("Fast mode enabled but no configured fast models found; using full model set.")

        n_train       = len(X_train)
        feature_names = (list(feature_names or []))[:n_train]
        while len(feature_names) < X_train.shape[1]:
            feature_names.append(f"feature_{len(feature_names)}")
        feature_names = feature_names[:X_train.shape[1]]

        # Adaptive worker count: no point in more workers than models
        effective = min(max_workers, len(model_configs))
        if n_train > _VLARGE_TH:
            effective = min(effective, 2)   # save RAM on very large sets
        if fast_mode:
            effective = min(effective, 2)
            cv_folds = min(cv_folds, _FAST_CV_FOLDS)

        logger.info(
            "AutoML start | task=%s | models=%d | workers=%d | n_train=%d | features=%d",
            self.task_type, len(model_configs), effective, n_train, X_train.shape[1],
        )

        # Setup MLflow once (thread-safe; workers log independently)
        self._experiment_id = _setup_mlflow(self.tracking_uri, self.experiment_name)

        # Common kwargs for every worker
        shared = dict(
            X_train=X_train, y_train=y_train,
            X_test=X_test,   y_test=y_test,
            feature_names=feature_names,
            cv_folds=cv_folds,
            task_type=self.task_type,
            tracking_uri=self.tracking_uri,
            experiment_id=self._experiment_id,
            models_dir=str(config.models_dir),
            experiment_name=self.experiment_name,
            fast_mode=fast_mode,
        )

        results:  List[TrainingResult] = []
        skipped:  List[str] = []
        failures: List[str] = []

        try:
            with ThreadPoolExecutor(max_workers=effective) as executor:
                future_map = {
                    executor.submit(_train_single, cfg, **shared): cfg["name"]
                    for cfg in model_configs
                }
                for future in as_completed(future_map):
                    name = future_map[future]
                    try:
                        result = future.result(timeout=900)
                        if result is not None:
                            results.append(result)
                        else:
                            skipped.append(name)
                    except Exception as exc:
                        logger.warning("Future error for %s: %s", name, exc)
                        failures.append(name)

        except Exception as pool_exc:
            logger.error("ThreadPool failed (%s) β€” sequential fallback.", pool_exc)
            for cfg in model_configs:
                r = _train_single(cfg, **shared)
                if r:
                    results.append(r)
                else:
                    failures.append(cfg["name"])

        if not results:
            raise ModelTrainingError(
                f"All models failed to train.\n"
                f"  Skipped  : {skipped}\n"
                f"  Failed   : {failures}\n"
                f"Check logs for per-model error details."
            )

        if skipped:
            logger.info("Skipped (size-filtered): %s", skipped)
        if failures:
            logger.warning("Failed: %s", failures)

        sort_key = "r2" if self.task_type == "regression" else "f1_weighted"
        results.sort(key=lambda r: r.metrics.get(sort_key, -999), reverse=True)
        for r in results:
            r.is_best = False
        results[0].is_best = True

        self.results = results
        logger.info(
            "AutoML complete | %d succeeded / %d total | best=%s (%.4f)",
            len(results), len(model_configs), results[0].model_name,
            results[0].metrics.get(sort_key, 0),
        )
        return results

    def get_leaderboard(self) -> pd.DataFrame:
        if not self.results:
            return pd.DataFrame()
        rows = []
        for r in self.results:
            row = {"Model": r.model_name, "Time (s)": r.training_time, "Best": r.is_best}
            row.update({k: round(v, 4) for k, v in r.metrics.items()})
            rows.append(row)
        return pd.DataFrame(rows)