mars-rec 0.1.0__tar.gz

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.
Files changed (65) hide show
  1. mars_rec-0.1.0/.gitignore +81 -0
  2. mars_rec-0.1.0/AGENTS.md +420 -0
  3. mars_rec-0.1.0/PKG-INFO +163 -0
  4. mars_rec-0.1.0/README.md +115 -0
  5. mars_rec-0.1.0/examples/__init__.py +0 -0
  6. mars_rec-0.1.0/examples/amazon_beauty/__init__.py +0 -0
  7. mars_rec-0.1.0/examples/amazon_beauty/config.py +39 -0
  8. mars_rec-0.1.0/examples/amazon_beauty/data.py +159 -0
  9. mars_rec-0.1.0/examples/amazon_beauty/model.py +58 -0
  10. mars_rec-0.1.0/examples/amazon_beauty/run_training.py +63 -0
  11. mars_rec-0.1.0/examples/lastfm/__init__.py +0 -0
  12. mars_rec-0.1.0/examples/lastfm/config.py +37 -0
  13. mars_rec-0.1.0/examples/lastfm/data.py +160 -0
  14. mars_rec-0.1.0/examples/lastfm/model.py +99 -0
  15. mars_rec-0.1.0/examples/lastfm/run_training.py +64 -0
  16. mars_rec-0.1.0/examples/movielens/__init__.py +0 -0
  17. mars_rec-0.1.0/examples/movielens/config.py +27 -0
  18. mars_rec-0.1.0/examples/movielens/data.py +187 -0
  19. mars_rec-0.1.0/examples/movielens/model.py +88 -0
  20. mars_rec-0.1.0/examples/movielens/run_training.py +62 -0
  21. mars_rec-0.1.0/examples/movielens100k_slate/__init__.py +0 -0
  22. mars_rec-0.1.0/examples/movielens100k_slate/config.py +43 -0
  23. mars_rec-0.1.0/examples/movielens100k_slate/data.py +181 -0
  24. mars_rec-0.1.0/examples/movielens100k_slate/model.py +67 -0
  25. mars_rec-0.1.0/examples/movielens100k_slate/run_training.py +63 -0
  26. mars_rec-0.1.0/examples/online_retail/__init__.py +0 -0
  27. mars_rec-0.1.0/examples/online_retail/config.py +40 -0
  28. mars_rec-0.1.0/examples/online_retail/data.py +131 -0
  29. mars_rec-0.1.0/examples/online_retail/model.py +66 -0
  30. mars_rec-0.1.0/examples/online_retail/run_training.py +61 -0
  31. mars_rec-0.1.0/pyproject.toml +144 -0
  32. mars_rec-0.1.0/requirements.lock +140 -0
  33. mars_rec-0.1.0/src/mars_rec/__init__.py +31 -0
  34. mars_rec-0.1.0/src/mars_rec/cli.py +582 -0
  35. mars_rec-0.1.0/src/mars_rec/data/__init__.py +0 -0
  36. mars_rec-0.1.0/src/mars_rec/data/dataset.py +2486 -0
  37. mars_rec-0.1.0/src/mars_rec/data/task.py +519 -0
  38. mars_rec-0.1.0/src/mars_rec/data/utils.py +71 -0
  39. mars_rec-0.1.0/src/mars_rec/filtering.py +364 -0
  40. mars_rec-0.1.0/src/mars_rec/inference.py +1214 -0
  41. mars_rec-0.1.0/src/mars_rec/luigi.cfg +13 -0
  42. mars_rec-0.1.0/src/mars_rec/meta_config.py +282 -0
  43. mars_rec-0.1.0/src/mars_rec/model/__init__.py +0 -0
  44. mars_rec-0.1.0/src/mars_rec/model/abstract.py +64 -0
  45. mars_rec-0.1.0/src/mars_rec/model/base_model.py +60 -0
  46. mars_rec-0.1.0/src/mars_rec/simulation/__init__.py +0 -0
  47. mars_rec-0.1.0/src/mars_rec/simulation/training.py +2370 -0
  48. mars_rec-0.1.0/src/mars_rec/torch/__init__.py +0 -0
  49. mars_rec-0.1.0/src/mars_rec/torch/callbacks.py +65 -0
  50. mars_rec-0.1.0/src/mars_rec/torch/data.py +117 -0
  51. mars_rec-0.1.0/src/mars_rec/torch/init.py +23 -0
  52. mars_rec-0.1.0/src/mars_rec/torch/lightning_module.py +212 -0
  53. mars_rec-0.1.0/src/mars_rec/torch/loss.py +410 -0
  54. mars_rec-0.1.0/src/mars_rec/torch/metrics.py +284 -0
  55. mars_rec-0.1.0/src/mars_rec/torch/optimizer.py +129 -0
  56. mars_rec-0.1.0/src/mars_rec/torch/summary.py +130 -0
  57. mars_rec-0.1.0/src/mars_rec/utils/__init__.py +0 -0
  58. mars_rec-0.1.0/src/mars_rec/utils/download.py +101 -0
  59. mars_rec-0.1.0/src/mars_rec/utils/files.py +88 -0
  60. mars_rec-0.1.0/src/mars_rec/utils/index_mapping.py +156 -0
  61. mars_rec-0.1.0/src/mars_rec/utils/logging.py +116 -0
  62. mars_rec-0.1.0/src/mars_rec/utils/plot.py +606 -0
  63. mars_rec-0.1.0/src/mars_rec/utils/reflection.py +58 -0
  64. mars_rec-0.1.0/src/mars_rec/utils/utils.py +252 -0
  65. mars_rec-0.1.0/src/mars_rec/visualization.py +1524 -0
@@ -0,0 +1,81 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # Distribution / packaging
7
+ .Python
8
+ build/
9
+ dist/
10
+ env/
11
+ venv/
12
+ ENV/
13
+ *.egg-info/
14
+ .eggs/
15
+ *.egg
16
+
17
+ # Conda
18
+ *.conda
19
+ *.condarc
20
+ .conda/
21
+
22
+ # Virtual environments
23
+ .venv/
24
+ venv/
25
+ env/
26
+ ENV/
27
+
28
+ # IDEs
29
+ .vscode/
30
+ .idea/
31
+ *.sublime-project
32
+ *.sublime-workspace
33
+
34
+ # macOS
35
+ .DS_Store
36
+ .AppleDouble
37
+ .LSOverride
38
+
39
+ # Jupyter
40
+ .ipynb_checkpoints
41
+
42
+ # Logs and temporary files
43
+ *.log
44
+ *.tmp
45
+ *.swp
46
+ *.bak
47
+
48
+ # Output folders
49
+ output/
50
+
51
+ # MkDocs build output
52
+ site/
53
+
54
+ # Python bytecode cache
55
+ src/mars_rec/**/__pycache__/
56
+ examples/**/__pycache__/
57
+ .local
58
+ .pytest_cache/
59
+ .claude
60
+ checkpoints/
61
+
62
+ # Secrets / credentials (never commit)
63
+ .env
64
+ .env.*
65
+ !.env.example
66
+ *-credentials.json
67
+ service-account*.json
68
+ *.key
69
+ *.pem
70
+ *.p12
71
+ *.pfx
72
+
73
+ # Training artifacts that may embed identifiers
74
+ lightning_logs/
75
+ mlruns/
76
+ logs/
77
+ output_v8/
78
+ # Coverage artifacts
79
+ .coverage
80
+ .coverage.*
81
+ htmlcov/
@@ -0,0 +1,420 @@
1
+ # AGENTS.md — Guide for AI Agents
2
+
3
+ This document guides AI agents (Claude Code, Copilot, Cursor, etc.) on how to navigate, modify, and extend the MARS-Rec project.
4
+
5
+ ## Language standard
6
+
7
+ **All documentation, code comments, commit messages, and PR descriptions in this project MUST be written in English.** This is an international project and English is the standard language across all artifacts.
8
+
9
+ ## Work in a git worktree (mandatory)
10
+
11
+ **Every task that modifies files MUST be done in a dedicated git worktree, never directly in the main checkout.** The main checkout may hold someone else's in-progress work (or another agent's); a worktree isolates each task on its own branch.
12
+
13
+ 1. Create the worktree under `.claude/worktrees/` (gitignored), branching from an up-to-date `main` and using the branch prefixes from `CONTRIBUTING.md`:
14
+ ```bash
15
+ git fetch origin main
16
+ git worktree add .claude/worktrees/<short-name> -b <type>/<short-name> origin/main
17
+ cd .claude/worktrees/<short-name>
18
+ ```
19
+ Claude Code agents can use the built-in `EnterWorktree` tool instead, which does the same thing.
20
+ 2. Run every command (edits, `make lint`, `make test`, git) from inside the worktree. Do not `cd` back to the main checkout to work.
21
+ 3. **Set `PYTHONPATH=src:.`** for anything that imports `mars_rec`. The shared `.venv` has an *editable install pointing at the main checkout's `src/`*, so without it Python silently loads the main checkout's code, not the worktree's:
22
+ ```bash
23
+ PYTHONPATH=src:. make test
24
+ PYTHONPATH=src:. python -c "import mars_rec; print(mars_rec.__file__)" # must print a path inside the worktree
25
+ ```
26
+ 4. Training outputs default to `output/` relative to the current directory, so runs started in a worktree stay in that worktree. Set `OUTPUT_PATH` explicitly to reuse cached datasets/runs from the main checkout.
27
+ 5. Do not use bare `git stash` / `git stash pop`: the stash stack is shared across all worktrees. Use a temporary WIP commit instead.
28
+ 6. When the branch is merged (or abandoned), remove the worktree: `git worktree remove .claude/worktrees/<short-name>` and delete the branch.
29
+
30
+ Read-only tasks (answering questions, reviewing code, exploring) do not need a worktree.
31
+
32
+ ## Project overview
33
+
34
+ MARS-Rec is a framework for training deep learning models for recommendation systems. It uses Luigi for pipeline orchestration, PyTorch for models, and PyTorch Lightning for the training loop. It contains no Reinforcement Learning, bandits, or exploration policy code.
35
+
36
+ **Scope rule**: this repository holds only the framework (`src/mars_rec/`) and the reference projects under `examples/`. Application / competition / research code (custom models, sweeps, submission pipelines) does not belong here — keep it in a separate project that depends on `mars-rec` as a library. Framework code must stay domain-agnostic: no hard-coded column names, dataset names or competition-specific logic in `src/`.
37
+
38
+ ## Directory structure
39
+
40
+ ```
41
+ src/mars_rec/ # Framework source code (the only installable package)
42
+ meta_config.py # ProjectConfig, Column, IOType — central definitions
43
+ cli.py # CLI (Click): "run supervised", "run data", "list", "results", "predict", "evaluate", "visualize"
44
+ filtering.py # CandidateProvider / CandidateFilter — inference-time candidate pools
45
+ inference.py # Standalone inference + evaluation (run_inference, run_evaluate)
46
+ visualization.py # Architecture visualization — single module, SVG-only.
47
+ # Exposes generate_architecture_diagram(), trace_model_shapes(),
48
+ # extract_model_ir(), render_svg_flow(), load_model_from_task(),
49
+ # print_text_summary(). No external system deps.
50
+ luigi.cfg # Default Luigi configuration
51
+ data/
52
+ dataset.py # PyTorch Datasets (InteractionsDataset and negative sampling variants)
53
+ task.py # BasePrepareDataFrames — Luigi task for train/val/test split
54
+ utils.py # DownloadDataset helper
55
+ model/
56
+ abstract.py # RecommenderModule — base class for ALL models
57
+ base_model.py # LogisticRegression — baseline model
58
+ simulation/
59
+ training.py # SupervisedModelTraining + run_evaluate — MAIN FILE (~2.4k lines)
60
+ torch/
61
+ callbacks.py # Lightning callbacks
62
+ data.py # Custom DataLoader and BatchSampler
63
+ init.py # Weight initializers
64
+ lightning_module.py # RecommenderLightningModule (Lightning wrapper)
65
+ loss.py # Custom loss functions
66
+ metrics.py # Evaluation metrics (METRIC_REGISTRY)
67
+ optimizer.py # RAdam optimizer
68
+ summary.py # Model summary print
69
+ utils/
70
+ files.py # Output artifact path functions (OUTPUT_PATH env var supported)
71
+ index_mapping.py # Categorical → integer mapping for embeddings
72
+ logging.py # Logger setup
73
+ reflection.py # load_attr — dynamic module import by string
74
+ utils.py # General utilities (parallel literal_eval, reduce memory)
75
+ download.py # download_file — stdlib HTTP download (certifi CA bundle, atomic rename)
76
+ plot.py # Training history plots
77
+
78
+ examples/ # Reference recsys projects (public datasets, auto-download)
79
+ movielens/ # MovieLens 1M — NCF (collaborative filtering + side features)
80
+ lastfm/ # Last.fm HetRec 2K — sequential SASRec-lite
81
+ online_retail/ # UCI Online Retail — session-based GRU4Rec (session_id as user)
82
+ amazon_beauty/ # Amazon Beauty 5-core — content-based two-tower (text emb)
83
+ movielens100k_slate/ # MovieLens 100K — slate ranking (available_items + metadata)
84
+
85
+ docs/ # Documentation site (MkDocs Material) — published to GitHub Pages
86
+ _ext/griffe_sphinx_roles.py # Docs-only griffe extension: Sphinx roles → Markdown links
87
+ reference/api/*.md # mkdocstrings stubs (`::: mars_rec.<module>`) — API pages are generated
88
+ mkdocs.yml # Site config + nav (strict build)
89
+
90
+ scripts/
91
+ make_vertex_config.py # Builds the Vertex AI job config used by `make vertex-run`
92
+ make_regression_fixtures.py # Regenerates tests/_fixtures/{legacy_artifacts,golden_history.json}
93
+
94
+ tests/ # Pytest suite (test_dataset, test_loss, test_metrics, test_meta_config, ...)
95
+ CONTRIBUTING.md # Branch / lint / PR workflow
96
+ .github/ # CI + Docs + Release (PyPI, on v* tags) workflows, Dependabot, PR template
97
+ Makefile # Development / Docker / Vertex AI targets (`make lint` = ruff check + format --check)
98
+ Dockerfile # CPU/GPU image (default base: pytorch/pytorch:2.14.1-cuda12.6)
99
+ entrypoint.sh # Container entrypoint (dataset download, Vertex AI artifact upload)
100
+ pyproject.toml # Package metadata + dependencies; requirements.lock pins them
101
+ ```
102
+
103
+ ## Execution flow
104
+
105
+ The pipeline follows this sequence orchestrated by Luigi:
106
+
107
+ ```
108
+ 1. DataTask (e.g., GenerateSyntheticData)
109
+ └── Generates or downloads raw data
110
+ │
111
+ 2. BasePrepareDataFrames (e.g., PrepareSyntheticDataFrame)
112
+ └── Reads CSV → filters → splits train/val/test → saves 3 CSVs
113
+ │
114
+ 3. SupervisedModelTraining
115
+ ├── Loads train/val/test DataFrames
116
+ ├── Creates index_mapping (categorical → integer)
117
+ ├── Instantiates the model (RecommenderModule) within RecommenderLightningModule
118
+ ├── Trains with PyTorch Lightning (callbacks: EarlyStopping, Checkpoint, CSVLogger, TensorBoard if the `tensorboard` extra is installed)
119
+ ├── Evaluates on the validation set
120
+ ├── Generates predictions on the test set
121
+ ├── Optional: ranking metrics (NDCG/HitRate/MRR/MAP @{5,10,20}) + ROC-AUC → metadata.json
122
+ └── Saves artifacts (weights.ckpt, history.csv, params.json, metadata.json, etc.)
123
+ ```
124
+
125
+ After training, two standalone entry points reuse the same artifacts:
126
+
127
+ - **`run_inference`** (`inference.py`) — top-k predictions from a `params.json` + `weights.ckpt` + `index_mapping.pkl`, exposed as `mars-rec predict`.
128
+ - **`run_evaluate`** (`simulation/training.py`) — re-runs evaluation on the original test split or on an external CSV/parquet, exposed as `mars-rec evaluate`.
129
+
130
+ ## Key concepts the agent MUST understand
131
+
132
+ ### 1. ProjectConfig is the central contract
133
+
134
+ All configuration for a recommendation project lives in `ProjectConfig`. It defines:
135
+ - Which columns exist and their types (`IOType`)
136
+ - Which task prepares the data
137
+ - Which dataset class to use
138
+
139
+ **Location**: `src/mars_rec/meta_config.py`
140
+
141
+ When creating a new project, ALWAYS start with the `ProjectConfig`.
142
+
143
+ ### 2. Dynamic class resolution by string
144
+
145
+ The framework uses strings to reference classes (via `load_attr` in `utils/reflection.py`):
146
+
147
+ ```python
148
+ # Example: "examples.movielens.model.MovieLensNCF"
149
+ # Is resolved to the MovieLensNCF class at runtime
150
+ ```
151
+
152
+ This means `project` and `recommender_module_class` are **importable Python paths** (dotted notation). The `PYTHONPATH` must include the project root directory.
153
+
154
+ ### 3. forward() argument order
155
+
156
+ The model's `forward()` method receives tensors in the **same order** as the columns defined in `ProjectConfig.input_columns`:
157
+
158
+ ```python
159
+ # If ProjectConfig has:
160
+ # user_column = Column("user_id", IOType.INDEXABLE)
161
+ # item_column = Column("item_id", IOType.INDEXABLE)
162
+ # other_input_columns = [Column("price", IOType.NUMBER)]
163
+ # Then forward receives:
164
+ def forward(self, user_ids, item_ids, price):
165
+ ```
166
+
167
+ ### 4. forward() output shape
168
+
169
+ The expected `forward()` output depends on the loss function:
170
+
171
+ | Loss | Output shape | Notes |
172
+ |---|---|---|
173
+ | `bce`, `implicit_feedback_bce` | `[batch_size]` | Probabilities (apply `sigmoid` in the model) |
174
+ | `bce_logits`, `bce_logits_smooth`, `focal_loss` | `[batch_size]` | Raw logits (in `_LOGIT_LOSSES`; metrics get `sigmoid(score)`) |
175
+ | `bpr`, `ranknet`, `lambdarank` | `[batch_size]` | Raw logits; pairwise/listwise over the batch |
176
+ | `mse`, `dummy` | `[batch_size]` | One score per row |
177
+ | `ce`, `nll` | `[batch_size, n_items]` | Scores over the item vocabulary (next-item / sequence models) |
178
+ | `infonce`, `cosine_similarity`, `hardneg_infonce` | embeddings | `EmbeddingRecommenderLightningModule` |
179
+
180
+ The user-facing version of this table lives in `docs/concepts/models.md` — keep both in sync.
181
+
182
+ For `[batch_size, 1]` outputs, add `.squeeze(-1)`:
183
+
184
+ ```python
185
+ def forward(self, user_ids, item_ids):
186
+ ...
187
+ return torch.sigmoid(score).squeeze(-1) # [batch, 1] → [batch]
188
+ ```
189
+
190
+ For CE-based next-item prediction, return logits without squeezing:
191
+
192
+ ```python
193
+ def forward(self, *features):
194
+ ...
195
+ return self.head(hidden) # [batch, n_items]
196
+ ```
197
+
198
+ Mismatched shapes are the most common source of `RuntimeError: target size != input size`.
199
+
200
+ ### 5. Index mapping
201
+
202
+ Columns of type `IOType.INDEXABLE` are converted from categorical values to integers before being passed to the model. The mapping is automatically created by `SupervisedModelTraining` and saved to `index_mapping.pkl`.
203
+
204
+ - Index `0` is reserved for unknown values (never seen during training)
205
+ - Index `1` is reserved for `None` / `NaN`
206
+ - Index `2` is reserved for `-1` / `"-1"` (the pad token for sequence columns)
207
+ - Actual values start at `3`
208
+
209
+ Inference never returns a reserved slot as a recommendation: `build_reverse_item_mapping` drops them and `predict_top_k` masks their logits.
210
+
211
+ ### 6. Luigi caching and --no-cache
212
+
213
+ Luigi marks tasks as DONE based on the existence of output files. If a training run fails midway but the output directory was already created, Luigi may consider the task complete. To force re-execution:
214
+
215
+ - Use `--no-cache` in the CLI: `mars-rec run supervised --no-cache ...`
216
+ - Manually delete the output directory, OR
217
+ - Change a task parameter (generates a new task_id hash)
218
+
219
+ `--no-cache` works by calling `task.invalidate_cache()` which deletes the data preparation and training outputs before starting Luigi, forcing re-execution of the entire pipeline.
220
+
221
+ ### 7. CLI commands
222
+
223
+ The CLI exposes seven commands rooted at `mars-rec`:
224
+
225
+ | Command | Purpose |
226
+ |---|---|
227
+ | `run supervised [--no-cache]` | Full training pipeline (data prep + train + eval). `--no-cache` calls `task.invalidate_cache()` to force re-execution. |
228
+ | `run data <module> <Task>` | Run an arbitrary Luigi task (e.g. just the data preparation). |
229
+ | `list [--project] [--limit]` | List executed runs (date, project, model, epochs, task_id). |
230
+ | `results [--project] [--metric] [--sort-by] [--params] [--limit]` | Compare metrics across runs; reads `params.json` + `history.csv` + `metadata.json`. |
231
+ | `predict --task-id … --data … [--top-k] [--device]` | Standalone batch inference → `result.json` with top-k items per user. Implemented in `inference.run_inference`. |
232
+ | `evaluate --task-id … [--data] [--metric] [--ranking-metrics] [--split]` | Re-run evaluation on original splits (Flow 1) or on an external CSV/parquet (Flow 2). Implemented in `simulation.training.run_evaluate`. Writes `metadata.json` so `list/results` pick up the new metrics. |
233
+ | `visualize --task-id … [--mode {svg,summary}] [--trace/--no-trace] [--output]` | Generate the architecture diagram. `svg` (default) writes a hand-rolled SVG flow diagram with role colors + feature pills + tensor shapes. `summary` prints a text table. `--trace` (default on) runs a forward pass with synthetic inputs to capture real tensor shapes via hooks. The legacy `block`/`torchviz` modes and the `--format` flag were removed in the visualization refactor — every training run now emits `architecture.svg` next to the checkpoint automatically. |
234
+
235
+ All `list/results` lookups read `output/models/SupervisedModelTraining/results/<task_id>/`.
236
+
237
+ ## Patterns for common modifications
238
+
239
+ ### Adding a new model
240
+
241
+ 1. Create a file at `examples/my_project/model.py`
242
+ 2. Inherit from `RecommenderModule`
243
+ 3. Implement `__init__(self, project_config, index_mapping, **kwargs)` and `forward()`
244
+ 4. `forward()` must return shape `[batch_size]` (`[batch_size, n_items]` for `ce` / `nll`)
245
+ 5. Pass extra params via `recommender_extra_params`
246
+
247
+ ### Adding a new dataset
248
+
249
+ 1. Create `examples/my_project/data.py` with a class inheriting `BasePrepareDataFrames`
250
+ 2. Implement: `requires()`, `dataset_dir`, `read_data_frame_path`
251
+ 3. Optional: `timestamp_property`, `metadata_data_frame_path`, `transform_data_frame()`
252
+ 4. Create `examples/my_project/config.py` with a `ProjectConfig`
253
+
254
+ ### Adding a new loss function
255
+
256
+ 1. Add the class to `src/mars_rec/torch/loss.py`
257
+ 2. Register it in the `TORCH_LOSS_FUNCTIONS` dictionary in `simulation/training.py`
258
+ 3. The loss must accept `(input, target)` and return a scalar
259
+
260
+ ### Adding a new metric
261
+
262
+ 1. Add the function to `src/mars_rec/torch/metrics.py`
263
+ 2. Register it in `METRIC_REGISTRY` (same file) — the registry key is the name used in the `metrics` list
264
+
265
+ ### Adding a new optimizer
266
+
267
+ 1. Add it to `src/mars_rec/torch/optimizer.py`
268
+ 2. Register it in the `TORCH_OPTIMIZERS` dictionary in `simulation/training.py`
269
+
270
+ ### Adding a sequence model (next-item prediction)
271
+
272
+ 1. Inherit from `RecommenderModule`; accept `*features` in `forward()` (positional unpacking of `ProjectConfig.input_columns`).
273
+ 2. Declare the history as an `IOType.INDEXABLE_ARRAY` column with `same_index_as` the item column (see `examples/lastfm/`).
274
+ 3. Return logits over the item vocabulary: `[batch_size, n_items]` and train with `--loss-function ce`.
275
+
276
+ ### Modifying the inference / evaluate pipeline
277
+
278
+ - `inference.py::run_inference` is the source of truth for batch top-k prediction. It loads `params.json` + `weights.ckpt` + `index_mapping.pkl`, preprocesses the input the same way training does, and writes `{top10s, user, time}` to JSON.
279
+ - `simulation/training.py::run_evaluate` re-builds a `SupervisedModelTraining` instance from `params.json`, points it to the existing task dir (`task._source_task_dir`), and runs the same `evaluate()` method as the original training. Two flows: original splits (`data_path=None`) or external dataset.
280
+ - Both write/refresh `metadata.json`, which is what `list` / `results` read for ranking + ROC-AUC metrics.
281
+
282
+ ## Documentation
283
+
284
+ The public docs live in `docs/` and are built with MkDocs Material + mkdocstrings (`make docs`, strict;
285
+ `make docs-serve` for live preview; install with `pip install -e ".[docs]"`). When you change
286
+ user-facing behavior (CLI options, training parameters, `ProjectConfig` fields, registries), update
287
+ the matching page under `docs/` in the same PR. The API reference is generated from docstrings, so keep
288
+ docstring parameters in sync with signatures — the strict build fails on mismatches. The example
289
+ tutorials include source files via `--8<--` snippets, so they never need manual syncing.
290
+ `CONTRIBUTING.md` is also included into the site (`docs/contributing.md`), so links in it must be absolute
291
+ GitHub URLs — a relative link such as `(AGENTS.md)` fails the strict build. Pushes to `main` publish to GitHub
292
+ Pages (https://marlesson.github.io/mars-rec/) while the `DOCS_DEPLOY` repository variable is `true`.
293
+
294
+ ## Critical files (modify with care)
295
+
296
+ | File | Risk | Reason |
297
+ |---|---|---|
298
+ | `simulation/training.py` | **High** | Full training pipeline + `run_evaluate`. ~2.4k lines. Changes can break the entire flow. |
299
+ | `meta_config.py` | **High** | Central contract. Changes affect all projects and the dataset/training. |
300
+ | `inference.py` | **High** | Standalone inference + evaluation. Must stay aligned with training's preprocessing/index_mapping. |
301
+ | `data/dataset.py` | **Medium** | Dataset classes used by every project. Changes to `__getitem__` affect training. |
302
+ | `data/task.py` | **Medium** | Data split and preparation. Changes alter how data is divided. |
303
+ | `utils/index_mapping.py` | **Medium** | Index mapping. Errors here cause embedding lookup failures. |
304
+ | `cli.py` | **Low** | Thin Click wrappers around `run_inference` / `run_evaluate` / Luigi. |
305
+
306
+ ## Global dictionaries in simulation/training.py
307
+
308
+ These dictionaries map configuration strings to Python classes:
309
+
310
+ ```python
311
+ TORCH_OPTIMIZERS = {
312
+ "adam": Adam, "adamw": AdamW, "sgd": SGD, "rmsprop": RMSprop,
313
+ "radam": RAdam, "adadelta": Adadelta, "adagrad": Adagrad, "adamax": Adamax
314
+ }
315
+
316
+ TORCH_LR_SCHEDULERS = {
317
+ "reduce_on_plateau": ReduceLROnPlateau, "cosine_annealing": CosineAnnealingLR,
318
+ "cosine_warm_restarts": CosineAnnealingWarmRestarts, "step": StepLR
319
+ }
320
+
321
+ TORCH_LOSS_FUNCTIONS = {
322
+ "bce": BCELoss, "mse": MSELoss, "nll": NLLLoss, "ce": CrossEntropyLoss,
323
+ "bce_logits": BCEWithLogitsLoss, "bce_logits_smooth": BCEWithLogitsLossSmooth,
324
+ "bpr": BPRLoss, "ranknet": RankNetLoss, "lambdarank": LambdaRankLoss,
325
+ "mlm": MultiLabelMarginLoss, "focal_loss": FocalLoss,
326
+ "implicit_feedback_bce": ImplicitFeedbackBCELoss, "dummy": DummyLoss,
327
+ # Embedding losses (EmbeddingRecommenderLightningModule):
328
+ "infonce": InfoNCELoss, "cosine_similarity": CosineSimilarityLoss, "hardneg_infonce": HardNegInfoNCELoss
329
+ }
330
+ # Losses that consume logits must also be listed in torch/lightning_module.py::_LOGIT_LOSSES.
331
+
332
+ TORCH_ACTIVATION_FUNCTIONS = {
333
+ "relu": F.relu, "selu": F.selu, "tanh": F.tanh, "sigmoid": F.sigmoid, "linear": F.linear
334
+ }
335
+
336
+ TORCH_WEIGHT_INIT = {
337
+ "lecun_normal": lecun_normal_init, "he": he_init, "xavier_normal": xavier_normal
338
+ }
339
+ ```
340
+
341
+ ## Environment variables
342
+
343
+ Read by the code:
344
+
345
+ | Variable | Default | Usage |
346
+ |---|---|---|
347
+ | `OUTPUT_PATH` | `"output"` (falls back to `AIP_MODEL_DIR`) | Root directory for all artifacts (`utils/files.py`) |
348
+ | `AIP_MODEL_DIR` | unset (Vertex AI sets it automatically) | GCS path for post-training upload; also a fallback for `OUTPUT_PATH` |
349
+ | `DATA_URI` | unset | Optional dataset source consumed by `entrypoint.sh` (`gs://`, `http(s)://`, or local path) |
350
+ | `DATASET_GCS_PREFIX` | unset | Optional GCS prefix (`gs://bucket/path/`) the entrypoint mirrors (rsync) into `OUTPUT_PATH/<project>/dataset/`. Used for offline-precomputed files (e.g. embedding pickles). |
351
+ | `PROJECT_NAME` | auto-detect from CLI `--project` | Forces the dataset target subdir used by `entrypoint.sh` (default: the package before `.config.` in `--project`). `EXPERIMENT_NAME` is a legacy alias. |
352
+ | `LUIGI_CONFIG_PATH` | auto (package's `luigi.cfg`) | Path to Luigi configuration; set by `cli.py` |
353
+ | `PYTHONPATH` | — | Must include the project root so `examples.*` (or your own project package) resolves |
354
+ | `PYTHONHASHSEED` | set at runtime to `seed` | Reproducibility (`training.py::seed_everything`) |
355
+
356
+ Read by the build / deploy tooling (`Makefile`, auto-loaded from `.env`):
357
+
358
+ | Variable | Default | Sensitivity | Usage |
359
+ |---|---|---|---|
360
+ | `GCP_PROJECT` | empty | **sensitive** | Artifact Registry / Cloud Build / Vertex AI project ID |
361
+ | `GCP_REGION` | `us-central1` | neutral | GCP region |
362
+ | `GCS_BUCKET` | empty | **sensitive** | Vertex AI artifact bucket (`gs://...`) |
363
+ | `IMAGE_NAME` / `IMAGE_TAG` | `mars-rec` / `latest` | neutral | Docker image identity |
364
+
365
+ `.env` is gitignored. Use `.env.example` as the template and never
366
+ commit `.env`, service-account JSON keys, `*.pem`, or `*.key`. The
367
+ GCP-touching `make` targets (`docker-push`, `docker-pull`,
368
+ `gcp-create-repo`, `gcp-submit`, `vertex-run`) error out cleanly when
369
+ `GCP_PROJECT` / `GCS_BUCKET` are missing.
370
+
371
+ ## Quick tests to validate changes
372
+
373
+ ```bash
374
+ # 1. Import test (checks for broken imports)
375
+ python -c "from mars_rec.simulation.training import SupervisedModelTraining; print('OK')"
376
+ python -c "from mars_rec.inference import run_inference, run_evaluate; print('OK')"
377
+
378
+ # 2. Unit tests (CI runs `make test-ci`: same suite + branch-coverage floor)
379
+ make test
380
+ make test-ci
381
+
382
+ # 3. End-to-end test with MovieLens 100K slate sample (small + fast)
383
+ PYTHONPATH=src:. python examples/movielens100k_slate/run_training.py
384
+
385
+ # 4. CLI test
386
+ mars-rec run supervised \
387
+ --project examples.movielens100k_slate.config.movielens100k_slate \
388
+ --recommender-module-class examples.movielens100k_slate.model.ML100KSlateRanker \
389
+ --recommender-extra-params '{"n_factors": 32, "genre_dim": 19, "hidden_size": 64}' \
390
+ --loss-function bce_logits --negative-proportion 0.5 --epochs 2 --device cpu
391
+
392
+ # 5. Query command tests
393
+ mars-rec list
394
+ mars-rec results --project movielens100k_slate --sort-by val_loss
395
+
396
+ # 6. Inference / re-evaluation
397
+ mars-rec predict --task-id <ID> --data data/test.parquet --output result.json
398
+ mars-rec evaluate --task-id <ID> --ranking-metrics --split test
399
+
400
+ # 7. Architecture diagram
401
+ # Each ``run supervised`` already drops ``architecture.svg`` (trace=True)
402
+ # next to the checkpoint. The CLI lets you regenerate or inspect:
403
+ mars-rec visualize --task-id <ID> # SVG (default), trace on
404
+ mars-rec visualize --task-id <ID> --no-trace # static introspection only
405
+ mars-rec visualize --task-id <ID> --output /tmp/arch.svg
406
+ mars-rec visualize --task-id <ID> --mode summary # text table
407
+ ```
408
+
409
+ ## Common errors and solutions
410
+
411
+ | Error | Cause | Solution |
412
+ |---|---|---|
413
+ | `RuntimeError: target size != input size` | `forward()` returns wrong shape for the chosen loss | BCE/MSE → `[batch]` (use `.squeeze(-1)`); CE → `[batch, n_items]` |
414
+ | `ModuleNotFoundError: No module named 'examples'` (or your project package) | PYTHONPATH doesn't include project root | Run from the project root or `PYTHONPATH=. python ...` |
415
+ | `Luigi task already DONE` | Output dir exists from a previous run | Use `--no-cache`, delete the output directory, or change a parameter (e.g. `--observation`) |
416
+ | `KeyError` in index_mapping | INDEXABLE column not found in DataFrame | Verify ProjectConfig column names match the CSV |
417
+ | `PermissionError` on cleanup | File locked by a previous process | Manually delete the output directory |
418
+ | `issubclass() arg 1 must be a class` | `load_attr` returned an instance instead of a class | `recommender_module_class` must point to the CLASS, not an instance |
419
+ | `FileNotFoundError: weights*.ckpt` in `predict`/`evaluate` | Task dir lacks a Lightning checkpoint | Re-train, or pass the correct `--task-id` / `--model-dir` |
420
+ | `metadata.json` missing in `results` | Run was trained without `--ranking-metrics` and never re-evaluated | Run `mars-rec evaluate --task-id <ID> --ranking-metrics` |
@@ -0,0 +1,163 @@
1
+ Metadata-Version: 2.5
2
+ Name: mars-rec
3
+ Version: 0.1.0
4
+ Summary: MARS-Rec: framework to model, train, and evaluate deep-learning recommendation systems (successor of MARS-Gym Lite).
5
+ Project-URL: Homepage, https://github.com/marlesson/mars-rec
6
+ Project-URL: Documentation, https://marlesson.github.io/mars-rec/
7
+ Project-URL: Source, https://github.com/marlesson/mars-rec
8
+ Project-URL: Issues, https://github.com/marlesson/mars-rec/issues
9
+ Author: MARS-Gym Authors
10
+ License: MIT
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Programming Language :: Python :: Implementation :: CPython
22
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
23
+ Requires-Python: >=3.11
24
+ Requires-Dist: certifi>=2024.2.2
25
+ Requires-Dist: click>=8.1
26
+ Requires-Dist: luigi<4,>=3.5
27
+ Requires-Dist: matplotlib>=3.8
28
+ Requires-Dist: numpy>=2.0
29
+ Requires-Dist: pandas>=2.2
30
+ Requires-Dist: pyarrow>=15
31
+ Requires-Dist: pytorch-lightning<3,>=2.4
32
+ Requires-Dist: scikit-learn>=1.5
33
+ Requires-Dist: scipy>=1.13
34
+ Requires-Dist: torch>=2.4
35
+ Requires-Dist: tqdm<5,>=4.65
36
+ Provides-Extra: dev
37
+ Requires-Dist: pytest-cov>=5; extra == 'dev'
38
+ Requires-Dist: pytest>=8; extra == 'dev'
39
+ Requires-Dist: ruff<0.18,>=0.17; extra == 'dev'
40
+ Provides-Extra: docs
41
+ Requires-Dist: mkdocs-click<0.10,>=0.9; extra == 'docs'
42
+ Requires-Dist: mkdocs-material<10,>=9.6; extra == 'docs'
43
+ Requires-Dist: mkdocs<2,>=1.6; extra == 'docs'
44
+ Requires-Dist: mkdocstrings[python]<2,>=1.0; extra == 'docs'
45
+ Provides-Extra: tensorboard
46
+ Requires-Dist: tensorboardx>=2.6; extra == 'tensorboard'
47
+ Description-Content-Type: text/markdown
48
+
49
+ # MARS-Rec
50
+
51
+ [![CI](https://github.com/marlesson/mars-rec/actions/workflows/ci.yml/badge.svg)](https://github.com/marlesson/mars-rec/actions/workflows/ci.yml)
52
+ [![Docs](https://github.com/marlesson/mars-rec/actions/workflows/docs.yml/badge.svg)](https://marlesson.github.io/mars-rec/)
53
+
54
+ **MARS-Rec** is a framework to model, train, and evaluate deep-learning recommendation systems.
55
+ It is the supervised-only successor of [MARS-Gym](https://github.com/deeplearningbrasil/mars-gym)
56
+ (formerly *MARS-Gym Lite*). All Reinforcement Learning, bandit, gym-environment and
57
+ policy-evaluation layers were removed, keeping a lean **data preparation → supervised training →
58
+ evaluation** pipeline built on Luigi, PyTorch and PyTorch Lightning.
59
+
60
+ 📖 **Documentation: <https://marlesson.github.io/mars-rec/>**
61
+
62
+ ## Features
63
+
64
+ - **Declarative projects**: a single `ProjectConfig` declares the columns, their types, the
65
+ data-prep task and the dataset class.
66
+ - **Reproducible pipelines**: Luigi caches every step by a hash of its parameters.
67
+ - **PyTorch Lightning training loop**: early stopping, checkpointing, CSV logging (TensorBoard optional),
68
+ LR schedulers and mixed precision.
69
+ - **Ranking metrics**: NDCG, HitRate, MRR and MAP @{5, 10, 20} plus ROC-AUC.
70
+ - **One CLI** (`mars-rec`): `run`, `list`, `results`, `predict`, `evaluate` and `visualize`.
71
+ - **Docker & Vertex AI**: the same image runs locally and on Google Cloud.
72
+
73
+ ## Installation
74
+
75
+ Python 3.11–3.13.
76
+
77
+ ```bash
78
+ pip install mars-rec
79
+ ```
80
+
81
+ From source (to run the bundled `examples/` or contribute):
82
+
83
+ ```bash
84
+ git clone https://github.com/marlesson/mars-rec.git
85
+ cd mars-rec
86
+ python -m venv .venv && source .venv/bin/activate
87
+ pip install -e . # or: make install-locked (pinned stack, as CI)
88
+ ```
89
+
90
+ ## Quickstart
91
+
92
+ ```bash
93
+ # Train the smallest bundled example (downloads MovieLens 100K on first run)
94
+ mars-rec run supervised \
95
+ --project examples.movielens100k_slate.config.movielens100k_slate \
96
+ --recommender-module-class examples.movielens100k_slate.model.ML100KSlateRanker \
97
+ --recommender-extra-params '{"n_factors": 32, "genre_dim": 19, "hidden_size": 64}' \
98
+ --loss-function bce_logits --epochs 8 --device cpu
99
+
100
+ # Compare runs, predict, re-evaluate
101
+ mars-rec results --project movielens100k_slate --sort-by val_loss
102
+ mars-rec predict --task-id <TASK_ID> --data data/test.parquet --top-k 10
103
+ mars-rec evaluate --task-id <TASK_ID> --ranking-metrics --split test
104
+ ```
105
+
106
+ A project has three parts: a data-prep task, a `ProjectConfig` and a model.
107
+
108
+ ```python
109
+ from mars_rec.meta_config import Column, IOType, ProjectConfig
110
+ from mars_rec.model.abstract import RecommenderModule
111
+
112
+ my_project = ProjectConfig(
113
+ base_dir="output/my_project",
114
+ prepare_data_frames_task=PrepareMyDataFrame, # a BasePrepareDataFrames subclass
115
+ dataset_class=InteractionsWithNegativeItemGenerationDataset,
116
+ user_column=Column("user_id", IOType.INDEXABLE),
117
+ item_column=Column("item_id", IOType.INDEXABLE),
118
+ other_input_columns=[Column("price", IOType.NUMBER)],
119
+ output_column=Column("purchased", IOType.NUMBER),
120
+ )
121
+
122
+ class MyModel(RecommenderModule):
123
+ def forward(self, user_ids, item_ids, price): # same order as the input columns
124
+ ... # → one score per row: [batch_size]
125
+ ```
126
+
127
+ For a step-by-step walkthrough, see
128
+ [Your first project](https://marlesson.github.io/mars-rec/tutorials/custom-project/).
129
+
130
+ ## Examples
131
+
132
+ | Example | Dataset | Feature it exercises |
133
+ |---|---|---|
134
+ | `movielens` | MovieLens 1M | NCF with user/genre side features |
135
+ | `lastfm` | HetRec Last.fm 2K | Sequential SASRec-lite (`INDEXABLE_ARRAY` + `same_index_as`) |
136
+ | `online_retail` | UCI Online Retail | Session-based GRU4Rec (`session_id` as user) |
137
+ | `amazon_beauty` | Amazon Beauty 5-core | Content-based two-tower (`metadata_columns` text embedding) |
138
+ | `movielens100k_slate` | MovieLens 100K | Slate ranking (`available_items` negatives) |
139
+
140
+ ```bash
141
+ PYTHONPATH=src:. python examples/<name>/run_training.py
142
+ ```
143
+
144
+ ## Documentation
145
+
146
+ | Section | Content |
147
+ |---|---|
148
+ | [Getting started](https://marlesson.github.io/mars-rec/getting-started/) | Installation and quickstart |
149
+ | [Concepts](https://marlesson.github.io/mars-rec/concepts/) | `ProjectConfig`, models, pipeline, index mapping, caching |
150
+ | [Tutorials](https://marlesson.github.io/mars-rec/tutorials/) | Building a project, and the five examples |
151
+ | [Guides](https://marlesson.github.io/mars-rec/guides/) | Training parameters, inference, extending, Docker & Vertex AI |
152
+ | [Reference](https://marlesson.github.io/mars-rec/reference/) | CLI and Python API |
153
+
154
+ To preview the docs locally: `pip install -e ".[docs]" && make docs-serve`.
155
+
156
+ ## Contributing
157
+
158
+ See [`CONTRIBUTING.md`](https://github.com/marlesson/mars-rec/blob/main/CONTRIBUTING.md) for the branch, lint and pull request workflow.
159
+ AI agents should also read [`AGENTS.md`](https://github.com/marlesson/mars-rec/blob/main/AGENTS.md).
160
+
161
+ ## License
162
+
163
+ MIT