Decode Non-Overlapping Keyphrase Spans from BERT Logits
Greedy & IntervalsModel answerLast 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
- 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. - 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.
- A valid span is bounded by token indices
- 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 atchar_end = token_offsets[j][1]. - The extracted text string is given by slice
raw_text[char_start:char_end].
- For a token span from $i$ to $j$, the underlying text span starts at index
- 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 smallerchar_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.
- Output Format:
- Return a list of dictionary entries formatted as:
[{"text": str, "char_start": int, "char_end": int, "score": float}, ...] - Return at most
top_kentries.
- Return a list of dictionary entries formatted as:
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).
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer & Discussion
Overview of the Approach
The task involves converting token-level outputs from a transformer architecture into clean character-level entity extractions. The implementation comprises four steps:
- Filtering & Candidate Generation: Identify non-special tokens where
offset != (0, 0). Iterate through all valid start token indices $i$ and end token indices $j$ satisfying $i \le j$ and $j - i + 1 \le \text{max_span_length}$. - Scoring & Thresholding: Compute raw logit score $S_{i, j} = \text{start_logits}[i] + \text{end_logits}[j]$. Retain pairs with score $\ge \text{min_score}$.
- Deterministic Sorting: Sort candidate spans descending by score. Break ties by
char_startascending, thenchar_endascending. - Greedy Non-Maximum Suppression (NMS): Sequentially iterate over candidate intervals. Maintain a set of accepted character intervals $[s_a, e_a)$. Accept candidate $[s_c, e_c)$ if it does not overlap with any previously accepted interval. Stop early once
top_kintervals have been selected.
Detailed Python Implementation
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]:
"""
Decodes token-level logits into top_k non-overlapping character spans.
"""
if top_k <= 0 or max_span_length <= 0:
return []
num_tokens = len(token_offsets)
is_valid_token = [offset != (0, 0) for offset in token_offsets]
candidates = []
# 1. Enumerate candidate spans
for i in range(num_tokens):
if not is_valid_token[i]:
continue
max_j = min(num_tokens - 1, i + max_span_length - 1)
for j in range(i, max_j + 1):
if not is_valid_token[j]:
continue
score = start_logits[i] + end_logits[j]
if score < min_score:
continue
char_start = token_offsets[i][0]
char_end = token_offsets[j][1]
candidates.append((score, char_start, char_end))
# 2. Sort candidates descending by score with deterministic tie-breaking
candidates.sort(key=lambda c: (-c[0], c[1], c[2]))
# 3. Greedy interval NMS
accepted_spans: list[tuple[int, int]] = []
output_spans: list[dict] = []
for score, cs, ce in candidates:
# Two half-open intervals [a, b) and [c, d) overlap if max(a, c) < min(b, d)
if any(max(cs, acc_start) < min(ce, acc_end) for acc_start, acc_end in accepted_spans):
continue
accepted_spans.append((cs, ce))
output_spans.append({
"text": raw_text[cs:ce],
"char_start": cs,
"char_end": ce,
"score": score
})
if len(output_spans) == top_k:
break
return output_output_spans if 'output_output_spans' in locals() else output_spans
Complexity Analysis
Let $N$ be the sequence length of tokens ($N \le 512$), $L$ be max_span_length ($L \le 5$), and $K$ be top_k.
- Candidate Generation: We evaluate at most $N \times L$ token pairs. This step takes $O(N \cdot L)$ time.
- Sorting: We sort at most $N \cdot L$ candidates. Time complexity is $O(N L \log(N L))$. For $N = 512$ and $L = 5$, $N L = 2560$, requiring $\approx 2.9 \times 10^4$ operations.
- Greedy Filtering: At most $N \cdot L$ candidates are checked against up to $K$ accepted spans. Overlap checking takes $O(N L \cdot K)$ time.
- Total Time Complexity: $O(N L \log(N L) + N L \cdot K)$, which runs in sub-millisecond time.
- Space Complexity: $O(N \cdot L)$ auxiliary space to store candidate tuples.
Key Interview Discussion Topics & Trade-offs
1. Long Documents Exceeding Transformer Context Limits (512 Tokens)
In real-world applications, documents often exceed single-window transformer capacity.
- Sliding Window Tokenization: Process text with overlapping windows (e.g., window size $W = 512$, stride $S = 384$).
- Aggregation Approaches:
- Span-Level Aggregation (Recommended): Run candidate extraction per window, convert candidates to global document character offsets, combine all candidates across windows, and execute NMS once globally.
- Logit Pooling: Merge overlapping tokens across windows by taking max or distance-weighted average of
start_logitsandend_logits, then decode once. (Distance weighting gives less weight to logits near sequence edges, where contextual awareness is diminished).
2. Subword Alignments & Partial Word Boundaries
Using WordPiece or BPE tokenizers can cause spans to begin or end mid-word (e.g., starting at ##ment in develop ##ment).
- Handling Strategies:
- Masking: Set logits for non-initial subwords to $-\infty$ for start predictions, and non-terminal subwords to $-\infty$ for end predictions using tokenizer
word_ids(). - Post-hoc Expansion: Expand extracted character ranges outward to match complete word boundaries in raw text.
- Masking: Set logits for non-initial subwords to $-\infty$ for start predictions, and non-terminal subwords to $-\infty$ for end predictions using tokenizer
3. Global Optimization (DP) vs. Greedy Selection
- Greedy NMS: Prioritizes highest confidence predictions. Selecting one long high-scoring span may block two slightly lower-scoring non-overlapping spans.
- Weighted Interval Scheduling (DP): Dynamically computes the combination of non-overlapping spans that maximizes overall sum of scores.
- Trade-off Choice: Greedy NMS is preferred in keyphrase extraction because local precision on top entity predictions is more critical than maximizing total aggregated logit score across the document.