creegon's picture
Release 0.1.0 (same files as staging-0.1.0 @ 90a07ac4)
7b0b7bc verified
Raw History Blame Contribute Delete
6.04 kB
"""Packed sequences and their attention schedules.
Attention kernels consume block schedules from this module. The dense mask
provides a CPU reference for checking short sequences.
"""
from dataclasses import dataclass
from typing import Dict, List, Sequence, Tuple
class PackedSequenceError(ValueError):
"""Raised when a packed sequence is structurally invalid."""
ATTENTION_MODES = ("causal", "full", "noise", "full_noise", "full_noise_target")
EXPERTS = ("understanding", "generation")
def normalize_attention_mode(mode: str) -> str:
if mode in ("full_noise", "full_noise_target"):
return "full"
if mode not in ("causal", "full", "noise"):
raise PackedSequenceError("unsupported attention mode: {}".format(mode))
return mode
@dataclass(frozen=True)
class PackedSegment:
length: int
attention_mode: str
modality: str
expert: str
def __post_init__(self) -> None:
if not isinstance(self.length, int) or isinstance(self.length, bool) or self.length <= 0:
raise PackedSequenceError("segment length must be a positive integer")
if self.attention_mode not in ATTENTION_MODES:
raise PackedSequenceError("unsupported attention mode: {}".format(self.attention_mode))
if self.expert not in EXPERTS:
raise PackedSequenceError("unsupported expert: {}".format(self.expert))
if not self.modality:
raise PackedSequenceError("segment modality must not be empty")
@property
def normalized_attention_mode(self) -> str:
return normalize_attention_mode(self.attention_mode)
@dataclass(frozen=True)
class PackedDocument:
sample_id: str
segments: Tuple[PackedSegment, ...]
def __post_init__(self) -> None:
if not self.sample_id:
raise PackedSequenceError("sample_id must not be empty")
if not self.segments:
raise PackedSequenceError("a document must contain at least one segment")
@property
def length(self) -> int:
return sum(segment.length for segment in self.segments)
@dataclass(frozen=True)
class AttentionBlock:
document_index: int
query_start: int
query_end: int
key_start: int
key_end: int
causal: bool
def to_dict(self) -> Dict[str, object]:
return dict(self.__dict__)
@dataclass(frozen=True)
class PackedSequence:
documents: Tuple[PackedDocument, ...]
def __post_init__(self) -> None:
if not self.documents:
raise PackedSequenceError("a packed sequence must contain at least one document")
sample_ids = [document.sample_id for document in self.documents]
if len(sample_ids) != len(set(sample_ids)):
raise PackedSequenceError("sample_id values must be unique inside a packed sequence")
@property
def length(self) -> int:
return sum(document.length for document in self.documents)
@property
def document_lengths(self) -> Tuple[int, ...]:
return tuple(document.length for document in self.documents)
@property
def split_lengths(self) -> Tuple[int, ...]:
return tuple(segment.length for document in self.documents for segment in document.segments)
@property
def attention_modes(self) -> Tuple[str, ...]:
return tuple(segment.attention_mode for document in self.documents for segment in document.segments)
def token_expert_indexes(self) -> Dict[str, Tuple[int, ...]]:
indexes: Dict[str, List[int]] = {"understanding": [], "generation": []}
offset = 0
for document in self.documents:
for segment in document.segments:
indexes[segment.expert].extend(range(offset, offset + segment.length))
offset += segment.length
result = {name: tuple(values) for name, values in indexes.items()}
combined = sorted(result["understanding"] + result["generation"])
if combined != list(range(self.length)):
raise PackedSequenceError("expert routing must cover every packed token exactly once")
return result
def block_schedule(self) -> Tuple[AttentionBlock, ...]:
"""Compile the upstream sparse-mask semantics into rectangular blocks.
Every query segment can read all earlier non-noise segments. It can read
itself causally for text or bidirectionally for full/noise visual spans.
A noise segment is never exposed as KV to another segment, including a
later segment in the same sample.
"""
blocks: List[AttentionBlock] = []
document_offset = 0
for document_index, document in enumerate(self.documents):
segment_ranges: List[Tuple[int, int, PackedSegment]] = []
cursor = document_offset
for segment in document.segments:
segment_ranges.append((cursor, cursor + segment.length, segment))
cursor += segment.length
for query_index, (query_start, query_end, query_segment) in enumerate(segment_ranges):
for key_start, key_end, key_segment in segment_ranges[:query_index]:
if key_segment.normalized_attention_mode != "noise":
blocks.append(
AttentionBlock(
document_index,
query_start,
query_end,
key_start,
key_end,
causal=False,
)
)
blocks.append(
AttentionBlock(
document_index,
query_start,
query_end,
query_start,
query_end,
causal=query_segment.normalized_attention_mode == "causal",
)
)
document_offset = cursor
return tuple(blocks)