Sub topic 8
Re-ranking for diversity and variety
This chapter assumes you have read the earlier chapters on scoring. You should know that each candidate post gets a single number from predicted reactions and a freshness decay. You should also be able to read short Python functions and know what a list sort does.
Why score order is not enough
Sorting by score gives the order that is best for each post taken alone. A feed is a sequence that a person reads from top to bottom, so posts affect each other. Three problems show up when you ship the raw sorted list:
- Runs from one source. An active author with a loyal audience can have five posts in the top ten. Each post scores well because the reader likes that author, so the feed becomes one author's page.
- Repeated formats or topics. Ten short videos in a row, or ten posts about the same news event, feel monotonous even when each is good.
- Near-duplicates. Several people share the same link or meme. The model scores each copy about equally, so the copies cluster together.
The score model rarely fixes this itself. It predicts reactions to one post and usually does not know what sits just above it. Re-ranking is a separate stage after scoring that looks at the list as a whole and applies rules about order.
Where re-ranking sits
Re-ranking takes the scored, filtered list and produces the final order. It does not change what is eligible. Integrity filters have already removed or demoted posts, and re-ranking only reorders what is left.
Re-ranking is cheap because it only touches the top few hundred posts, not millions. That means it can use rules that would be too slow to compute for every candidate, such as "look at the last three items already placed".
Common kinds of rules
Platforms use some mix of the rules below. The values here are illustrative.
| Rule | What it prevents | Typical form |
|---|---|---|
| Author spacing | One author filling the screen | No more than 2 posts in a row from one author |
| Author cap | One author dominating a session | At most 3 posts per author per page |
| Format mixing | Ten videos or ten text posts in a row | Penalty when the previous items share a format |
| Topic spreading | Many posts on one subject | Penalty based on similarity to items already placed |
| Duplicate removal | The same link or image repeated | Keep the highest-scoring copy, drop or push down the rest |
| Source mixing | Only friends, or only recommended accounts | Alternate between sources at a target ratio |
These rules fall into two styles. A hard constraint forbids an arrangement outright, such as three in a row from one author. A soft penalty lowers a post's score by an amount that grows with how much it resembles what is already placed. Hard constraints are easy to explain and test. Soft penalties degrade gracefully and let a very strong post still win.
A greedy re-ranker with a hard constraint
Most re-rankers are greedy. They build the list one position at a time and choose the best allowed post for the next slot. They never go back and revise earlier slots. This version enforces author spacing.
from dataclasses import dataclass
@dataclass
class Post:
id: str
author: str
score: float
def rerank(posts, max_run=2):
"""Order by score, but never place more than max_run posts in a row from one author."""
remaining = sorted(posts, key=lambda p: p.score, reverse=True)
result = []
while remaining:
recent = [q.author for q in result[-max_run:]]
for i, p in enumerate(remaining):
blocked = len(recent) == max_run and all(a == p.author for a in recent)
if not blocked:
result.append(remaining.pop(i))
break
else:
# Every remaining post would break the rule, so take the best one.
result.append(remaining.pop(0))
return result
posts = [
Post("a1", "ana", 0.90),
Post("a2", "ana", 0.85),
Post("a3", "ana", 0.80),
Post("b1", "ben", 0.60),
Post("c1", "cy", 0.50),
Post("a4", "ana", 0.40),
]
print([p.id for p in rerank(posts)])The output is ['a1', 'a2', 'b1', 'a3', 'c1', 'a4'].
Here is how it unfolds:
- The sorted order is a1, a2, a3, b1, c1, a4. Slot 1 takes a1 and slot 2 takes a2, because fewer than two posts are placed before each.
- For slot 3, the last two placed posts are both from Ana. The best remaining post, a3, is also Ana's, so it is blocked. The loop moves on and finds b1, which is allowed.
- For slot 4, the last two authors are Ana and Ben. They differ, so a3 is no longer blocked and is placed.
- The rest follow without conflict.
The for ... else clause matters. It runs only when the loop finished without a break, which means every remaining post was blocked. In that case the function takes the best one anyway. Without this fallback, the loop would never end or would drop posts when the pool is dominated by one author.
A soft penalty alternative
A soft penalty avoids the all-or-nothing behavior. Each time an author appears, that author's later posts have their scores multiplied by a factor below 1.
def rerank_penalty(posts, penalty=0.7):
"""Pick the best post at each step after discounting authors already placed."""
remaining = list(posts)
result = []
seen = {}
while remaining:
best = max(
remaining,
key=lambda p: p.score * (penalty ** seen.get(p.author, 0)),
)
remaining.remove(best)
result.append(best)
seen[best.author] = seen.get(best.author, 0) + 1
return result
print([p.id for p in rerank_penalty(posts)])On the same six posts this prints ['a1', 'b1', 'a2', 'c1', 'a3', 'a4']. The soft version spreads Ana's posts more than the hard rule did. At step 2, a2 has a discounted score of 0.85 × 0.7 = 0.595, which is lower than Ben's 0.60, so Ben moves up.
Note one difference. The hard rule looks only at the last max_run slots, so Ana can return after one gap. The penalty counts every earlier post by that author in the whole list. Choose the one that matches the experience you want, and name it clearly in code and documentation.
Edge cases and common errors
Small or lopsided pools. If most candidates come from one author, the rule has nothing to alternate with. Always define a fallback. Falling back to the best remaining post keeps the feed full. Leaving a slot empty makes the feed shorter, which is usually worse.
Pagination. Feeds load in pages. If you re-rank each page on its own, the first post of page two can repeat the author who ended page one. Pass the tail of the previous page, or the recent author history, into the next call as starting state.
Constraints that fight each other. An author cap, a format rule, and a topic rule can all block the same post. Greedy search then picks whatever survives, and the result depends on the order in which you check the rules. Decide an explicit priority, and test the combination, not only each rule alone.
Rules that undo the score. A strong penalty can push a very relevant post far down the list. Keep penalties modest, or let a hard rule apply only above a score threshold. Measure how far posts move: if the median post shifts by many positions, the rules are overriding the model rather than adjusting it.
Cost of the greedy loop. The soft version rescans all remaining posts at every step, so it takes time proportional to the square of the list size. That is fine for a few hundred posts. If the list grows into the thousands, restrict re-ranking to the top slice.
Interaction with exploration. Slots reserved for less-seen content are often applied after re-ranking. Then they can break a spacing rule. Either run the diversity check again after inserting them, or reserve the slots before re-ranking and treat them as fixed positions.
Trade-offs
Diversity rules usually cost a little short-term engagement, because they demote posts that the model predicts a person would react to. Platforms accept this for reasons that appear in other chapters. A varied feed tends to keep people returning, makes room for new authors, and reduces the sense that the feed is repetitive. Whether the trade is worth it is an empirical question. Teams answer it with experiments that compare retention and satisfaction, not only likes.
Summary
- Scoring ranks posts one at a time. Re-ranking fixes problems that only appear when the posts are seen as a sequence.
- Hard constraints forbid arrangements and are easy to test. Soft penalties reduce scores and fail more gently.
- A greedy pass picks the best allowed post for each slot and needs a fallback for when every post is blocked.
- Pagination, rule conflicts, and exploration slots are the most common sources of bugs.
Exercise
Using the first rerank function with max_run=1, what order do you get for the posts a1 (ana, 0.9), b1 (ben, 0.8), a2 (ana, 0.7), c1 (cy, 0.6)? Then explain what happens if the input is only three posts from ana.
Show answer
Sorted order is a1, b1, a2, c1. Slot 1 takes a1. For slot 2, the last author is ana, but the best remaining post is b1 (ben), which is allowed, so b1 is placed. For slot 3, the last author is ben, so a2 is allowed. Slot 4 takes c1. The result is a1, b1, a2, c1. With three posts only from ana and max_run=1, every remaining post is blocked at slots 2 and 3, so the for-else fallback takes the best remaining post each time and the output is the original score order.
Exercise
In rerank_penalty, a platform wants a strong post from an author already shown twice to still appear early if it is much better than the alternatives. Which parameter would you change, and in which direction? What is the risk?
Show answer
Raise penalty toward 1.0, for example from 0.7 to 0.85, so repeat authors lose less score and a strong post can still win. The risk is that the feed drifts back to the raw score order and loses variety. A penalty of 1.0 disables the rule entirely.
Exercise
A feed loads 10 posts per page and re-ranks each page alone with max_run=2. Describe a bug this can cause and one way to fix it.
Show answer
The last two posts of page one can both be from one author, and the first post of page two can be from the same author, producing a run of three across the page boundary. Fix it by passing the author history of the previous page's tail into the next re-ranking call, so the recent list starts with those authors.