Next-week purchase recommendation
Task type: RecommendationTask. Predict unique products purchased in [T, T + 7 days), including products purchased before T. This is not new-product acquisition and is not only the next basket. Repeated purchases are learned by BaseModel. Do not mask historical items or re-rank model output with a repeat rule.
Start with about 10% of customers to check the complete workflow. Then remove that customer limit and train on the full eligible population. Keep every buyer in the evaluation cohort, including buyers without history. For a buyer without history, use the top 12 items by purchase frequency strictly before T, with item-ID order to break ties. This cold-start fallback is not a reranker for customers with history.
Target contract
Use native existing split points for the head at every distinct basket timestamp. Request the same strategy for FM, but disclose the engine limit below. Events exactly at T belong to the future. With date-resolution retail events, a basket means all purchases on that day. Keep the full history before T; use only purchases in the half-open seven-day outcome window. Deduplicate target IDs, give each item weight 1, and do not subtract previously purchased items. A future window with no purchases has no positive recommendation target. This does not remove cold-start buyers from evaluation.
Save the target function and entry points below with your configured source paths. Validate the target against the foundation checkpoint before training the scenario. The settings below are explicit engine configuration.
If head initialization raises TargetFunctionValidationError: No valid target found or the stack trace names _get_target_sample, compare inherited FM settings with the effective reviewed head overrides before changing eligibility. The troubleshooting page explains the combined-settings retry and why it did not isolate a single cause. Preserve your declared population and horizon.
ENGINE LIMIT: requested FM basket origins
The configuration requests existing for both FM and head. This is not a claim that both stages consume exact basket timestamps. The FM task forces valid, an override in place since a 2025 refactor. Observed FM runs confirm the override, and the engine warns: "Foundation Model task only supports 'valid' sampling strategy. Setting strategy to 'valid'." A large split-point cap does not remove that override.
The FM sampler source uses consecutive-basket intervals: with n distinct basket timestamps it produces n - 1 interval candidates, not n exact basket origins. There is no first-basket candidate. One randomized point is drawn per interval, limited to the seven days before the next basket. This formula is source evidence, not a measured count of consumed examples. Do not infer an exact every-basket FM count from accepted YAML or a large cap. verify_target() probes the head's training origins, but the FM still forces valid; the verifier does not remove this FM sampling limit.
ENGINE LIMIT: exact every-basket FM training remains unmet on the observed path. Report this limit rather than calling interval sampling exact basket sampling. The head still uses native existing origins and assigns events exactly at T to the future. Its unique-item [T, T + 7 days) target, including repeat purchases, is unchanged. Measure accepted examples and optimizer updates for FM and head separately. Do not replace the native objective or add reranking to hide a sampling limit.
Training settings
This concrete public retail example uses the development week starting 2020-09-02. Adapt source paths and schema, not the target meaning. The development week is the temporal validation week; it is allowed to select the checkpoint. Never use a held-out test or confirm week to select a checkpoint.
Save as fm_config.yaml (source paths are relative to the container working directory):
data_sources:
- type: event
name: transactions
main_entity_column: customer_id
date_column:
name: t_dat
format: '%Y-%m-%d'
allowed_columns:
- article_id
- price
- sales_channel_id
column_type_overrides:
article_id: categoricalCompressed
sales_channel_id: categorical
joined_data_sources:
- name: articles
join_on:
- - article_id
- article_id
data_location:
database_type: parquet
connection_params:
path: ./data/transactions_train.parquet
cache_path: ./source-cache
config_overrides:
memory_limit: 32GB
table_name: transactions
- type: attribute
name: articles
allowed_columns:
- article_id
- catalogue_article_id
- product_type_no
- product_group_name
- department_no
- colour_group_code
- index_group_name
- detail_desc
column_type_overrides:
catalogue_article_id: categoricalCompressed
product_type_no: categorical
product_group_name: categorical
department_no: categorical
colour_group_code: categorical
index_group_name: categorical
detail_desc: text
data_location:
database_type: parquet
connection_params:
path: ./data/articles_catalogue_identity.parquet
cache_path: ./source-cache
config_overrides:
memory_limit: 32GB
table_name: articles
- type: main_entity_attribute
name: customers
main_entity_column: customer_id
allowed_columns:
- FN
- Active
- club_member_status
- fashion_news_frequency
- age
column_type_overrides:
FN: categorical
Active: categorical
club_member_status: categorical
fashion_news_frequency: categorical
age: decimal
data_location:
database_type: parquet
connection_params:
path: ./data/customers.parquet
cache_path: ./source-cache
config_overrides:
memory_limit: 32GB
table_name: customers
shared_entities:
- name: article
id_columns:
articles: article_id
transactions: article_id
columns:
- name: catalogue_article_id
sources:
articles: catalogue_article_id
data_params:
data_start_date: '2018-09-20 00:00:00'
target_sampling_strategy: existing
split_point_data_sources:
- transactions
maximum_splitpoints_per_entity: 1000000
minimum_splitpoint_date: null
dynamic_events_sampling: false
apply_event_count_weighting: false
apply_recency_based_weighting: true
ignore_entities_without_history: false
history_future_split_overrides:
split_point_inclusion_overrides:
transactions: future
split:
type: time
training:
start_date: '2018-09-20 00:00:00'
end_date: '2020-09-01 23:59:59'
validation:
start_date: '2020-09-02 00:00:00'
end_date: '2020-09-08 23:59:59'
data_loader_params:
batch_size: 512
num_workers: 4
training_params:
epochs: 5
learning_rate: 0.0001
The split-point budget is deliberately above the number of daily baskets in these event tables. The head's native existing sampler enumerates actual timestamps; the budget must not silently reduce them to the default 20 split points. The FM override described above is a separate limit, not solved by this budget. Use the largest budget that covers the observed basket counts and fits memory. If memory requires a smaller budget, state the reduction and measure accepted examples and updates per epoch for both FM and head. A fixed two-week training cohort is not an implementation of this recipe.
Use the same monad version for the foundation model and the head. Record it for both stages; do not load an FM trained with one monad version into a head trained with another for this recipe.
Preserve the default network and optimizer unless an actual measurement justifies a change. Do not substitute a larger model, Top-M loss, reranker, or learning-rate search for missing training exposure. Five epochs is an initial budget, not a promise that the final epoch is best. Remove reduced-batch limits after the small workflow succeeds. Record accepted examples, optimizer updates, completed epochs, validation curve, selected epoch and the resolved config. Keep per-epoch checkpoint selection: on the 10% sample, head validation peaked at epoch 1 (zero-based; the second completed epoch) and then declined. This is a single-run diagnostic, not a fixed epoch budget for other datasets.
Target and public training entry points
Save as train_recommendation.py beside fm_config.yaml. Create the catalogue identity file described below first. Run python train_recommendation.py inside the engine container. A fresh FM output directory is required.
from datetime import timedelta
from pathlib import Path
import numpy as np
from monad.batch import SPLIT_TIMESTAMP
from monad.config import MetricParams, TrainingParams
from monad.ui import pretrain
from monad.ui.module import RecommendationTask, load_from_foundation_model
from monad.ui.target_function import has_incomplete_training_window, sketch
def next_week_target(history, future, attributes, ctx):
horizon = timedelta(days=7)
if has_incomplete_training_window(ctx, horizon):
return None
window = future.interval_from(ctx[SPLIT_TIMESTAMP], horizon)["transactions"]
if window.count() == 0:
return None
items = window["article_id"]
# Repeated rows together contribute weight 1 per unique item.
_, inverse, counts = np.unique(items.events, return_inverse=True, return_counts=True)
return sketch(items, (1.0 / counts[inverse]).astype(np.float32))
pretrain(config_path=Path("fm_config.yaml"), output_path=Path("project/recommendation"))
trainer = load_from_foundation_model(
checkpoint_path=Path("project/recommendation/fm"),
downstream_task=RecommendationTask(),
target_fn=next_week_target,
target_sampling_strategy='existing',
split_point_data_sources=['transactions'],
maximum_splitpoints_per_entity=1000000,
minimum_splitpoint_date=None,
dynamic_events_sampling=False,
apply_recency_based_weighting=True,
ignore_entities_without_history=False,
history_future_split_overrides={'split_point_inclusion_overrides': {'transactions': 'future'}},
)
trainer.fit(TrainingParams(
checkpoint_dir=Path("project/recommendation/scenario"),
devices=[0],
epochs=5,
learning_rate=0.0001,
top_k=12,
metrics=[MetricParams(alias="map12", metric_name="MeanAveragePrecisionAtK", kwargs={"k": 12})],
metric_to_monitor="val_map12_0",
metric_monitoring_mode="max",
))
The loader validates the target when it initializes the scenario; inspect rejected examples before full training. top_k, output type and readout belong to testing/export, not extra fields on the foundation config. Use the documented testing API and sketch readout API for the export contract below. An external common-protocol evaluator is a separately supplied artifact, not a command delivered by this page.
Catalogue and item features
Prepare working Parquet copies with string item IDs on both sides of the join. The shared-entity connector filters empty strings, so an integer identity column fails during native fitting. Keep article_id in the article source's allowed_columns. Preserve leading zeros when reading raw CSV (dtype={"article_id": "string"}); casting an already numeric Parquet column cannot restore them.
from pathlib import Path
import pandas as pd
root = Path("data") # writable working copies, separate from raw inputs
articles = pd.read_parquet(root / "articles.parquet")
transactions = pd.read_parquet(root / "transactions_train.parquet")
for frame in (articles, transactions):
if frame["article_id"].isna().any():
raise ValueError("Article IDs must be present in both sources")
frame["article_id"] = frame["article_id"].astype("string")
articles["catalogue_article_id"] = articles["article_id"]
articles.to_parquet(root / "articles_catalogue_identity.parquet", index=False)
transactions.to_parquet(root / "transactions_train.parquet", index=False)
Create articles_catalogue_identity.parquet as above by adding catalogue_article_id = article_id. This preserves the full eligible catalogue independently of sampled transaction IDs. Fit item coordinates from training history only. Decode against the complete eligible item table, not only IDs observed in the sampled training customers. For public H&M this means all 105,542 articles. Keep the same code mapping for training and export. Include available categorical article attributes. The example explicitly uses detail_desc: text for the public descriptions when the installed native text feature is available. Item text is useful only if the installed feature engine supports its representation; public descriptive text is not evidence that an arbitrary text encoder exists. This configuration uses no item images or image embeddings. Do not add them. For comparison, report the full-input model and, when a comparison arm lacks text or attributes, also an explicitly labelled equal-input model. Keep the cohort, truth week, training-information cutoff, catalogue, metric and cold-start fallback identical. Judge the full-input model; the equal-input result explains the effect of its additional available inputs, not a different evaluation.
Validation, export and handover
See the 39-tip target design and training guide for the full contract and evidence checklist.
Use temporal validation and select the checkpoint by real, unmasked validation MAP@12 over the full catalogue after each epoch. Flag a curve that is zero or NO_TARGET for every epoch: checkpoint selection would be blind. Inspect the filter, truth and decode path, repair it and rerun validation before selecting a checkpoint; fixing only the final export does not repair selection.
Omit predictions_to_include_fn and predictions_to_exclude_fn when nothing is restricted. If a callback is required, return an explicit list wherever the restriction applies: a callback that returns None for an entity, including through a conditional branch or implicit fall-through, leaves that entity unrestricted. Ranking positions left without an eligible item are exported as NO_TARGET. Keep an independent full-catalogue key check.
Prefer OutputType.ENCODED export with an explicit readout_sketch readout against the full catalogue, then map the top 12 indices back to original item IDs. Record the code mapping and depth policy. Native DECODED (and its SEMANTIC ID mapping) averages across learned depths; fewer learned depths can increase score variance and over-represent items with random codes in top-k. An equal-quality synthetic diagnostic on monad dev measured about 1.7× their catalogue share. This is evidence of decoder bias, not a measured quality gain from ENCODED export. Validate the chosen readout on development data and report random-code item shares in the catalogue, truth and top-12 predictions.
Both validation and export require top_k >= 12. Evaluate every buyer with exactly 12 distinct item IDs and the metric denominator min(12, number of unique truth items). Report the unchanged common-protocol evaluator's result alongside baselines on exactly the same rows; an engine metric with a different denominator is not interchangeable.
For held-out origins, freeze all choices made on development data, including the selected epoch budget. Refresh training to the day before the requested origin. The neutral evaluator runs held-out weeks and seeds; do not inspect held-out truth to choose settings. Deliver the target, complete source config, training and export entry points, selected settings and cold-start rule together.