Run this notebook

Download it with the View page source link at the top right, or from the repository at docs/source/multimodal-concat-wrapper.ipynb.

Multimodal ContentRecommender and TEASER with MMConcatWrapper

MMConcatWrapper makes an existing matrix-based cold-start recommender consume a dictionary of modality embeddings. It validates the selected matrices, handles missing rows, optionally normalizes each modality, and concatenates them in a fixed order. The wrapped model still learns and scores in its usual way.

Here we use real DBbook interactions and pretrained MiniLM text and ViT image vectors from the SWAP multimodal dataset release. We train both ContentRecommender and TEASER, register unseen books from their embeddings, and measure cold-item recommendations. Neither raw-text embedding generation nor a GPU is needed.

This is a small API tutorial, not a reproduction of the paper’s results. We use support filtering and a new random item split, rather than DBbook’s official train/test protocol. Filtering uses the interaction dataset before splitting; this is not a temporal or prospective evaluation.

Install the package from the checkout containing the wrapper with pip install -e ".[docs]", then select that environment as the notebook kernel. The first run downloads the DBbook interaction archive and roughly 348 MB of multimodal JSON data. Subsequent runs reuse the cache. Run from the repository root to reuse its data/ directory, or use any writable working directory.

[1]:
from pathlib import Path
from time import perf_counter

import numpy as np
import pandas as pd
from IPython.display import display

import compresso_recsys as cr
from compresso_recsys.evaluation import evaluate_recommender
from compresso_recsys.metrics import CalibratedRecall, NDCG
from compresso_recsys.models import (
    ContentRecommender, ContentRecommenderConfig,
    MMConcatWrapper, MMConcatWrapperConfig,
    TEASER, TEASERConfig,
)

OUTPUT_DIR = Path("artifacts/tutorials")
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
checkpoint = OUTPUT_DIR / "mm-concat-dbbook.zip"

Load aligned embeddings and explicit availability masks

We use split_mode="item_split" with the builder’s default filtering, split fractions, and random seed for DBbook. The validation partition is unused here; model settings are fixed without test-set tuning. Delete the cached checkpoint if you change the preparation settings.

Each loaded modality is aligned by stable item ID. The available vector tells us which rows have embeddings; a zero vector by itself does not imply missingness.

[2]:
if not checkpoint.exists():
    cr.build_recsys_checkpoint(
        dataset="dbbook",
        data_dir="data",
        checkpoint_path=str(checkpoint),
        split_mode="item_split",
        multimodal_features=["text/minilm", "image/vit_cls"],
        show_progress=True,
    )

with cr.read_checkpoint(checkpoint) as root:
    split = cr.load_recsys_split(root)
    item_ids = split["item_ids"]
    loaded = {
        "text": cr.load_item_embeddings(root, "text/minilm", item_ids=item_ids),
        "image": cr.load_item_embeddings(root, "image/vit_cls", item_ids=item_ids),
    }

features = {name: value["embeddings"] for name, value in loaded.items()}
available = {name: value["available"] for name, value in loaded.items()}
warm = split["warm_item_indices"]
cold = split["test_cold_item_indices"]
x_train = split["x_train"][:, warm].tocsr()
test_source = split["test_source_matrix"][:, warm].tocsr()
test_targets = split["test_target_matrix"][:, cold].tocsr()
[3]:
warm_ids, cold_ids = item_ids[warm], item_ids[cold]
warm_features = {name: matrix[warm] for name, matrix in features.items()}
cold_features = {name: matrix[cold] for name, matrix in features.items()}
warm_masks = {name: mask[warm] for name, mask in available.items()}
cold_masks = {name: mask[cold] for name, mask in available.items()}

assert set(warm_ids).isdisjoint(cold_ids)
assert x_train.shape[1] == len(warm_ids)
assert test_source.shape[0] == test_targets.shape[0]
assert len(cold_ids) >= 20

display(pd.DataFrame([
    {
        "modality": name,
        "dimensions": matrix.shape[1],
        "warm items available": int(warm_masks[name].sum()),
        "warm items total": len(warm),
        "cold items available": int(cold_masks[name].sum()),
        "cold items total": len(cold),
    }
    for name, matrix in features.items()
]).set_index("modality"))
print(f"Training: {x_train.shape[0]:,} users, {x_train.shape[1]:,} warm items, {x_train.nnz:,} interactions")
print(f"Evaluation: {test_source.shape[0]:,} histories, {test_targets.shape[1]:,} cold candidates")
dimensions warm items available warm items total cold items available cold items total
modality
text 384 4863 5557 558 654
image 768 5353 5557 624 654
Training: 5,883 users, 5,557 warm items, 62,110 interactions
Evaluation: 3,974 histories, 654 cold candidates

The same wrapper, two different fit signatures

ContentRecommender.fit receives features alone. TEASER.fit receives interactions and features. The wrapper binds each inner signature and replaces only its feature argument. Positional and keyword calls both work; other arguments pass through unchanged. A custom model naming that argument embeddings can set fit_features_parameter="embeddings" in the wrapper config. For an opaque fit(*args, **kwargs), supply it by the configured keyword.

We choose missing="mean" and normalize=True: unavailable rows receive the mean of available training rows in that modality, then each modality is L2 normalized before concatenation. Only warm features enter these fits, so cold items cannot influence imputation statistics. When fitting a full catalog instead, use feature_fit_indices=warm; a forwarded train_item_indices is also recognized.

The configured order is always text, image, regardless of dictionary order. Default block weights are one. Set weights={"text": 1.0, "image": 0.5} to scale the image block; these are feature multipliers, not guaranteed score contributions.

[4]:
content_rec = MMConcatWrapper(MMConcatWrapperConfig(
    model=ContentRecommender,
    model_config=ContentRecommenderConfig(normalize=True, device="cpu"),
    modalities=["text", "image"],
    missing="mean",
    normalize=True,
))
started = perf_counter()
content_rec.fit(warm_features, item_ids=warm_ids, modality_masks=warm_masks)
content_fit_seconds = perf_counter() - started

teaser_rec = MMConcatWrapper(MMConcatWrapperConfig(
    model=TEASER,
    model_config=TEASERConfig(
        l2_coefficients=0.05,
        l2_encoder=0.05,
        rho=0.05,
        max_iterations=10,
    ),
    modalities=["text", "image"],
    missing="mean",
    normalize=True,
))
started = perf_counter()
teaser_rec.fit(
    x_train, item_features=warm_features,
    item_ids=warm_ids, modality_masks=warm_masks
)
teaser_fit_seconds = perf_counter() - started

print("Input widths:", dict(teaser_rec.feature_dims_))
print("Concatenated width:", teaser_rec.transform_features(warm_features, modality_masks=warm_masks).shape[1])
print("Inner models:", type(content_rec.inner_model).__name__, "and", type(teaser_rec.inner_model).__name__)
Input widths: {'text': 384, 'image': 768}
Concatenated width: 1152
Inner models: ContentRecommender and TEASER

Register cold candidates without refitting

build_candidates replaces the recommendation catalog with the held-out books. The wrapper applies the same fitted imputation and normalization and passes the resulting matrix to the inner model’s candidate method. The inner model owns the only stored catalog, including any model-specific transformation it performs.

Histories keep their warm-item columns; targets use the cold-candidate columns. New candidates become recommendable immediately, but do not become valid history items. Removing an item from the candidate catalog likewise does not remove its fitted history representation. Catalog publication guarantees are inherited from the inner model; a whole multi-batch prediction is not pinned to one version.

[5]:
for model in (content_rec, teaser_rec):
    model.build_candidates(
        item_ids=cold_ids,
        item_features=cold_features,
        modality_masks=cold_masks,
    )
    np.testing.assert_array_equal(model.source_item_ids, warm_ids)
    np.testing.assert_array_equal(model.candidate_item_ids, cold_ids)

batch = teaser_rec.predict_on_batch(test_source[:2], k=5)
batched = teaser_rec.predict(test_source[:2], k=5, batch_size=1)
np.testing.assert_array_equal(batch.cols.numpy(), batched.cols.numpy())

history = warm_ids[test_source[0].indices].tolist()
recommendations = teaser_rec.recommend([history], k=5)
display(pd.DataFrame({
    "rank": np.arange(1, 6),
    "recommended cold book ID": recommendations.item_ids[0],
    "score": recommendations.scores[0],
}))
rank recommended cold book ID score
0 1 4076 0.090634
1 2 5464 0.064508
2 3 4823 0.057424
3 4 7042 0.055381
4 5 3189 0.052498

Compare individual modalities with their concatenation

All six models see the same training interactions (where needed), histories, candidate IDs, and relevance labels. The two single-modality variants select one key from the same dictionary. We set extra_modalities="ignore" explicitly so unused keys in both feature and availability-mask dictionaries are ignored. The default, extra_modalities="error", rejects unknown keys to catch typos before they can silently trigger imputation or change fitted means. Both model families keep their settings fixed across feature choices. The table reports NDCG@20 and calibrated recall@20 on cold candidates only, plus observed fitting time.

Concatenation makes a model multimodal; it does not guarantee better ranking. The results describe this filtered split and these untuned settings, not a general comparison of the models or modalities. Fitting time depends on hardware.

[6]:
models = {"Content / text + image": content_rec, "TEASER / text + image": teaser_rec}
fit_seconds = {"Content / text + image": content_fit_seconds, "TEASER / text + image": teaser_fit_seconds}

for family, model_class, model_config in [
    ("Content", ContentRecommender, content_rec.cfg.model_config),
    ("TEASER", TEASER, teaser_rec.cfg.model_config),
]:
    for modality in ["text", "image"]:
        model = MMConcatWrapper(MMConcatWrapperConfig(
            model=model_class, model_config=model_config,
            modalities=[modality], missing="mean", normalize=True,
            extra_modalities="ignore",
        ))
        started = perf_counter()
        args = () if model_class is ContentRecommender else (x_train,)
        model.fit(*args, item_features=warm_features, item_ids=warm_ids, modality_masks=warm_masks)
        label = f"{family} / {modality}"
        fit_seconds[label] = perf_counter() - started
        model.build_candidates(item_ids=cold_ids, item_features=cold_features, modality_masks=cold_masks)
        models[label] = model

rows = []
for label, model in models.items():
    result = evaluate_recommender(
        model, source=test_source, targets=test_targets,
        metrics=[NDCG(20), CalibratedRecall(20)],
        batch_size=256, show_progress=True,
    )
    rows.append({"model": label, **result.metrics, "users scored": result.n_scored_rows, "fit seconds": fit_seconds[label]})

results = pd.DataFrame(rows).set_index("model").sort_index()
display(results.round(4))
ndcg@20 calibrated_recall@20 users scored fit seconds
model
Content / image 0.0107 0.0227 3974 0.0548
Content / text 0.0083 0.0127 3974 0.0263
Content / text + image 0.0102 0.0206 3974 0.1014
TEASER / image 0.0490 0.0894 3974 14.9155
TEASER / text 0.1279 0.1951 3974 11.6066
TEASER / text + image 0.1058 0.1735 3974 18.1052

Save the complete wrapper and update candidates later

Saving includes modality order and widths, preprocessing settings and learned means, and the inner model’s checkpoint. Loading restores the current candidate catalog as well as the fixed history vocabulary. Built-in cold-start models load directly. For a custom model, call MMConcatWrapper.register_model(MyModel) in a fresh process before loading; checkpoints never dynamically import model classes.

Below we reload TEASER and replace one existing candidate using only its image embedding. Since its text width and training mean are known, missing="mean" can fill the entire omitted text modality. missing="zero" would use zeros; the default missing="error" would reject this call. All selected modalities must be present at initial fit to establish their dimensions.

[7]:
model_path = OUTPUT_DIR / "mm-concat-teaser.zip"
teaser_rec.save(model_path)
restored = MMConcatWrapper.load(model_path)
before = teaser_rec.predict_on_batch(test_source[:2], k=5)
after = restored.predict_on_batch(test_source[:2], k=5)
np.testing.assert_array_equal(before.cols.numpy(), after.cols.numpy())
np.testing.assert_allclose(before.vals.numpy(), after.vals.numpy())

restored.update_candidates(
    item_ids=cold_ids[:1],
    item_features={"image": cold_features["image"][:1]},
    modality_masks={"image": cold_masks["image"][:1]},
    on_conflict="replace",
)
np.testing.assert_array_equal(restored.source_item_ids, warm_ids)
print("Reloaded predictions match. Candidate replacement reuses the fitted text mean.")
Reloaded predictions match. Candidate replacement reuses the fitted text mean.

For custom fusion architectures, use BaseMultiModalRecommender directly and define fitting, scoring, and any representation-specific candidate operations. MMConcatWrapper is the simpler choice when an existing matrix model and feature concatenation are the desired architecture.

Dataset references: SWAP dataset release, dataset repository, and resource paper.

[ ]:

[ ]:

[ ]: