Sequence and Attention Utilities
Original Python research interviews on attention visibility, cache positions, stable normalization, sequence supervision, constrained decoding, and path-mass recurrences.
These problems are original practice. They are not questions from a named employer or a live hiring loop.
1.Keep real padding-valued tokens distinct from added padding
Write
left_pad(sequences, pad). sequences contains integer token lists; pad is integer. Pad on the left to the longest length, width 0 if no sequences. Return {"tokens":padded rows,"valid":Boolean rows,"positions":0-based positions within each original sequence,Noneat added pads}. Original tokens equal to pad remain valid. Preserve order and do not mutate.2.Compare absolute query and key positions in a cache mask
Write
causal_offsets(query_count, key_count, query_start, key_start). Counts are nonnegative integers; starts are integer absolute positions. Return aquery_count-by-key_countBoolean matrix: row i allows column j iffkey_start+j<=query_start+i. Include position equality. Counts may be zero; do not assume the query starts at position 0.3.Combine local causal distance with packed segment identity
Write
segmented_window(segments, positions, radius). segments is string ids; positions is equally long integers; radius>=0 integer. Return a square Boolean mask allowing query i to key j iff segments match and 0<=positions[i]-positions[j]<=radius. Positions may reset across segments. Both distance endpoints are inclusive; do not mutate.4.Keep prefix context bidirectional and continuation causal
Write
prefix_visibility(length, prefix). Integers satisfy 0<=prefix<=length. Positions 0..prefix-1 form a bidirectional prefix. Prefix queries see only prefix keys; continuation query i sees all keys j<=i. Return the square Boolean visibility matrix. A zero prefix is fully causal; a full-length prefix is fully visible.5.Trim old cache entries without renumbering aligned rows
Write
trim_cache(old, new, capacity). Rows are[integer_absolute_position,key_vector,value_vector]with compatible finite vector widths; positions strictly increase across old+new. capacity>=0 integer. Append new to old, retain the last capacity rows, and return copied rows/vectors preserving positions. capacity=0 returns []. Do not renumber or mutate inputs.6.Map contiguous query-head groups onto shared key heads
Write
query_head_map(query_heads, key_heads), nonnegative integers. ReturnNoneif either is zero orquery_headsis not divisible bykey_heads. Otherwise each key head serves one equal contiguous group of query heads; return the key-head index for query indices 0..query_heads-1. Do not use cyclic modulo assignment.7.Rotate adjacent coordinates using the supplied pair angles
Write
rotate_pairs(vector, angles). vector is a finite even-length list, angles has half its length in radians. For each adjacent (x,y) and angle a return (x*cos(a)-y*sin(a), x*sin(a)+y*cos(a)). Preserve pair order and return a flat list. Empty inputs return []; do not pair the first half against the second half or mutate.8.Clip signed key distances before assigning boundary buckets
Write
distance_buckets(queries, keys, clip, bounds). Positions and bounds are integers; bounds strictly increase and clip>=0. Per query q/key k set d=min(clip,max(-clip,k-q)). Bucket is the first index with d<=bounds[index], orlen(bounds)if none. Return query-by-key integer rows. Empty bounds gives bucket 0; do not discard the distance sign.9.Keep head slope and signed absolute distance separate
Write
distance_bias(slopes, queries, keys). slopes is finite scalars; query/key positions are integers. Return[head][query][key]values slope*(key_position-query_position). Preserve all three input orders. Future key distance is positive and past distance negative; do not apply a causal mask or take absolute distance.10.Apply query-key scaling before returning supported scores
Write
score_matrix(queries, keys, visible). queries is n-by-d and keys m-by-d finite vectors, d>0; visible is n-by-m Booleans,Truemeans allowed. Return query-by-keydot(query,key)/sqrt(d), replacing hidden entries byNone. Empty query/key lists are valid. Do not normalize scores or transpose the output orientation.11.Exclude hidden logits from both maximum and denominator
Write
masked_probs(logits, visible). Equal-length finite logits and Boolean visibility. Return probabilities proportional toexp(logit)overTrueentries and 0 elsewhere. Use max subtraction over visible logits only. An entirely hidden row, including empty input, returns all zeros. Do not evaluate exponentials for hidden logits or mutate inputs.12.Preserve zero-supported attention rows in value aggregation
Write
weighted_values(weights, values, width). weights is n-by-m finite nonnegative rows, each summing to 1 or 0. values is m-by-width finite; width>=0 integer. Return n-by-width sumssum(weights[i][j]*values[j][k]). A zero-supported row returns zeros, including m=0. Do not renormalize or mutate inputs.13.Rescale chunk summaries to one common attention maximum
Write
merge_attention(states, width). Each state isNoneor [finite_max,positive_scaled_sum,finite_weighted_vector_of_width]. It summarizesexp(logit-max)and their value-weighted sums. Rescale nonempty states to their greatest max before adding. Return{"state":[max,sum,weighted],"value":weighted/sum}; if all empty return{"state":None,"value":None}. No mutation.14.Include cross-coordinate coupling in a probability pullback
Write
probability_pullback(probabilities, upstream). Equal-length finite lists; probabilities>=0 sum to 1 unless empty. Returnprobabilities[i]*(upstream[i]-sum(probabilities[j]*upstream[j])) for every i. This is the normalized-exponential logit cotangent. Do not keep only diagonal terms, normalize its length, or mutate inputs.15.Project concatenated heads in their declared order
Write
project_heads(heads, projection, bias). heads is finite equal-width head vectors, flattened by head order then coordinate order. projection has one finite row per output, each of that flattened width; bias matches outputs. Return projection*flat+bias. Empty heads and zero outputs are allowed with compatible dimensions. Do not transpose or mutate.16.Mask query rows and key columns independently
Write
cross_visibility(query_valid, key_valid). Two Boolean lists describe different sequence lengths. Return a rectangular Boolean matrix where row i, column j isquery_valid[i]andkey_valid[j]. Invalid queries have entirely hidden rows; invalid keys have hidden columns. Do not assume equal lengths or infer validity from token ids.17.Keep attention inside packed sequence blocks
Write
packed_visibility(lengths). lengths contains nonnegative integer segment lengths in packed order. Return asum(lengths)-square Boolean mask,Trueiff two flattened positions belong to the same segment. Visibility inside a segment is bidirectional; zero-length segments contribute no positions. Do not apply causality or merge neighboring nonempty segments.18.Reset token positions at every packed segment boundary
Write
packed_positions(lengths). lengths is nonnegative integers in packed segment order. Return one flattened integer list, using positions 0..length-1 within each segment. Empty segments contribute nothing. Preserve segment order and do not use a running global token index as the local position.19.Build bounded teacher contexts without crossing documents
Write
teacher_contexts(documents, window). documents contains integer token lists; window>=1 integer. For each document d and target index i=1..len(doc)-1 return [d,doc[max(0,i-window):i],doc[i]], in document then target order. Every supplied token id is real, even 0. Do not append terminal tokens or join document boundaries; no mutation.20.Shift target validity together with token labels
Write
shifted_labels(tokens, valid, segments). Equal-length lists of integer tokens, Boolean validity and string segment ids. For each i=0..n-2 returntokens[i+1]iffvalid[i],valid[i+1]andsegments[i]==segments[i+1]; elseNone. Preserve one result per adjacent slot, including hidden slots. A valid target id 0 remains 0. Do not mutate.21.Normalize sequence loss by actual supervised tokens
Write
sequence_loss(logits, targets, mask). logits is finite n-by-v with v>=1; target indices and Boolean mask have length n. Sum stable negative log softmax at each target only where mask=True. Return {"sum":total_loss,"count":supported_tokens,"mean":total_loss/count orNoneif count=0}. Empty sequence yields sum=0. Do not divide by padded length or mutate.22.Keep forbidden vocabulary entries at zero target mass
Write
restricted_target(size, target, allowed, smoothing). size>=1 integer; allowed lists unique valid vocabulary indices; target is valid; smoothing in[0,1]. ReturnNoneif target not in allowed. Otherwise put smoothing/len(allowed)on each allowed index, add 1-smoothing at target, and leave all other size entries zero. This includes target in the uniform part. No mutation.23.Separate macro sequence accuracy from pooled token accuracy
Write
sequence_accuracy(predictions, targets, masks). Three equally long lists of sequences; each corresponding row has equal length and Boolean masks. Return {"per_sequence":accuracies orNonefor zero support,"macro":mean of supported sequence accuracies orNone,"pooled":all correct supported tokens/all supported tokens orNone}. Token ids are integers. Do not mutate.24.Rank completed paths using exact declared length penalties
Write
rank_paths(rows, alpha). Rows are [unique_string_id,nonempty_token_list,finite_exact_decimal_score]; alpha>=0 integer. Rank by score/(token_count^alpha) decreasing, then id alphabetically. Return[id,normalized_score]rows. Compare exactly before numeric output. Do not change raw scores, use length+1, or discard deterministic ties.25.Rank all parent-token candidates before beam truncation
Write
beam_extensions(parent_scores, token_scores, limit). Finite exact-decimal parent scores;token_scoreshas one equal-width row per parent, finite entries orNonefor forbidden tokens; limit>=0 integer. Score each allowed pair by parent+token. Return up to limit[parent_index,token_index,score]rows by score decreasing, then parent index, then token index. No mutation.26.Carry finished beams unchanged through candidate selection
Write
retain_beams(beams, expansions, limit). beams rows:[id,score,done_bool];expansions[parent_id]rows:[child_id,increment,done_bool]. Scores/increments are exact finite decimals, candidate ids unique; limit>=0 integer. Retain done parents unchanged, ignoring expansions. Replace active parents by children scored parent+increment. Return top limit rows by score decreasing then id; no mutation.27.Block only tokens that would repeat the current suffix gram
Write
ngram_blocks(tokens, n). tokens lists integer ids; n>=1 integer. Return sorted unique next-token ids that would create an n-gram already present in tokens. Match the current suffix of length n-1 against each previous complete n-gram prefix. For n=1 block every observed id; if too short to match any gram return []. Do not generate a token or mutate.28.Allow tokens by edge presence, including empty destinations
Write
state_visibility(states, transitions, vocabulary). states lists strings; transitions maps state strings to dictstoken_string->next_state_string; vocabulary lists unique token strings. Return[hypothesis][token]Booleans for whether that outgoing token edge exists. Missing states have no edges. Empty destination strings are valid states. Preserve both orders; do not advance states or mutate.29.Sum path mass stably instead of choosing only the best path
Write
forward_logmass(initial, transition, emissions). Log potentials are finite orNone(zero mass). initial length S>=1; transition is S-by-S from old state i to new j; emissions is T-by-S. Path log weight isinitial[first]+all emissions+intermediate transitions. Return log(sum(exp(path_weight))) over all state paths,Noneif unsupported. T=0 returnslogsumexp(initial). Use stable arithmetic.30.Merge adjacent path repeats before removing the blank symbol
Write
collapse_path(path, blank). path lists integer symbols; blank is an integer. First collapse each adjacent run of identical symbols to one, then remove blank symbols. Return the resulting symbol list. Repeats separated by a blank remain separate outputs; do not remove blanks before deciding runs, globally deduplicate labels, or mutate.