mars-rec 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mars_rec/__init__.py +31 -0
- mars_rec/cli.py +582 -0
- mars_rec/data/__init__.py +0 -0
- mars_rec/data/dataset.py +2486 -0
- mars_rec/data/task.py +519 -0
- mars_rec/data/utils.py +71 -0
- mars_rec/filtering.py +364 -0
- mars_rec/inference.py +1214 -0
- mars_rec/luigi.cfg +13 -0
- mars_rec/meta_config.py +282 -0
- mars_rec/model/__init__.py +0 -0
- mars_rec/model/abstract.py +64 -0
- mars_rec/model/base_model.py +60 -0
- mars_rec/simulation/__init__.py +0 -0
- mars_rec/simulation/training.py +2370 -0
- mars_rec/torch/__init__.py +0 -0
- mars_rec/torch/callbacks.py +65 -0
- mars_rec/torch/data.py +117 -0
- mars_rec/torch/init.py +23 -0
- mars_rec/torch/lightning_module.py +212 -0
- mars_rec/torch/loss.py +410 -0
- mars_rec/torch/metrics.py +284 -0
- mars_rec/torch/optimizer.py +129 -0
- mars_rec/torch/summary.py +130 -0
- mars_rec/utils/__init__.py +0 -0
- mars_rec/utils/download.py +101 -0
- mars_rec/utils/files.py +88 -0
- mars_rec/utils/index_mapping.py +156 -0
- mars_rec/utils/logging.py +116 -0
- mars_rec/utils/plot.py +606 -0
- mars_rec/utils/reflection.py +58 -0
- mars_rec/utils/utils.py +252 -0
- mars_rec/visualization.py +1524 -0
- mars_rec-0.1.0.dist-info/METADATA +163 -0
- mars_rec-0.1.0.dist-info/RECORD +37 -0
- mars_rec-0.1.0.dist-info/WHEEL +4 -0
- mars_rec-0.1.0.dist-info/entry_points.txt +2 -0
mars_rec/__init__.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""mars-rec — supervised training framework for recommender systems.
|
|
2
|
+
|
|
3
|
+
A lightweight version of MARS-Gym focused on the supervised side of
|
|
4
|
+
recsys research: data preparation, deep-learning model training, and
|
|
5
|
+
ranking-metric evaluation. Built on Luigi (pipeline), PyTorch /
|
|
6
|
+
PyTorch Lightning (training) and pandas (data).
|
|
7
|
+
|
|
8
|
+
Top-level entry points:
|
|
9
|
+
|
|
10
|
+
- :mod:`mars_rec.meta_config` — the :class:`ProjectConfig`
|
|
11
|
+
contract every project declares.
|
|
12
|
+
- :mod:`mars_rec.simulation.training` — the
|
|
13
|
+
:class:`SupervisedModelTraining` Luigi task that drives the whole
|
|
14
|
+
pipeline (also exposed as ``mars-rec run supervised``).
|
|
15
|
+
- :mod:`mars_rec.inference` — standalone top-k prediction
|
|
16
|
+
(``mars-rec predict``) and re-evaluation
|
|
17
|
+
(``mars-rec evaluate``) entry points.
|
|
18
|
+
- :mod:`mars_rec.data.task` — :class:`BasePrepareDataFrames`,
|
|
19
|
+
the abstract Luigi task projects subclass to materialise CSVs.
|
|
20
|
+
- :mod:`mars_rec.data.dataset` — PyTorch ``Dataset`` classes
|
|
21
|
+
with built-in negative sampling variants.
|
|
22
|
+
- :mod:`mars_rec.model.abstract` — :class:`RecommenderModule`,
|
|
23
|
+
the abstract base class for every model.
|
|
24
|
+
|
|
25
|
+
See ``examples/`` for end-to-end projects (MovieLens, Last.fm,
|
|
26
|
+
Online Retail, Amazon Beauty, MovieLens-100K slate ranking).
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
__version__ = "0.1.0"
|
|
30
|
+
|
|
31
|
+
import mars_rec.torch.metrics # noqa: F401 (side effect: populates METRIC_REGISTRY)
|
mars_rec/cli.py
ADDED
|
@@ -0,0 +1,582 @@
|
|
|
1
|
+
"""Click-based CLI for mars-rec.
|
|
2
|
+
|
|
3
|
+
Exposes the framework's main entry points as ``mars-rec`` shell
|
|
4
|
+
commands installed by ``pip install -e .``:
|
|
5
|
+
|
|
6
|
+
- ``mars-rec run supervised`` — dispatch a
|
|
7
|
+
:class:`SupervisedModelTraining` (or any task fully-qualified via
|
|
8
|
+
``--task-class``) through Luigi.
|
|
9
|
+
- ``mars-rec run data <module> <TaskClass>`` — run an arbitrary
|
|
10
|
+
data-preparation Luigi task.
|
|
11
|
+
- ``mars-rec list`` — list previously executed runs.
|
|
12
|
+
- ``mars-rec results`` — compare per-run metrics / hyperparameters.
|
|
13
|
+
- ``mars-rec predict`` / ``evaluate`` — wrappers around
|
|
14
|
+
:mod:`mars_rec.inference` and
|
|
15
|
+
:func:`mars_rec.simulation.training.run_evaluate`.
|
|
16
|
+
- ``mars-rec visualize`` — render the architecture diagram of a
|
|
17
|
+
trained run (see :mod:`mars_rec.visualization`).
|
|
18
|
+
|
|
19
|
+
Each command surfaces its CLI options via ``--help``; the function
|
|
20
|
+
docstrings below mirror those summaries so pydoc reflects the same
|
|
21
|
+
contract.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
import json
|
|
25
|
+
import os
|
|
26
|
+
import subprocess
|
|
27
|
+
import sys
|
|
28
|
+
from datetime import datetime
|
|
29
|
+
from typing import Tuple
|
|
30
|
+
|
|
31
|
+
import click
|
|
32
|
+
|
|
33
|
+
import mars_rec
|
|
34
|
+
|
|
35
|
+
os.environ["LUIGI_CONFIG_PATH"] = os.path.join(os.path.split(mars_rec.__file__)[0], "luigi.cfg")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _run_luigi(luigi_args) -> None:
|
|
39
|
+
"""Dispatch ``luigi`` in a subprocess and exit with its return code.
|
|
40
|
+
|
|
41
|
+
Uses ``sys.executable -m luigi`` (not whatever ``luigi`` is first on
|
|
42
|
+
``PATH``) so the task runs in the same interpreter/venv as this CLI,
|
|
43
|
+
and *prepends* the cwd to ``PYTHONPATH`` instead of overwriting it so
|
|
44
|
+
user-provided paths (e.g. ``PYTHONPATH=src:.``) keep working. Args are
|
|
45
|
+
passed as a list, so no shell quoting is involved.
|
|
46
|
+
"""
|
|
47
|
+
env = os.environ.copy()
|
|
48
|
+
existing = env.get("PYTHONPATH", "")
|
|
49
|
+
env["PYTHONPATH"] = os.pathsep.join([os.getcwd()] + ([existing] if existing else []))
|
|
50
|
+
cmd = [sys.executable, "-m", "luigi", "--module", *luigi_args, "--local-scheduler"]
|
|
51
|
+
result = subprocess.run(cmd, env=env)
|
|
52
|
+
if result.returncode != 0:
|
|
53
|
+
sys.exit(result.returncode)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _invalidate_supervised_cache(
|
|
57
|
+
args: Tuple[str],
|
|
58
|
+
module_path: str = "mars_rec.simulation.training",
|
|
59
|
+
class_name: str = "SupervisedModelTraining",
|
|
60
|
+
):
|
|
61
|
+
"""Build the dispatched training task from CLI args and delete its cached outputs."""
|
|
62
|
+
import importlib
|
|
63
|
+
import sys
|
|
64
|
+
|
|
65
|
+
cwd = os.getcwd()
|
|
66
|
+
if cwd not in sys.path:
|
|
67
|
+
sys.path.insert(0, cwd)
|
|
68
|
+
|
|
69
|
+
module = importlib.import_module(module_path)
|
|
70
|
+
task_cls = getattr(module, class_name)
|
|
71
|
+
|
|
72
|
+
params = {}
|
|
73
|
+
it = iter(args)
|
|
74
|
+
for arg in it:
|
|
75
|
+
if arg.startswith("--"):
|
|
76
|
+
key = arg.lstrip("-").replace("-", "_")
|
|
77
|
+
try:
|
|
78
|
+
value = next(it)
|
|
79
|
+
if value.startswith("--"):
|
|
80
|
+
params[key] = "True"
|
|
81
|
+
key = value.lstrip("-").replace("-", "_")
|
|
82
|
+
continue
|
|
83
|
+
params[key] = value
|
|
84
|
+
except StopIteration:
|
|
85
|
+
params[key] = "True"
|
|
86
|
+
|
|
87
|
+
task = task_cls.from_str_params(params)
|
|
88
|
+
task.invalidate_cache()
|
|
89
|
+
click.echo("Cache invalidated. Re-running entire pipeline...")
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _get_results_dir():
|
|
93
|
+
from mars_rec.utils.files import OUTPUT_PATH
|
|
94
|
+
|
|
95
|
+
return os.path.join(OUTPUT_PATH, "models", "SupervisedModelTraining", "results")
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _load_run(run_dir):
|
|
99
|
+
"""Load metadata for a single training run."""
|
|
100
|
+
params_path = os.path.join(run_dir, "params.json")
|
|
101
|
+
history_path = os.path.join(run_dir, "history.csv")
|
|
102
|
+
|
|
103
|
+
if not os.path.exists(params_path):
|
|
104
|
+
return None
|
|
105
|
+
|
|
106
|
+
with open(params_path) as f:
|
|
107
|
+
params = json.load(f)
|
|
108
|
+
|
|
109
|
+
# Get timestamp from params.json modification time
|
|
110
|
+
mtime = os.path.getmtime(params_path)
|
|
111
|
+
timestamp = datetime.fromtimestamp(mtime)
|
|
112
|
+
|
|
113
|
+
# Load best metrics from last epoch of history
|
|
114
|
+
best_metrics = {}
|
|
115
|
+
if os.path.exists(history_path):
|
|
116
|
+
import pandas as pd
|
|
117
|
+
|
|
118
|
+
history = pd.read_csv(history_path)
|
|
119
|
+
if len(history) > 0:
|
|
120
|
+
last = history.iloc[-1]
|
|
121
|
+
for col in history.columns:
|
|
122
|
+
if col != "epoch":
|
|
123
|
+
best_metrics[col] = last[col]
|
|
124
|
+
best_metrics["total_epochs"] = int(last["epoch"]) + 1
|
|
125
|
+
|
|
126
|
+
# Load ranking metrics from metadata.json (computed post-training)
|
|
127
|
+
metadata_path = os.path.join(run_dir, "metadata.json")
|
|
128
|
+
if os.path.exists(metadata_path):
|
|
129
|
+
with open(metadata_path) as f:
|
|
130
|
+
metadata = json.load(f)
|
|
131
|
+
ranking = metadata.get("ranking_metrics", {})
|
|
132
|
+
for k, v in ranking.items():
|
|
133
|
+
best_metrics[k] = v
|
|
134
|
+
roc_auc = metadata.get("roc_auc_metrics", {})
|
|
135
|
+
for k, v in roc_auc.items():
|
|
136
|
+
best_metrics[k] = v
|
|
137
|
+
|
|
138
|
+
return {
|
|
139
|
+
"task_id": os.path.basename(run_dir),
|
|
140
|
+
"path": run_dir,
|
|
141
|
+
"timestamp": timestamp,
|
|
142
|
+
"params": params,
|
|
143
|
+
"best_metrics": best_metrics,
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _load_all_runs(project_filter=None):
|
|
148
|
+
"""Load all training runs, optionally filtered by project."""
|
|
149
|
+
results_dir = _get_results_dir()
|
|
150
|
+
if not os.path.isdir(results_dir):
|
|
151
|
+
return []
|
|
152
|
+
|
|
153
|
+
runs = []
|
|
154
|
+
for name in os.listdir(results_dir):
|
|
155
|
+
run_dir = os.path.join(results_dir, name)
|
|
156
|
+
if not os.path.isdir(run_dir):
|
|
157
|
+
continue
|
|
158
|
+
run = _load_run(run_dir)
|
|
159
|
+
if run is None:
|
|
160
|
+
continue
|
|
161
|
+
if project_filter and project_filter not in run["params"].get("project", ""):
|
|
162
|
+
continue
|
|
163
|
+
runs.append(run)
|
|
164
|
+
|
|
165
|
+
runs.sort(key=lambda r: r["timestamp"], reverse=True)
|
|
166
|
+
return runs
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
@click.group()
|
|
170
|
+
def cli():
|
|
171
|
+
"""``mars-rec`` — supervised training framework for recommender systems."""
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
@cli.group()
|
|
175
|
+
def run():
|
|
176
|
+
"""Run training tasks."""
|
|
177
|
+
pass
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
@run.command(
|
|
181
|
+
context_settings=dict(
|
|
182
|
+
ignore_unknown_options=True,
|
|
183
|
+
),
|
|
184
|
+
add_help_option=False,
|
|
185
|
+
)
|
|
186
|
+
@click.option(
|
|
187
|
+
"--no-cache",
|
|
188
|
+
is_flag=True,
|
|
189
|
+
default=False,
|
|
190
|
+
help="Force re-execution of the entire pipeline, ignoring cached results.",
|
|
191
|
+
)
|
|
192
|
+
@click.option(
|
|
193
|
+
"--task-class",
|
|
194
|
+
default="mars_rec.simulation.training.SupervisedModelTraining",
|
|
195
|
+
help=(
|
|
196
|
+
"Fully-qualified path of the Luigi training task to dispatch "
|
|
197
|
+
"(e.g. a `SupervisedModelTraining` subclass in your project). "
|
|
198
|
+
"Default is `mars_rec.simulation.training.SupervisedModelTraining`."
|
|
199
|
+
),
|
|
200
|
+
)
|
|
201
|
+
@click.argument("args", nargs=-1, type=click.UNPROCESSED)
|
|
202
|
+
def supervised(no_cache: bool, task_class: str, args: Tuple[str]):
|
|
203
|
+
"""Run a supervised training task (default ``SupervisedModelTraining``).
|
|
204
|
+
|
|
205
|
+
Dispatches the configured task through Luigi with ``--local-scheduler``.
|
|
206
|
+
Extra positional arguments are forwarded verbatim as Luigi parameters
|
|
207
|
+
(e.g. ``--project examples.movielens.config.movielens
|
|
208
|
+
--recommender-module-class ... --epochs 5``).
|
|
209
|
+
"""
|
|
210
|
+
if "." not in task_class:
|
|
211
|
+
raise click.BadParameter(
|
|
212
|
+
f"--task-class must be a fully-qualified Python path (`module.submodule.ClassName`), got {task_class!r}"
|
|
213
|
+
)
|
|
214
|
+
module_path, class_name = task_class.rsplit(".", 1)
|
|
215
|
+
if no_cache:
|
|
216
|
+
_invalidate_supervised_cache(args, module_path=module_path, class_name=class_name)
|
|
217
|
+
_run_luigi([module_path, class_name, *args])
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
@run.command(
|
|
221
|
+
context_settings=dict(
|
|
222
|
+
ignore_unknown_options=True,
|
|
223
|
+
),
|
|
224
|
+
add_help_option=False,
|
|
225
|
+
)
|
|
226
|
+
@click.argument("args", nargs=-1, type=click.UNPROCESSED)
|
|
227
|
+
def data(args: Tuple[str]):
|
|
228
|
+
"""Run an arbitrary Luigi data-preparation task by ``module Task``.
|
|
229
|
+
|
|
230
|
+
Useful to materialise the train/val/test CSVs without launching a
|
|
231
|
+
training (e.g. ``mars-rec run data examples.movielens.data
|
|
232
|
+
PrepareMovieLensDataFrame``).
|
|
233
|
+
"""
|
|
234
|
+
_run_luigi(list(args))
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
@cli.command("list")
|
|
238
|
+
@click.option("--project", default=None, help="Filter by project name (substring match).")
|
|
239
|
+
@click.option("--limit", default=20, help="Max number of runs to show.")
|
|
240
|
+
def list_runs(project, limit):
|
|
241
|
+
"""List all executed training runs."""
|
|
242
|
+
runs = _load_all_runs(project_filter=project)
|
|
243
|
+
|
|
244
|
+
if not runs:
|
|
245
|
+
click.echo("No training runs found.")
|
|
246
|
+
return
|
|
247
|
+
|
|
248
|
+
runs = runs[:limit]
|
|
249
|
+
|
|
250
|
+
# Table header
|
|
251
|
+
click.echo(f"{'#':<4} {'Date':<18} {'Project':<40} {'Model':<40} {'Epochs':<8} {'Task ID'}")
|
|
252
|
+
click.echo("-" * 160)
|
|
253
|
+
|
|
254
|
+
for i, run in enumerate(runs, 1):
|
|
255
|
+
p = run["params"]
|
|
256
|
+
project_name = p.get("project", "?").split(".")[-1]
|
|
257
|
+
model_name = p.get("recommender_module_class", "?").split(".")[-1]
|
|
258
|
+
date_str = run["timestamp"].strftime("%Y-%m-%d %H:%M")
|
|
259
|
+
epochs = run["best_metrics"].get("total_epochs", p.get("epochs", "?"))
|
|
260
|
+
task_id = run["task_id"]
|
|
261
|
+
|
|
262
|
+
click.echo(f"{i:<4} {date_str:<18} {project_name:<40} {model_name:<40} {epochs:<8} {task_id}")
|
|
263
|
+
|
|
264
|
+
click.echo(f"\nTotal: {len(runs)} run(s)")
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
@cli.command("results")
|
|
268
|
+
@click.option("--project", default=None, help="Filter by project name (substring match).")
|
|
269
|
+
@click.option(
|
|
270
|
+
"--metric",
|
|
271
|
+
multiple=True,
|
|
272
|
+
help="Metrics to display (e.g. --metric val_loss --metric val_binary_accuracy). Shows all if omitted.",
|
|
273
|
+
)
|
|
274
|
+
@click.option("--sort-by", default=None, help="Sort results by this metric (ascending).")
|
|
275
|
+
@click.option("--limit", default=20, help="Max number of runs to show.")
|
|
276
|
+
@click.option(
|
|
277
|
+
"--params", multiple=True, help="Extra params to display as columns (e.g. --params learning_rate --params epochs)."
|
|
278
|
+
)
|
|
279
|
+
def results(project, metric, sort_by, limit, params):
|
|
280
|
+
"""Compare results across training runs."""
|
|
281
|
+
import pandas as pd
|
|
282
|
+
|
|
283
|
+
runs = _load_all_runs(project_filter=project)
|
|
284
|
+
|
|
285
|
+
if not runs:
|
|
286
|
+
click.echo("No training runs found.")
|
|
287
|
+
return
|
|
288
|
+
|
|
289
|
+
# Build comparison table
|
|
290
|
+
rows = []
|
|
291
|
+
for run in runs:
|
|
292
|
+
p = run["params"]
|
|
293
|
+
row = {
|
|
294
|
+
"date": run["timestamp"].strftime("%Y-%m-%d %H:%M"),
|
|
295
|
+
"project": p.get("project", "?").split(".")[-1],
|
|
296
|
+
"model": p.get("recommender_module_class", "?").split(".")[-1],
|
|
297
|
+
"epochs": run["best_metrics"].get("total_epochs", p.get("epochs", "?")),
|
|
298
|
+
"lr": p.get("learning_rate"),
|
|
299
|
+
"batch_size": p.get("batch_size"),
|
|
300
|
+
"loss_fn": p.get("loss_function"),
|
|
301
|
+
"optimizer": p.get("optimizer"),
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
# Add extra params (also search inside recommender_extra_params)
|
|
305
|
+
extra = p.get("recommender_extra_params", {})
|
|
306
|
+
for param in params:
|
|
307
|
+
if param in p:
|
|
308
|
+
row[param] = p[param]
|
|
309
|
+
elif param in extra:
|
|
310
|
+
row[param] = extra[param]
|
|
311
|
+
else:
|
|
312
|
+
row[param] = "?"
|
|
313
|
+
|
|
314
|
+
# Add metrics
|
|
315
|
+
for k, v in run["best_metrics"].items():
|
|
316
|
+
if k == "total_epochs":
|
|
317
|
+
continue
|
|
318
|
+
if metric and k not in metric:
|
|
319
|
+
continue
|
|
320
|
+
if isinstance(v, float):
|
|
321
|
+
row[k] = round(v, 6)
|
|
322
|
+
else:
|
|
323
|
+
row[k] = v
|
|
324
|
+
|
|
325
|
+
row["task_id"] = run["task_id"]
|
|
326
|
+
rows.append(row)
|
|
327
|
+
|
|
328
|
+
df = pd.DataFrame(rows)
|
|
329
|
+
|
|
330
|
+
if sort_by and sort_by in df.columns:
|
|
331
|
+
df = df.sort_values(sort_by, ascending=True).reset_index(drop=True)
|
|
332
|
+
|
|
333
|
+
df = df.head(limit)
|
|
334
|
+
df.index = range(1, len(df) + 1)
|
|
335
|
+
df.index.name = "#"
|
|
336
|
+
|
|
337
|
+
# Separate into config cols and metric cols for display
|
|
338
|
+
config_cols = ["date", "project", "model", "epochs", "lr", "batch_size", "loss_fn", "optimizer"]
|
|
339
|
+
config_cols += list(params)
|
|
340
|
+
metric_cols = [c for c in df.columns if c not in config_cols and c != "task_id"]
|
|
341
|
+
|
|
342
|
+
display_cols = [c for c in config_cols if c in df.columns] + metric_cols + ["task_id"]
|
|
343
|
+
|
|
344
|
+
pd.set_option("display.max_columns", None)
|
|
345
|
+
pd.set_option("display.width", None)
|
|
346
|
+
pd.set_option("display.max_colwidth", 30)
|
|
347
|
+
|
|
348
|
+
click.echo(df[display_cols].to_string())
|
|
349
|
+
click.echo(f"\nTotal: {len(df)} run(s)")
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
@cli.command("predict")
|
|
353
|
+
@click.option("--model-dir", required=False, default=None, help="Full path to the model task directory.")
|
|
354
|
+
@click.option(
|
|
355
|
+
"--task-id", required=False, default=None, help="Task ID (looks up inside the standard results directory)."
|
|
356
|
+
)
|
|
357
|
+
@click.option("--data", required=True, help="Path to input data file (parquet or CSV).")
|
|
358
|
+
@click.option("--output", default="result.json", help="Output file path.")
|
|
359
|
+
@click.option("--batch-size", default=128, type=int, help="Batch size for inference.")
|
|
360
|
+
@click.option("--top-k", default=10, type=int, help="Number of top items per user.")
|
|
361
|
+
@click.option("--device", default="cpu", help="Device for inference (cpu, cuda, cuda:0, ...).")
|
|
362
|
+
def predict(model_dir, task_id, data, output, batch_size, top_k, device):
|
|
363
|
+
"""Run inference on a trained model and produce top-k predictions."""
|
|
364
|
+
import sys
|
|
365
|
+
|
|
366
|
+
cwd = os.getcwd()
|
|
367
|
+
if cwd not in sys.path:
|
|
368
|
+
sys.path.insert(0, cwd)
|
|
369
|
+
|
|
370
|
+
if model_dir is None and task_id is None:
|
|
371
|
+
click.echo("Error: Provide either --model-dir or --task-id.", err=True)
|
|
372
|
+
raise SystemExit(1)
|
|
373
|
+
|
|
374
|
+
if model_dir is None:
|
|
375
|
+
model_dir = os.path.join(_get_results_dir(), task_id)
|
|
376
|
+
|
|
377
|
+
if not os.path.isdir(model_dir):
|
|
378
|
+
click.echo(f"Error: Directory not found: {model_dir}", err=True)
|
|
379
|
+
raise SystemExit(1)
|
|
380
|
+
|
|
381
|
+
from mars_rec.inference import run_inference
|
|
382
|
+
|
|
383
|
+
run_inference(
|
|
384
|
+
task_dir=model_dir,
|
|
385
|
+
data_path=data,
|
|
386
|
+
output_path=output,
|
|
387
|
+
batch_size=batch_size,
|
|
388
|
+
k=top_k,
|
|
389
|
+
device=device,
|
|
390
|
+
)
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
@cli.command("evaluate")
|
|
394
|
+
@click.option("--model-dir", required=False, default=None, help="Full path to the model task directory.")
|
|
395
|
+
@click.option(
|
|
396
|
+
"--task-id", required=False, default=None, help="Task ID (looks up inside the standard results directory)."
|
|
397
|
+
)
|
|
398
|
+
@click.option(
|
|
399
|
+
"--data",
|
|
400
|
+
default=None,
|
|
401
|
+
help="Path to external data file (CSV or parquet) for evaluation. Must contain the target column. If omitted, uses original training splits.",
|
|
402
|
+
)
|
|
403
|
+
@click.option(
|
|
404
|
+
"--metric",
|
|
405
|
+
multiple=True,
|
|
406
|
+
help="Override validation metrics (e.g. --metric loss --metric f1_score --metric binary_accuracy). Uses original if omitted.",
|
|
407
|
+
)
|
|
408
|
+
@click.option(
|
|
409
|
+
"--ranking-metrics/--no-ranking-metrics",
|
|
410
|
+
default=None,
|
|
411
|
+
help="Enable/disable ranking metrics (NDCG, HitRate, MRR, MAP).",
|
|
412
|
+
)
|
|
413
|
+
@click.option("--sample-size-eval", default=None, type=int, help="Override test-set sample size for evaluation.")
|
|
414
|
+
@click.option("--batch-size", default=None, type=int, help="Override batch size for evaluation.")
|
|
415
|
+
@click.option("--device", default=None, help="Override device (cpu, cuda, mps).")
|
|
416
|
+
@click.option(
|
|
417
|
+
"--split",
|
|
418
|
+
type=click.Choice(["val", "test", "all"]),
|
|
419
|
+
default="all",
|
|
420
|
+
help="Which split to evaluate: val, test, or all (default). Ignored when --data is provided.",
|
|
421
|
+
)
|
|
422
|
+
@click.option(
|
|
423
|
+
"--output",
|
|
424
|
+
default=None,
|
|
425
|
+
help="Directory to save evaluation artifacts (plots, predictions, eval_results.json). Defaults to the model task directory.",
|
|
426
|
+
)
|
|
427
|
+
@click.option(
|
|
428
|
+
"--prefilter/--no-prefilter",
|
|
429
|
+
default=False,
|
|
430
|
+
help="Apply the project's CandidateProvider (eligibility filter) when generating ranking-metrics candidates. Default off: ranking metrics are computed against the legacy random-sample candidate pool. Configs without a provider declared are unaffected.",
|
|
431
|
+
)
|
|
432
|
+
def evaluate_cmd(
|
|
433
|
+
model_dir, task_id, data, metric, ranking_metrics, sample_size_eval, batch_size, device, split, output, prefilter
|
|
434
|
+
):
|
|
435
|
+
"""Re-run evaluation on training splits or on a new external dataset.
|
|
436
|
+
|
|
437
|
+
\b
|
|
438
|
+
Flow 1 (original data):
|
|
439
|
+
mars-rec evaluate --task-id <ID> --ranking-metrics --metric f1_score
|
|
440
|
+
|
|
441
|
+
\b
|
|
442
|
+
Flow 2 (external data):
|
|
443
|
+
mars-rec evaluate --task-id <ID> --data new_test.parquet --ranking-metrics
|
|
444
|
+
"""
|
|
445
|
+
import sys
|
|
446
|
+
|
|
447
|
+
cwd = os.getcwd()
|
|
448
|
+
if cwd not in sys.path:
|
|
449
|
+
sys.path.insert(0, cwd)
|
|
450
|
+
|
|
451
|
+
if model_dir is None and task_id is None:
|
|
452
|
+
click.echo("Error: Provide either --model-dir or --task-id.", err=True)
|
|
453
|
+
raise SystemExit(1)
|
|
454
|
+
|
|
455
|
+
if model_dir is None:
|
|
456
|
+
model_dir = os.path.join(_get_results_dir(), task_id)
|
|
457
|
+
|
|
458
|
+
if not os.path.isdir(model_dir):
|
|
459
|
+
click.echo(f"Error: Directory not found: {model_dir}", err=True)
|
|
460
|
+
raise SystemExit(1)
|
|
461
|
+
|
|
462
|
+
if data is not None and not os.path.isfile(data):
|
|
463
|
+
click.echo(f"Error: Data file not found: {data}", err=True)
|
|
464
|
+
raise SystemExit(1)
|
|
465
|
+
|
|
466
|
+
from mars_rec.simulation.training import run_evaluate
|
|
467
|
+
|
|
468
|
+
metrics_list = list(metric) if metric else None
|
|
469
|
+
|
|
470
|
+
results = run_evaluate(
|
|
471
|
+
task_dir=model_dir,
|
|
472
|
+
metrics=metrics_list,
|
|
473
|
+
ranking_metrics=ranking_metrics,
|
|
474
|
+
sample_size_eval=sample_size_eval,
|
|
475
|
+
batch_size=batch_size,
|
|
476
|
+
device=device,
|
|
477
|
+
eval_split=split,
|
|
478
|
+
data_path=data,
|
|
479
|
+
output_dir=output,
|
|
480
|
+
enable_prefilter=prefilter,
|
|
481
|
+
)
|
|
482
|
+
|
|
483
|
+
# Print summary
|
|
484
|
+
click.echo("\n" + "=" * 60)
|
|
485
|
+
click.echo("EVALUATION SUMMARY")
|
|
486
|
+
click.echo("=" * 60)
|
|
487
|
+
|
|
488
|
+
if "val_metrics" in results and results["val_metrics"]:
|
|
489
|
+
click.echo("\nPoint-wise metrics:")
|
|
490
|
+
for k, v in results["val_metrics"].items():
|
|
491
|
+
click.echo(f" {k}: {v:.6f}" if isinstance(v, float) else f" {k}: {v}")
|
|
492
|
+
|
|
493
|
+
if results.get("ranking_metrics"):
|
|
494
|
+
click.echo("\nRanking metrics:")
|
|
495
|
+
for k, v in results["ranking_metrics"].items():
|
|
496
|
+
click.echo(f" {k}: {v:.6f}")
|
|
497
|
+
|
|
498
|
+
if results.get("roc_auc_metrics"):
|
|
499
|
+
click.echo("\nROC-AUC metrics:")
|
|
500
|
+
for k, v in results["roc_auc_metrics"].items():
|
|
501
|
+
click.echo(f" {k}: {v:.6f}")
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
@cli.command("visualize")
|
|
505
|
+
@click.option("--model-dir", required=False, default=None, help="Full path to the model task directory.")
|
|
506
|
+
@click.option(
|
|
507
|
+
"--task-id", required=False, default=None, help="Task ID (looks up inside the standard results directory)."
|
|
508
|
+
)
|
|
509
|
+
@click.option(
|
|
510
|
+
"--mode",
|
|
511
|
+
type=click.Choice(["svg", "summary"]),
|
|
512
|
+
default="svg",
|
|
513
|
+
help="svg: writes architecture.svg (default). summary: prints a text table.",
|
|
514
|
+
)
|
|
515
|
+
@click.option(
|
|
516
|
+
"--output", "-o", default=None, help="Output .svg path (svg mode only). Defaults to <task_dir>/architecture.svg."
|
|
517
|
+
)
|
|
518
|
+
@click.option(
|
|
519
|
+
"--trace/--no-trace", default=True, help="Trace tensor shapes via a forward pass (slightly slower, more accurate)."
|
|
520
|
+
)
|
|
521
|
+
@click.option("--device", default="cpu", help="Device for model instantiation.")
|
|
522
|
+
def visualize(model_dir, task_id, mode, output, trace, device):
|
|
523
|
+
"""Generate the architecture diagram for a trained model.
|
|
524
|
+
|
|
525
|
+
\b
|
|
526
|
+
Modes:
|
|
527
|
+
svg — Hand-rolled SVG flow diagram with feature pills, role
|
|
528
|
+
colors, and tensor shapes (default). No external deps.
|
|
529
|
+
summary — Enhanced text table with feature groups + layer list.
|
|
530
|
+
"""
|
|
531
|
+
import sys
|
|
532
|
+
|
|
533
|
+
cwd = os.getcwd()
|
|
534
|
+
if cwd not in sys.path:
|
|
535
|
+
sys.path.insert(0, cwd)
|
|
536
|
+
|
|
537
|
+
if model_dir is None and task_id is None:
|
|
538
|
+
click.echo("Error: Provide either --model-dir or --task-id.", err=True)
|
|
539
|
+
raise SystemExit(1)
|
|
540
|
+
|
|
541
|
+
if model_dir is None:
|
|
542
|
+
model_dir = os.path.join(_get_results_dir(), task_id)
|
|
543
|
+
|
|
544
|
+
if not os.path.isdir(model_dir):
|
|
545
|
+
click.echo(f"Error: Directory not found: {model_dir}", err=True)
|
|
546
|
+
raise SystemExit(1)
|
|
547
|
+
|
|
548
|
+
from mars_rec.visualization import (
|
|
549
|
+
generate_architecture_diagram,
|
|
550
|
+
load_model_from_task,
|
|
551
|
+
print_text_summary,
|
|
552
|
+
)
|
|
553
|
+
|
|
554
|
+
click.echo(f"Loading model from: {model_dir}")
|
|
555
|
+
model, project_config, index_mapping, params = load_model_from_task(
|
|
556
|
+
model_dir,
|
|
557
|
+
device=device,
|
|
558
|
+
)
|
|
559
|
+
model_cls = params.get("recommender_module_class", "?").split(".")[-1]
|
|
560
|
+
click.echo(f"Model: {model_cls} | Input columns: {len(project_config.input_columns)}")
|
|
561
|
+
|
|
562
|
+
if mode == "summary":
|
|
563
|
+
print_text_summary(model, project_config, params)
|
|
564
|
+
return
|
|
565
|
+
|
|
566
|
+
if output is None:
|
|
567
|
+
output = os.path.join(model_dir, "architecture.svg")
|
|
568
|
+
|
|
569
|
+
rendered = generate_architecture_diagram(
|
|
570
|
+
model,
|
|
571
|
+
project_config,
|
|
572
|
+
params,
|
|
573
|
+
output,
|
|
574
|
+
index_mapping=index_mapping,
|
|
575
|
+
trace=trace,
|
|
576
|
+
device=device,
|
|
577
|
+
)
|
|
578
|
+
click.echo(f"SVG diagram saved to: {rendered}" + (" (with forward-pass shape trace)" if trace else ""))
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
if __name__ == "__main__":
|
|
582
|
+
cli()
|
|
File without changes
|