KatInterview

Decode Non-Overlapping Keyphrase Spans from BERT Logits

Greedy & IntervalsModel answer
MediumModel answerGreedy & Intervalsstringsgreedy-intervalsmachine-learning

Last updated

Implement a decoder that converts token start and end logits into non-overlapping character spans using offset mappings and greedy selection.

You are building an entity and keyphrase extraction system for unstructured textual notes. Your underlying model is a BERT-style span extractor that predicts two raw logits for every input token: a start_logit (indicating how likely the token is to begin a keyphrase) and an end_logit (indicating how likely it is to terminate a keyphrase).

Your objective is to write the post-processing decoder function extract_keyphrases. This function takes the raw model outputs and Hugging Face-style offset_mapping tuples and extracts up to top_k non-overlapping text spans from the original document.

Interface

def extract_keyphrases(
    raw_text: str,
    token_offsets: list[tuple[int, int]],
    start_logits: list[float],
    end_logits: list[float],
    max_span_length: int = 5,
    top_k: int = 3,
    min_score: float = 0.0
) -> list[dict]:
    """
    Extracts up to top_k keyphrase spans sorted by score in descending order.
    """
    pass

Business Logic and Specifications

  1. Special Tokens: Tokens mapped to offset (0, 0) are special or padding tokens (such as [CLS], [SEP], or [PAD]). They cannot be chosen as either the start or the end of a valid phrase span.
  2. Span Validity & Scoring:
    • A valid span is bounded by token indices (i, j) where $i \le j$.
    • The token span length in tokens is defined as $j - i + 1$, which must not exceed max_span_length.
    • Neither token $i$ nor token $j$ can be a special token (0, 0).
    • The score of the span is the sum of the logits: $\text{score}(i, j) = \text{start_logits}[i] + \text{end_logits}[j]$.
    • Spans with $\text{score} < \text{min_score}$ are excluded.
  3. Character Range Mapping:
    • For a token span from $i$ to $j$, the underlying text span starts at index char_start = token_offsets[i][0] and ends at char_end = token_offsets[j][1].
    • The extracted text string is given by slice raw_text[char_start:char_end].
  4. Greedy Non-Max Suppression (Deduplication):
    • Extracted character spans must not overlap. Character ranges are half-open intervals $[char_start, char_end)$.
    • Sort candidate spans primarily by score in descending order. If scores tie, break ties deterministically by choosing the candidate with the earlier char_start, then the smaller char_end.
    • Iterate through sorted candidate spans sequentially, selecting a candidate span only if its character interval $[char_start, char_end)$ does not overlap with any previously accepted character span.
  5. Output Format:
    • Return a list of dictionary entries formatted as: [{"text": str, "char_start": int, "char_end": int, "score": float}, ...]
    • Return at most top_k entries.

Example

raw_text = "Design systems scale UI components."
token_offsets = [(0, 0), (0, 6), (7, 14), (15, 20), (21, 23), (24, 34), (34, 35), (0, 0)]
# Tokens corresponding to offsets:
# [CLS], "Design", "systems", "scale", "UI", "components", ".", [SEP]

start_logits = [0.0, 3.5, 0.2, 0.1, 2.8, 0.4, -1.0, 0.0]
end_logits   = [0.0, 0.1, 3.2, 0.0, 0.5, 3.0, -1.0, 0.0]

results = extract_keyphrases(
    raw_text, token_offsets, start_logits, end_logits, max_span_length=3, top_k=2
)
# Expected Output:
# [
#   {"text": "Design systems", "char_start": 0, "char_end": 14, "score": 6.7},
#   {"text": "UI components", "char_start": 21, "char_end": 34, "score": 5.8}
# ]

Constraints

  • len(token_offsets) == len(start_logits) == len(end_logits)
  • Token sequence lengths are within typical transformer bounds ($N \le 512$).
  • max_span_length >= 1, top_k >= 0.

Hints

Hint 1

Recall the standard interval overlap condition: two half-open intervals [a, b) and [c, d) overlap if and only if max(a, c) < min(b, d).

Hint 2

Compute token scores directly as start_logits[i] + end_logits[j], filtering out pairs where start or end token has offset (0, 0) or length exceeds max_span_length.

Hint 3

Sort all valid candidates by (-score, char_start, char_end) before executing 1D Greedy Non-Maximum Suppression (NMS).