rohitg00/ai-engineering-from-scratch · error · ValueError

weights length must match rankings length

Error message

weights length must match rankings length

What it means

rrf fuses several ranked lists with per-list weights; if the weights vector length differs from the number of rankings, weights would be misassigned to the wrong retriever, so the fused score would silently weight the wrong lists.

Solutions

  1. Omit weights to get uniform weighting ([1.0] per ranking is the default)
  2. Supply exactly one weight per ranking list, in the same order as `rankings`
  3. Build weights programmatically: weights = [w for _ in rankings]
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at phases/19-capstone-projects/65-hybrid-retrieval-bm25-dense/code/main.py:151 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of rohitg00/ai-engineering-from-scratch@39ea8a1c6d (2026-08-26). Data as JSON: /api/errors/0d891657c47c4dea. Report an issue: GitHub.

Appendix: source

Thrown at phases/19-capstone-projects/65-hybrid-retrieval-bm25-dense/code/main.py:151

        qv = mock_embed(query)
        scored = [(d, cosine(qv, v)) for d, v in self.vectors]
        scored.sort(key=lambda x: -x[1])
        return scored[:k]


# ---------------------------------------------------------------------------
# Reciprocal Rank Fusion
# ---------------------------------------------------------------------------

def rrf(
    rankings: list[list[tuple[Doc, float]]],
    k: int = 60,
    weights: list[float] | None = None,
) -> list[tuple[Doc, float]]:
    if weights is None:
        weights = [1.0] * len(rankings)
    if len(weights) != len(rankings):
        raise ValueError("weights length must match rankings length")
    score: dict[str, float] = defaultdict(float)
    by_id: dict[str, Doc] = {}
    for w, ranks in zip(weights, rankings):
        for rank, (doc, _) in enumerate(ranks):
            score[doc.doc_id] += w * (1.0 / (k + rank + 1))
            by_id[doc.doc_id] = doc
    fused = sorted(score.items(), key=lambda x: -x[1])
    return [(by_id[did], s) for did, s in fused]


# ---------------------------------------------------------------------------
# Hybrid retriever
# ---------------------------------------------------------------------------

@dataclass
class HybridRetriever:
    bm25: BM25Index = field(default_factory=BM25Index)
    dense: DenseIndex = field(default_factory=DenseIndex)

View on GitHub (pinned to 39ea8a1c6d)