RECOMMENDATION / NOTEBOOK LESSON

10 · System improvement and engineering experiments

Study retrieval quotas, distillation, drift, and the limits of social simulations.

Real data + mechanism / simulationRead-only · saved experiment

Saved outputs come from recorded teaching runs; opening this page does not rerun an experiment. The code and original outputs are preserved; original-language data and annotations may remain.

System improvement and engineering experiments

Goal

Turn concepts into inspectable inputs, operations, gradients, and comparisons.

Evidence: real snapshots + controlled drift/social simulation. Local teaching parameters are not production defaults; mechanism experiments are not full reproductions of the original papers.

English companion. All instructional Markdown is translated. Experiment code, Chinese language examples, execution counts, and saved outputs remain as in the source edition; historical output text may therefore be Chinese. The initial setup cell anchors the working directory and Python import path for this companion's deeper folder; it does not change the experiment. Saved outputs are historical evidence, not a new run. Run from the top after preparing the required data and models.

PYTHON · 01
# English companions live one directory deeper; keep the original experiment code unchanged.
from pathlib import Path as _TranslationPath
import os as _translation_os
import sys as _translation_sys
_translation_root = next((p for p in [_TranslationPath.cwd(), *_TranslationPath.cwd().parents]
                          if (p / "reclab").is_dir()), None)
if _translation_root is None:
    raise RuntimeError("Open this notebook from inside the Search Recommendation Ads Lab checkout.")
_translation_os.chdir(_translation_root)
if str(_translation_root) not in _translation_sys.path:
    _translation_sys.path.insert(0, str(_translation_root))

Setup

On the first pass, run from Setup in order: later cells reuse earlier variables. Then change one parameter and rerun that cell and its downstream cells. Constructed data does not establish real business impact.

PYTHON · 02
from pathlib import Path
import sys
import inspect
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from IPython.display import display, Code

PROJECT = next(p for p in [Path.cwd(), *Path.cwd().parents]
               if (p / "reclab/models.py").exists())
if str(PROJECT) not in sys.path:
    sys.path.insert(0, str(PROJECT))
from reclab.data import Dataset
from reclab.paths import ARTIFACTS, PROCESSED, read_json

plt.rcParams.update({"figure.figsize": (9, 3.8), "font.size": 11,
    "axes.spines.top": False, "axes.spines.right": False,
    "axes.labelcolor": "#182b2b", "text.color": "#182b2b",
    "axes.facecolor": "white", "figure.facecolor": "white",
    "grid.color": "#d4ddda", "axes.axisbelow": True})
dataset = Dataset()
print("Project:", PROJECT)
print("Dataset version:", dataset.manifest["dataset_version"])
print("Python:", sys.executable)
assert Path(sys.executable).parent == PROJECT / ".venv/bin", "请选择 Recommendation Lab 内核"
Saved notebook output · not executed on this page
Project: /Users/lizuolin/local/recommendation-lab
Dataset version: 2772cab0aca8cb81
Python: /Users/lizuolin/local/recommendation-lab/.venv/bin/python

Steps

Lecture references: 08_Improvement_01.pdf, 08_Improvement_02.pdf, 08_Improvement_03.pdf, 08_Improvement_04.pdf, 08_Improvement_05.pdf, 08_Improvement_06.pdf

Retrieval quotas and deduplication

Popular, ItemCF, and two-tower candidates come from real training snapshots. The sum of per-channel counts is not the number after deduplication.

Predict first: With a fixed total budget, which quality, coverage, and latency metrics should you inspect while adjusting quotas?

PYTHON · 03
from scipy import sparse
from reclab.retrieval import cf_scores,topk
from reclab.train import load_model,model_scorer
user=next(iter(dataset.histories));sim=sparse.load_npz(ARTIFACTS/"baselines/itemcf.npz")
model,report=load_model(dataset,"baseline-history32");scorer,_=model_scorer(dataset,model)
channels={"popular":topk(dataset.popularity,100,dataset.seen[user]),
    "itemcf":topk(cf_scores(sim,dataset.histories[user],dataset.n_items),100,dataset.seen[user]),
    "tower":topk(scorer(user),100,dataset.seen[user])}
display(pd.DataFrame([{"per_channel":n,"sum_before":3*n,
    "unique_after":len(set().union(*(set(ids[:n]) for ids in channels.values())))} for n in [10,30,100]]))
Saved notebook output · not executed on this page
per_channel sum_before unique_after
0 10 30 30
1 30 90 90
2 100 300 295

Distillation from ranking to pre-ranking

Controlled teacher/student scores check KL direction and gradients; no complete ranking teacher is claimed.

Predict first: If the teacher is poor, is fitting it more closely necessarily better?

PYTHON · 04
import torch
from reclab.learning.systems import distillation_loss
torch.manual_seed(42);torch.set_num_threads(4)
teacher=torch.randn(8,20);student=torch.nn.Parameter(torch.zeros(8,20))
opt=torch.optim.Adam([student],lr=.15);curve=[]
for _ in range(70):
    opt.zero_grad();loss=distillation_loss(student,teacher,2.)
    loss.backward();opt.step();curve.append(float(loss.detach()))
assert curve[-1]<curve[0]
plt.plot(curve,color="#006e60");plt.xlabel("Step");plt.ylabel("Listwise KL distillation loss");plt.ylim(bottom=0);plt.show()
Saved notebook output · not executed on this page
<Figure size 900x380 with 1 Axes>
Saved notebook figure

Full retraining, incremental training, and distribution drift

Change a controlled binary-classification rule to compare continued training with restarting. Training accuracy is not generalization or evidence of online benefits from a long-lived model.

Predict first: How much old data should remain to balance forgetting against adaptation to the new distribution?

PYTHON · 05
torch.manual_seed(42)
x=torch.randn(512,4);old_y=(x[:,0]+x[:,1]>0).float();new_y=(-x[:,0]+x[:,1]>0).float()
def fit(net,label,steps):
    optimizer=torch.optim.SGD(net.parameters(),lr=.2)
    for _ in range(steps):
        optimizer.zero_grad();loss=torch.nn.functional.binary_cross_entropy_with_logits(net(x).squeeze(-1),label)
        loss.backward();optimizer.step()
    return net
old=fit(torch.nn.Linear(4,1),old_y,80)
import copy
incremental=fit(copy.deepcopy(old),new_y,20);fresh=fit(torch.nn.Linear(4,1),new_y,20)
display(pd.DataFrame([{"model":name,"new_distribution_training_accuracy":float(((net(x).squeeze(-1)>0)==new_y.bool()).float().mean())}
    for name,net in [("old",old),("incremental20",incremental),("fresh20",fresh)]]))
Saved notebook output · not executed on this page
model new_distribution_training_accuracy
0 old 0.533203
1 incremental20 0.710938
2 fresh20 0.919922

User segments, diversity, exploration, and social signals

Segment users by training-period activity. Follow, creator, and external-return fields are absent; social relations use an explicitly constructed dictionary. Static logs cannot establish long-term gains from an exploration rate.

Predict first: Why should next week's activity never be used to segment today's users?

PYTHON · 06
activity=pd.Series({u:len(h) for u,h in dataset.histories.items()})
groups=pd.cut(activity,bins=[0,10,50,np.inf],labels=["low","medium","high"])
display(groups.value_counts(sort=False).to_frame("training-defined users"))
synthetic_follows={"u1":{"authorA","authorB"}}
synthetic_items={"authorA":["i1","i2"],"authorB":["i3"]}
social={i for author in synthetic_follows["u1"] for i in synthetic_items[author]}
assert social=={"i1","i2","i3"}
print("Synthetic U2A2I:",sorted(social))
print("MMR/diversity experiments: chapter 08. Exploration 2% is a hypothesis, not a universal default.")
Saved notebook output · not executed on this page
training-defined users
low 3843
medium 2643
high 248
Synthetic U2A2I: ['i1', 'i2', 'i3']
MMR/diversity experiments: chapter 08. Exploration 2% is a hypothesis, not a universal default.

Checks

Every assertion and output is traceable to code. They check operators, data snapshots, or mechanisms, not online gains.

Next steps

Record your prediction, change only one variable, and run the relevant experiment cell. Open reclab/learning/ to inspect helper functions.

GO TO THE SOURCE

Sources for this lesson

Author courseChinese

Shusen Wang · Recommender Systems

Corresponding author-course module; see individual lecture links below

45 lecture references mapped to practice. An exercise on a topic is not a complete paper reproduction. Originals retain their language and authors’ rights.

Author courseChinese

Other retrieval channels

02_Retrieval_11.pdf · 16 pages

A mechanism is readable; the real business task needs additional data and labels.

Author courseChinese

Improving metrics: overview

08_Improvement_01.pdf · 7 pages

Partial method or mechanism exercise; full pipelines and scale are not covered.

Author courseChinese

Retrieval improvements

08_Improvement_02.pdf · 20 pages

Partial method or mechanism exercise; full pipelines and scale are not covered.

Author courseChinese

Ranking-model improvements

08_Improvement_03.pdf · 35 pages

A related teaching mechanism is readable; the full method in the lecture remains an advanced objective.

Author courseChinese

Diversity and exploration

08_Improvement_04.pdf · 15 pages

Partial method or mechanism exercise; full pipelines and scale are not covered.

Author courseChinese

Special user segments

08_Improvement_05.pdf · 23 pages

A related teaching mechanism is readable; the full method in the lecture remains an advanced objective.

Author courseChinese

Interactions and social value

08_Improvement_06.pdf · 24 pages

A mechanism is readable; the real business task needs additional data and labels.

Completion marks are optional and stored only in this browser. Reading a page does not mark it complete.