from __future__ import annotations from collections.abc import Sequence import numpy as np def loop_onset( token_ids: Sequence[int], min_period: int = 1, max_period: int = 512, min_repeats: int = 4, min_span: int = 64, ) -> int | None: """Index where the trailing repetition run starts, or None if the tail is not a loop. A tail loops when, for some period p, the last p + r tokens satisfy a[i] == a[i - p] throughout, i.e. a block of p tokens repeated back to back, with p + r >= max(min_span, min_repeats * p). The run is extended backwards as far as it keeps matching, so if a suffix of the preceding text equals the end of the block, the reported onset is earlier than the first full block by that overlap (always less than p tokens). """ a = np.asarray(token_ids) n = len(a) best: int | None = None for p in range(max(1, min_period), min(max_period, n - 1) + 1): if a[-1] != a[-1 - p]: continue eq = (a[p:] == a[:-p])[::-1] first_break = int(np.argmin(eq)) run = first_break if not eq[first_break] else len(eq) span = p + run if span >= max(min_span, min_repeats * p): start = n - span if best is None or start < best: best = start return best def repeated_fraction(token_ids: Sequence[int], n: int = 32) -> float: """Fraction of n-grams that already appeared earlier in the sequence.""" a = np.asarray(token_ids, dtype=np.int64) total = len(a) - n + 1 if total <= 0: return 0.0 raw = a.tobytes() width = 8 * n seen: set[bytes] = set() repeated = 0 for i in range(total): gram = raw[8 * i : 8 * i + width] if gram in seen: repeated += 1 else: seen.add(gram) return repeated / total