File size: 13,238 Bytes
c4b87d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a58567
c4b87d2
 
 
 
 
0a58567
 
 
c4b87d2
0a58567
 
 
 
c4b87d2
 
 
 
 
 
 
 
 
 
 
 
0a58567
c4b87d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a58567
c4b87d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a58567
 
c4b87d2
0a58567
c4b87d2
 
0a58567
c4b87d2
0a58567
 
 
c4b87d2
 
 
 
 
 
 
0a58567
c4b87d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a58567
c4b87d2
 
 
 
 
 
 
 
 
 
0a58567
c4b87d2
 
 
 
 
 
0a58567
 
c4b87d2
0a58567
c4b87d2
0a58567
c4b87d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a58567
 
c4b87d2
0a58567
c4b87d2
0a58567
c4b87d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a58567
 
c4b87d2
0a58567
c4b87d2
0a58567
c4b87d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a58567
c4b87d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a58567
c4b87d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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
import argparse
import logging
import warnings
from pathlib import Path

import matplotlib
from gluonts.model.evaluation import evaluate_model
from gluonts.time_feature import get_seasonality
from linear_operator.utils.cholesky import NumericalWarning

from src.gift_eval.constants import (
    DATASET_PROPERTIES,
    MED_LONG_DATASETS,
    METRICS,
    PRETTY_NAMES,
)
from src.gift_eval.core import DatasetMetadata, EvaluationItem, expand_datasets_arg
from src.gift_eval.data import Dataset
from src.gift_eval.predictor import TimeSeriesPredictor
from src.gift_eval.results import write_results_to_disk
from src.plotting.gift_eval_utils import create_plots_for_dataset

logger = logging.getLogger(__name__)

# Warnings configuration
warnings.filterwarnings("ignore", category=NumericalWarning)
warnings.filterwarnings("ignore", category=FutureWarning)
warnings.filterwarnings("ignore", category=DeprecationWarning)
matplotlib.set_loglevel("WARNING")
logging.getLogger("matplotlib").setLevel(logging.WARNING)
logging.getLogger("matplotlib.font_manager").setLevel(logging.WARNING)
logging.getLogger("PIL").setLevel(logging.WARNING)


class WarningFilter(logging.Filter):
    def __init__(self, text_to_filter: str) -> None:
        super().__init__()
        self.text_to_filter = text_to_filter

    def filter(self, record: logging.LogRecord) -> bool:
        return self.text_to_filter not in record.getMessage()


# Filter out gluonts warnings about mean predictions
gts_logger = logging.getLogger("gluonts.model.forecast")
gts_logger.addFilter(WarningFilter("The mean prediction is not stored in the forecast data"))


def construct_evaluation_data(
    dataset_name: str,
    dataset_storage_path: str,
    terms: list[str] | None = None,
    max_windows: int | None = None,
) -> list[tuple[Dataset, DatasetMetadata]]:
    """Build datasets and rich metadata per term for a dataset name."""
    if terms is None:
        terms = ["short", "medium", "long"]

    sub_datasets: list[tuple[Dataset, DatasetMetadata]] = []

    if "/" in dataset_name:
        ds_key, ds_freq = dataset_name.split("/")
        ds_key = ds_key.lower()
        ds_key = PRETTY_NAMES.get(ds_key, ds_key)
    else:
        ds_key = dataset_name.lower()
        ds_key = PRETTY_NAMES.get(ds_key, ds_key)
        ds_freq = DATASET_PROPERTIES.get(ds_key, {}).get("frequency")

    for term in terms:
        # Skip medium/long terms for datasets that don't support them
        if (term == "medium" or term == "long") and dataset_name not in MED_LONG_DATASETS:
            continue

        # Probe once to determine dimensionality
        probe_dataset = Dataset(
            name=dataset_name,
            term=term,
            to_univariate=False,
            storage_path=dataset_storage_path,
            max_windows=max_windows,
        )

        to_univariate = probe_dataset.target_dim > 1

        dataset = Dataset(
            name=dataset_name,
            term=term,
            to_univariate=to_univariate,
            storage_path=dataset_storage_path,
            max_windows=max_windows,
        )

        # Compute metadata
        season_length = get_seasonality(dataset.freq)
        actual_freq = ds_freq if ds_freq else dataset.freq

        metadata = DatasetMetadata(
            full_name=f"{ds_key}/{actual_freq}/{term}",
            key=ds_key,
            freq=actual_freq,
            term=term,
            season_length=season_length,
            target_dim=probe_dataset.target_dim,
            to_univariate=to_univariate,
            prediction_length=dataset.prediction_length,
            windows=dataset.windows,
        )

        sub_datasets.append((dataset, metadata))

    return sub_datasets


def evaluate_datasets(
    predictor: TimeSeriesPredictor,
    dataset: str,
    dataset_storage_path: str,
    terms: list[str] | None = None,
    max_windows: int | None = None,
    batch_size: int = 48,
    max_context_length: int | None = 1024,
    create_plots: bool = False,
    max_plots_per_dataset: int = 10,
) -> list[EvaluationItem]:
    """Evaluate predictor on one dataset across the requested terms."""
    if terms is None:
        terms = ["short", "medium", "long"]

    sub_datasets = construct_evaluation_data(
        dataset_name=dataset,
        dataset_storage_path=dataset_storage_path,
        terms=terms,
        max_windows=max_windows,
    )

    results: list[EvaluationItem] = []
    for i, (sub_dataset, metadata) in enumerate(sub_datasets):
        logger.info(f"Evaluating {i + 1}/{len(sub_datasets)}: {metadata.full_name}")
        logger.info(f"  Dataset size: {len(sub_dataset.test_data)}")
        logger.info(f"  Frequency: {sub_dataset.freq}")
        logger.info(f"  Term: {metadata.term}")
        logger.info(f"  Prediction length: {sub_dataset.prediction_length}")
        logger.info(f"  Target dimensions: {sub_dataset.target_dim}")
        logger.info(f"  Windows: {sub_dataset.windows}")

        # Update context on the reusable predictor
        predictor.set_dataset_context(
            prediction_length=sub_dataset.prediction_length,
            freq=sub_dataset.freq,
            batch_size=batch_size,
            max_context_length=max_context_length,
        )

        res = evaluate_model(
            model=predictor,
            test_data=sub_dataset.test_data,
            metrics=METRICS,
            axis=None,
            mask_invalid_label=True,
            allow_nan_forecast=False,
            seasonality=metadata.season_length,
        )

        figs: list[tuple[object, str]] = []
        if create_plots:
            forecasts = predictor.predict(sub_dataset.test_data.input)
            figs = create_plots_for_dataset(
                forecasts=forecasts,
                test_data=sub_dataset.test_data,
                dataset_metadata=metadata,
                max_plots=max_plots_per_dataset,
                max_context_length=max_context_length,
            )

        results.append(EvaluationItem(dataset_metadata=metadata, metrics=res, figures=figs))

    return results


def _run_evaluation(
    predictor: TimeSeriesPredictor,
    datasets: list[str] | str,
    terms: list[str],
    dataset_storage_path: str,
    max_windows: int | None = None,
    batch_size: int = 48,
    max_context_length: int | None = 1024,
    output_dir: str = "gift_eval_results",
    model_name: str = "TimeSeriesModel",
    create_plots: bool = False,
    max_plots: int = 10,
) -> None:
    """Shared evaluation workflow used by both entry points."""
    datasets_to_run = expand_datasets_arg(datasets)
    results_root = Path(output_dir)

    for ds_name in datasets_to_run:
        items = evaluate_datasets(
            predictor=predictor,
            dataset=ds_name,
            dataset_storage_path=dataset_storage_path,
            terms=terms,
            max_windows=max_windows,
            batch_size=batch_size,
            max_context_length=max_context_length,
            create_plots=create_plots,
            max_plots_per_dataset=max_plots,
        )
        write_results_to_disk(
            items=items,
            dataset_name=ds_name,
            output_dir=results_root,
            model_name=model_name,
            create_plots=create_plots,
        )


def evaluate_from_paths(
    model_path: str,
    config_path: str,
    datasets: list[str] | str,
    terms: list[str],
    dataset_storage_path: str,
    max_windows: int | None = None,
    batch_size: int = 48,
    max_context_length: int | None = 1024,
    output_dir: str = "gift_eval_results",
    model_name: str = "TimeSeriesModel",
    create_plots: bool = False,
    max_plots: int = 10,
) -> None:
    """Entry point: load model from disk and save metrics/plots to disk."""
    # Validate inputs early
    if not Path(model_path).exists():
        raise FileNotFoundError(f"Model path does not exist: {model_path}")
    if not Path(config_path).exists():
        raise FileNotFoundError(f"Config path does not exist: {config_path}")

    predictor = TimeSeriesPredictor.from_paths(
        model_path=model_path,
        config_path=config_path,
        ds_prediction_length=1,  # placeholder; set per dataset below
        ds_freq="D",  # placeholder; set per dataset below
        batch_size=batch_size,
        max_context_length=max_context_length,
    )

    _run_evaluation(
        predictor=predictor,
        datasets=datasets,
        terms=terms,
        dataset_storage_path=dataset_storage_path,
        max_windows=max_windows,
        batch_size=batch_size,
        max_context_length=max_context_length,
        output_dir=output_dir,
        model_name=model_name,
        create_plots=create_plots,
        max_plots=max_plots,
    )


def evaluate_in_memory(
    model,
    config: dict,
    datasets: list[str] | str,
    terms: list[str],
    dataset_storage_path: str,
    max_windows: int | None = None,
    batch_size: int = 48,
    max_context_length: int | None = 1024,
    output_dir: str = "gift_eval_results",
    model_name: str = "TimeSeriesModel",
    create_plots: bool = False,
    max_plots: int = 10,
) -> None:
    """Entry point: evaluate in-memory model and return results per dataset."""
    predictor = TimeSeriesPredictor.from_model(
        model=model,
        config=config,
        ds_prediction_length=1,  # placeholder; set per dataset below
        ds_freq="D",  # placeholder; set per dataset below
        batch_size=batch_size,
        max_context_length=max_context_length,
    )

    _run_evaluation(
        predictor=predictor,
        datasets=datasets,
        terms=terms,
        dataset_storage_path=dataset_storage_path,
        max_windows=max_windows,
        batch_size=batch_size,
        max_context_length=max_context_length,
        output_dir=output_dir,
        model_name=model_name,
        create_plots=create_plots,
        max_plots=max_plots,
    )


def _parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Evaluate TimeSeriesModel on GIFT-Eval datasets")

    # Model configuration
    parser.add_argument(
        "--model_path",
        type=str,
        required=True,
        help="Path to the trained model checkpoint",
    )
    parser.add_argument(
        "--config_path",
        type=str,
        required=True,
        help="Path to the model configuration YAML file",
    )
    parser.add_argument(
        "--model_name",
        type=str,
        default="TimeSeriesModel",
        help="Name identifier for the model",
    )

    # Dataset configuration
    parser.add_argument(
        "--datasets",
        type=str,
        default="all",
        help="Comma-separated list of dataset names to evaluate (or 'all')",
    )
    parser.add_argument(
        "--dataset_storage_path",
        type=str,
        default="/work/dlclarge2/moroshav-GiftEvalPretrain/gift_eval",
        help="Path to the dataset storage directory (default: GIFT_EVAL)",
    )
    parser.add_argument(
        "--terms",
        type=str,
        default="short,medium,long",
        help="Comma-separated list of prediction terms to evaluate",
    )
    parser.add_argument(
        "--max_windows",
        type=int,
        default=None,
        help="Maximum number of windows to use for evaluation",
    )

    # Inference configuration
    parser.add_argument("--batch_size", type=int, default=48, help="Batch size for model inference")
    parser.add_argument(
        "--max_context_length",
        type=int,
        default=1024,
        help="Maximum context length to use (None for no limit)",
    )

    # Output configuration
    parser.add_argument(
        "--output_dir",
        type=str,
        default="gift_eval_results",
        help="Directory to save evaluation results",
    )

    # Plotting configuration
    parser.add_argument(
        "--create_plots",
        action="store_true",
        help="Create and save plots for each evaluation window",
    )
    parser.add_argument(
        "--max_plots_per_dataset",
        type=int,
        default=10,
        help="Maximum number of plots to create per dataset term",
    )

    args = parser.parse_args()
    args.terms = args.terms.split(",")
    args.datasets = args.datasets.split(",")
    return args


def _configure_logging() -> None:
    logging.basicConfig(
        level=logging.INFO,
        format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    )


if __name__ == "__main__":
    _configure_logging()
    args = _parse_args()
    logger.info(f"Command Line Arguments: {vars(args)}")
    try:
        evaluate_from_paths(
            model_path=args.model_path,
            config_path=args.config_path,
            datasets=args.datasets,
            terms=args.terms,
            dataset_storage_path=args.dataset_storage_path,
            max_windows=args.max_windows,
            batch_size=args.batch_size,
            max_context_length=args.max_context_length,
            output_dir=args.output_dir,
            model_name=args.model_name,
            create_plots=args.create_plots,
            max_plots=args.max_plots_per_dataset,
        )
    except Exception as e:
        logger.error(f"Evaluation failed: {str(e)}")
        raise