diff --git a/aspec/models/dflash.py b/aspec/models/dflash.py index 0cc0302..edca84c 100644 --- a/aspec/models/dflash.py +++ b/aspec/models/dflash.py @@ -77,6 +77,7 @@ def _create_dflash_mask_mod( sliding_window: int | None = None, ctx_doc_ids: Optional[torch.Tensor] = None, context_window: int | None = None, + attention_mask: Optional[torch.Tensor] = None, ): """Create a mask_mod function for DFlash block-causal attention. @@ -103,6 +104,9 @@ def dflash_mask_mod(b, h, q_idx, kv_idx): context_index = torch.where(is_context, kv_idx, torch.zeros_like(kv_idx)) context_doc = ctx_doc_ids[b, context_index] mask_context = mask_context & (anchor_doc >= 0) & (context_doc == anchor_doc) + if attention_mask is not None: + context_index = torch.where(is_context, kv_idx, torch.zeros_like(kv_idx)) + mask_context = mask_context & attention_mask[b, context_index].bool() is_draft = kv_idx >= ctx_len kv_block_id = (kv_idx - ctx_len) // block_size @@ -137,6 +141,7 @@ def _create_dflash_dense_mask( ctx_len: int, block_size: int, is_causal: bool, + attention_mask: Optional[torch.Tensor] = None, ) -> torch.Tensor: """Materialize the block mask for backends without FlexAttention (CPU). @@ -157,6 +162,14 @@ def _create_dflash_dense_mask( mask_context = is_context.unsqueeze(0).unsqueeze(0) & ( kv_index.unsqueeze(0).unsqueeze(0) < anchor.unsqueeze(-1) ) + if attention_mask is not None: + if attention_mask.shape != (anchor_positions.shape[0], ctx_len): + raise ValueError("DFlash attention_mask must match [B, context length]") + context_valid = torch.zeros( + attention_mask.shape[0], kv_len, dtype=torch.bool, device=device + ) + context_valid[:, :ctx_len] = attention_mask.to(device=device).bool() + mask_context = mask_context & context_valid.unsqueeze(1) is_draft = kv_index >= ctx_len kv_block = (kv_index - ctx_len) // block_size mask_draft = is_draft.unsqueeze(0).unsqueeze(0) & ( @@ -865,6 +878,7 @@ def _draft_backbone( ctx_len=seq_len, block_size=self.block_size, ctx_doc_ids=ctx_doc_ids, + attention_mask=attention_mask, **options, ) mask_cache[cache_key] = compile_friendly_create_block_mask( @@ -911,6 +925,7 @@ def _draft_backbone( seq_len, self.block_size, is_causal=causal, + attention_mask=attention_mask, ) dense_masks.append(dense_cache[causal]) else: diff --git a/aspec/models/draft/dspine.py b/aspec/models/draft/dspine.py new file mode 100644 index 0000000..4755b12 --- /dev/null +++ b/aspec/models/draft/dspine.py @@ -0,0 +1,327 @@ +# Copyright 2026 Ant Group Co., Ltd. +# SPDX-License-Identifier: Apache-2.0 + +# Adapted from the public DSpine implementation (Tencent/DSpine, Apache-2.0) +# and the merged SpecForge DSpine training path (PR #965, corrected by PR #1038). +# The adjacent injection, transfer-code space and candidate refinement follow +# those references; ASpec supplies configuration validation and training wiring. +"""DSpine Draft: DFlash backbone with adjacent causal injection and refinement.""" + +from __future__ import annotations + +import math +from dataclasses import asdict, dataclass +from typing import NamedTuple + +import torch +import torch.nn.functional as F +from torch import nn + +from aspec.models.draft.dflash import DFlashConfig, DFlashDraftModel + + +@dataclass(frozen=True) +class DSpineOptions: + transfer_rank: int = 1024 + message_size: int = 512 + top_k: int = 16 + ce_weight: float = 0.1 + alignment_weight: float = 0.5 + alignment_warmup_steps: int = 146 + replacement_layers: int = 3 + replacement_probability: float = 0.5 + replacement_hold_ratio: float = 1 / 6 + replacement_end_ratio: float = 1 / 3 + candidate_mass_threshold: float = 1e-4 + + def validate(self, hidden_size: int, vocab_size: int) -> None: + for name in ( + "transfer_rank", "message_size", "top_k", "alignment_warmup_steps", + "replacement_layers", + ): + value = getattr(self, name) + if not isinstance(value, int) or isinstance(value, bool): + raise ValueError(f"DSpine {name} must be an integer") + for name, value in asdict(self).items(): + if not math.isfinite(value): + raise ValueError(f"DSpine {name} must be finite") + if not 0 < self.transfer_rank <= min(hidden_size, vocab_size - 1): + raise ValueError( + "DSpine transfer_rank must be in [1, min(hidden_size, vocab_size - 1)]" + ) + if self.message_size < 1 or not 1 <= self.top_k <= vocab_size: + raise ValueError("DSpine requires message_size > 0 and top_k in [1, vocab_size]") + if not 0 <= self.ce_weight <= 1 or self.alignment_weight < 0: + raise ValueError( + "DSpine requires ce_weight in [0, 1] and alignment_weight >= 0" + ) + if self.alignment_warmup_steps < 0 or self.replacement_layers < 0: + raise ValueError( + "DSpine warmup steps and replacement layers must be nonnegative" + ) + if not 0 <= self.replacement_probability <= 1: + raise ValueError("DSpine replacement_probability must be in [0, 1]") + if not 0 <= self.replacement_hold_ratio < self.replacement_end_ratio <= 1: + raise ValueError( + "DSpine requires 0 <= replacement_hold_ratio < replacement_end_ratio <= 1" + ) + if not 0 <= self.candidate_mass_threshold < 1: + raise ValueError("DSpine candidate_mass_threshold must be in [0, 1)") + + def schedule(self, step: int, total_steps: int | None) -> tuple[float, float]: + warmup = self.alignment_warmup_steps + beta = self.alignment_weight * (min(max(step, 0) / warmup, 1) if warmup else 1) + if not total_steps or total_steps <= 0: + return beta, 0.0 + progress = max(step, 0) / total_steps + fraction = (self.replacement_end_ratio - progress) / ( + self.replacement_end_ratio - self.replacement_hold_ratio + ) + return beta, self.replacement_probability * min(max(fraction, 0), 1) + + +class DSpineConfig(DFlashConfig): + """DFlash backbone plus DSpine injection/refinement options.""" + + model_type = "dspine" + + def __init__( + self, + *, + block_size: int = 16, + dspine_config: dict | None = None, + **kwargs, + ): + architectures = kwargs.pop("architectures", ["DSpineDraftModel"]) + if architectures != ["DSpineDraftModel"]: + raise ValueError("DSpine uses exactly one DSpineDraftModel architecture") + if kwargs.get("is_causal") is False: + raise ValueError("DSpine requires causal draft attention") + if isinstance(block_size, bool) or not isinstance(block_size, int) or block_size < 2: + raise ValueError("DSpine block_size must be an integer >= 2") + kwargs["is_causal"] = True + options = DSpineOptions(**(dspine_config or {})) + super().__init__(architectures=architectures, block_size=block_size, **kwargs) + options.validate(self.hidden_size, self.vocab_size) + if self.ffn_type != "dense": + raise ValueError("DSpine currently supports dense Draft FFNs only") + if any(kind != "full_attention" for kind in (self.layer_types or [])): + raise ValueError("DSpine currently supports full intra-block attention only") + if getattr(self, "mtp_conditioning", None) is not None: + raise ValueError("DSpine does not use the native-MTP conditioning contract") + for stage in ("csa_training_stage", "qsa_training_stage", "dsa_training_stage"): + if getattr(self, stage, None) is not None: + raise ValueError("DSpine is not integrated with sparse-attention training") + self.dspine_config = asdict(options) + + +class DSpineOutput(NamedTuple): + hidden_states: torch.Tensor + pre_injection: torch.Tensor + layer_features: torch.Tensor + + +class AdjacentInjection(nn.Module): + """Adjacent-token transfer codes and gated writes between draft layers.""" + + def __init__(self, hidden_size: int, num_layers: int, options: DSpineOptions): + super().__init__() + self.rank = options.transfer_rank + self.replacement_layers = options.replacement_layers + self.readouts = nn.ModuleList( + nn.Linear(hidden_size, self.rank, bias=False) for _ in range(num_layers) + ) + self.writes = nn.ModuleList( + nn.Linear(options.message_size, hidden_size, bias=False) + for _ in range(num_layers) + ) + self.message = nn.Linear(self.rank, options.message_size, bias=False) + self.receiver_gate = nn.Linear(self.rank, options.message_size, bias=False) + self.predecessor_gate = nn.Linear(self.rank, options.message_size, bias=False) + self.bias = nn.Parameter(torch.zeros(options.message_size)) + for write in self.writes: + nn.init.zeros_(write.weight) + nn.init.zeros_(self.predecessor_gate.weight) + + def feature(self, hidden: torch.Tensor, layer: int) -> torch.Tensor: + projected = self.readouts[layer](hidden) + return (math.sqrt(self.rank) * F.normalize(projected.float(), dim=-1)).to( + hidden.dtype + ) + + def write( + self, + hidden: torch.Tensor, + receiver: torch.Tensor, + predecessor: torch.Tensor, + layer: int, + ) -> torch.Tensor: + predecessor = predecessor.to(receiver.dtype) + gate = torch.sigmoid( + self.receiver_gate(receiver) + + self.predecessor_gate(predecessor) + + self.bias + ) + delta = self.writes[layer](gate * self.message(predecessor)) + scale = ( + torch.linalg.vector_norm(hidden.float(), dim=-1, keepdim=True) + / math.sqrt(hidden.shape[-1]) + ).to(hidden.dtype) + return hidden + scale * delta + + def forward( + self, + hidden: torch.Tensor, + layer: int, + token_ids: torch.Tensor, + codes: torch.Tensor, + replace: torch.Tensor | None = None, + ) -> torch.Tensor: + features = self.feature(hidden, layer) + anchor = math.sqrt(self.rank) * F.embedding(token_ids[..., :1], codes) + predecessors = torch.cat((anchor, features[..., 1:-1, :]), dim=-2) + if replace is not None and layer < self.replacement_layers: + correct = math.sqrt(self.rank) * F.embedding(token_ids[..., :-1], codes) + predecessors = torch.where(replace[..., None, None], correct, predecessors) + successors = self.write( + hidden[..., 1:, :], features[..., 1:, :], predecessors, layer + ) + return torch.cat((hidden[..., :1, :], successors), dim=-2) + + +class DSpineDraftModel(DFlashDraftModel): + """DFlash Draft with DSpine adjacent injection and refinement.""" + + config_class = DSpineConfig + + def __init__(self, config): + super().__init__(config) + self.dspine_config = DSpineOptions(**config.dspine_config) + self.dspine_config.validate(config.hidden_size, config.vocab_size) + if config.block_size < 2: + raise ValueError( + "DSpine block_size must include an anchor and at least one proposal" + ) + self.injection = AdjacentInjection( + config.hidden_size, config.num_hidden_layers, self.dspine_config + ) + self.register_buffer( + "transfer_codes", + torch.zeros(config.vocab_size, self.dspine_config.transfer_rank), + ) + self.register_buffer("transfer_ready", torch.tensor(False)) + + @torch.no_grad() + def initialize_transfer_space( + self, head_weight: torch.Tensor, chunk_size: int = 4096 + ) -> None: + """Initialize whitened token codes and layer readouts from the Target head.""" + if tuple(head_weight.shape) != ( + self.config.vocab_size, + self.config.hidden_size, + ): + raise ValueError( + "DSpine transfer space requires the Target head's full vocabulary and hidden width" + ) + if chunk_size < 1: + raise ValueError("chunk_size must be positive") + width = head_weight.shape[1] + covariance = torch.zeros( + width, width, device=head_weight.device, dtype=torch.float32 + ) + total = covariance.new_zeros(width) + for rows in head_weight.split(chunk_size): + normalized = F.normalize(rows.float(), dim=-1) + total.add_(normalized.sum(dim=0)) + covariance.add_(normalized.T @ normalized) + mean = total / head_weight.shape[0] + covariance.sub_(head_weight.shape[0] * torch.outer(mean, mean)) + values, directions = torch.linalg.eigh(covariance) + values = values[-self.dspine_config.transfer_rank :] + directions = directions[:, -self.dspine_config.transfer_rank :] + if not torch.isfinite(values).all() or (values <= 0).any(): + raise ValueError( + "Target head has insufficient positive principal directions for transfer_rank" + ) + for start in range(0, head_weight.shape[0], chunk_size): + rows = head_weight[start : start + chunk_size] + codes = F.normalize( + (F.normalize(rows.float(), dim=-1) - mean) @ directions + / values.sqrt(), + dim=-1, + ) + self.transfer_codes[start : start + len(rows)].copy_(codes.to(self.transfer_codes.dtype)) + for readout in self.injection.readouts: + readout.weight.copy_(directions.T.to(readout.weight.dtype)) + self.transfer_ready.fill_(True) + + def _require_transfer_ready(self) -> None: + if not bool(self.transfer_ready): + raise ValueError( + "Initialize or load the DSpine transfer space before use" + ) + + def forward( + self, + context_feature: torch.Tensor, + draft_position_ids: torch.Tensor, + context_position_ids: torch.Tensor, + block_mask=None, + noise_embedding: torch.Tensor | None = None, + block_token_ids: torch.Tensor | None = None, + replace_mask: torch.Tensor | None = None, + draft_attention_mask=None, + **kwargs, + ) -> DSpineOutput: + self._require_transfer_ready() + if block_mask is None and draft_attention_mask is None: + raise ValueError( + "DSpineDraftModel.forward requires block_mask or draft_attention_mask " + "to keep each block causal" + ) + if kwargs.pop("use_cache", False) or kwargs.pop("past_key_values", None) is not None: + raise ValueError("DSpine reference forward requires explicit context without a draft KV cache") + if block_token_ids is None: + raise ValueError("DSpine requires block_token_ids for adjacent injection") + if noise_embedding is None: + raise ValueError("DSpine requires precomputed noise embeddings") + batch, blocks, size = block_token_ids.shape + if size != self.config.block_size or noise_embedding.shape[:2] != (batch, blocks * size): + raise ValueError("DSpine token blocks and noise embeddings must match block_size") + hidden = noise_embedding.to(context_feature.dtype) + layer_features = [] + pre_injection = None + for index, layer in enumerate(self.layers): + hidden = layer( + draft_hidden=hidden, + context_hidden=context_feature, + draft_position_ids=draft_position_ids, + context_position_ids=context_position_ids, + block_mask=block_mask, + draft_attention_mask=draft_attention_mask, + ) + pre_injection = hidden.reshape(batch, blocks, size, -1) + hidden = self.injection( + pre_injection, index, block_token_ids, self.transfer_codes, + replace_mask, + ) + layer_features.append(self.injection.feature(hidden, index)) + hidden = hidden.reshape(batch, blocks * size, -1) + return DSpineOutput( + self.final_norm(hidden).reshape(batch, blocks, size, -1), + pre_injection, + torch.stack(layer_features), + ) + + def refine( + self, hidden: torch.Tensor, predecessor_ids: torch.Tensor + ) -> torch.Tensor: + self._require_transfer_ready() + layer = len(self.layers) - 1 + receiver = self.injection.feature(hidden, layer) + predecessor = math.sqrt(self.injection.rank) * F.embedding( + predecessor_ids, self.transfer_codes + ) + return self.final_norm( + self.injection.write(hidden, receiver, predecessor, layer) + ) diff --git a/aspec/models/dspine.py b/aspec/models/dspine.py new file mode 100644 index 0000000..5b4b07b --- /dev/null +++ b/aspec/models/dspine.py @@ -0,0 +1,339 @@ +# Copyright 2026 Ant Group Co., Ltd. +# SPDX-License-Identifier: Apache-2.0 + +# Adapted from the public DSpine implementation (Tencent/DSpine, Apache-2.0) +# and the merged SpecForge DSpine training path (PR #965, corrected by PR #1038). +# Anchor sampling, block masks and the DFlash feature path stay in ASpec. +"""DSpine training objective on the DFlash block backbone.""" + +from __future__ import annotations + +from typing import List, Optional, Tuple + +import torch +import torch.nn.functional as F + +from aspec.models.dflash import ( + DFlashModel, + _create_dflash_dense_mask, + _create_dflash_mask_mod, +) +from aspec.models.ops.flex_attention import compile_friendly_create_block_mask + + +def refinement_loss( + *, scores: torch.Tensor, candidates: torch.Tensor, + target_candidates: torch.Tensor, proposal_labels: torch.Tensor, + proposal_weights: torch.Tensor, proposal_supervised: torch.Tensor, + ce_weight: float, mass_threshold: float, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """Reference refinement means, each normalized by its own eligible weight sum.""" + mass = target_candidates.sum(-1) + covered = candidates == proposal_labels.unsqueeze(-1) + ce_mask = covered.any(-1) + ce_per = F.cross_entropy( + scores.reshape(-1, candidates.shape[-1]), + covered.long().argmax(-1).reshape(-1), + reduction="none", + ).reshape(proposal_labels.shape) * ce_mask + normalized_target = target_candidates / mass.clamp_min(1e-12).unsqueeze(-1) + l1_mask = mass > mass_threshold + l1_per = ( + (torch.softmax(scores, dim=-1) - normalized_target).abs().sum(-1) * l1_mask + ) + ce_mass = (ce_mask * proposal_weights).sum() + l1_mass = (l1_mask * proposal_weights).sum() + ce_mean = (ce_per * proposal_weights).sum() / ce_mass.clamp_min(1e-12) + l1_mean = (l1_per * proposal_weights).sum() / l1_mass.clamp_min(1e-12) + refinement = ( + ce_weight * ce_mean + (1 - ce_weight) * l1_mean + ) * proposal_supervised.float().sum() + return refinement, ce_mean, l1_mean, ce_mass, l1_mass + + +class DSpineModel(DFlashModel): + """Block-parallel DFlash backbone with adjacent injection and refinement.""" + + _materialize_cpu_block_mask = True + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + config = getattr(self.draft_model, "config", None) + if getattr(config, "model_type", None) != "dspine": + raise ValueError("DSpine training requires a DSpine draft config") + if not hasattr(self.draft_model, "refine"): + raise ValueError("DSpine training requires a DSpineDraftModel") + if config.block_size != self.block_size: + raise ValueError("DSpine training block_size must match its Draft config") + if getattr(config, "is_causal", None) is not True: + raise ValueError("DSpine requires causal draft attention") + if self.mtp_conditioning is not None: + raise ValueError("DSpine does not use the native-MTP conditioning contract") + if self.draft_context_parallel_size != 1: + raise NotImplementedError( + "DSpine currently requires draft_context_parallel_size=1" + ) + if self.loss_objective != "decay": + raise ValueError("DSpine supports the decay weighting objective only") + if self.ce_loss_alpha != 1 or self.l1_loss_alpha != 0: + raise ValueError( + "DSpine replaces the CE/L1 mix with its own objective; set " + "ce_loss_alpha=1 and l1_loss_alpha=0" + ) + + def _prepare_draft_prefix( + self, input_ids, last_hidden_states, attention_mask, draft_prefix, + *packed_metadata, + ): + ctx_doc_ids, _, packed_context_positions, packed_document_lengths = packed_metadata + if any( + value is not None + for value in (ctx_doc_ids, packed_context_positions, packed_document_lengths) + ): + raise NotImplementedError( + "DSpine supports padded, non-packed inputs only; packed documents " + "or sharded context are rejected before backbone execution" + ) + return super()._prepare_draft_prefix( + input_ids, last_hidden_states, attention_mask, draft_prefix, + *packed_metadata, + ) + + def _block_mask(self, anchors, keep, seq_len, batch, attention_mask=None): + draft_len = anchors.shape[1] * self.block_size + if anchors.device.type == "cuda" and self.attention_backend == "flex_attention": + mask_mod = _create_dflash_mask_mod( + anchor_positions=anchors, + block_keep_mask=keep, + ctx_len=seq_len, + block_size=self.block_size, + is_causal=True, + attention_mask=attention_mask, + ) + return compile_friendly_create_block_mask( + mask_mod=mask_mod, B=batch, H=None, + Q_LEN=draft_len, KV_LEN=seq_len + draft_len, + device=anchors.device, + ), None + if self.attention_backend not in {"sdpa", "eager"}: + raise NotImplementedError( + "DSpine CPU/reference execution supports sdpa/eager only" + ) + return None, _create_dflash_dense_mask( + anchors, keep, seq_len, self.block_size, is_causal=True, + attention_mask=attention_mask, + ) + + def forward( + self, + input_ids: torch.Tensor, + hidden_states_list: List[torch.Tensor] | torch.Tensor, + loss_mask: torch.Tensor, + lm_head_weight: torch.Tensor, + last_hidden_states: Optional[torch.Tensor] = None, + ctx_doc_ids: Optional[torch.Tensor] = None, + base_position_ids: Optional[torch.Tensor] = None, + packed_context_positions: Optional[torch.Tensor] = None, + injected_anchors: Optional[torch.Tensor] = None, + injected_keep_mask: Optional[torch.Tensor] = None, + anchor_seed: Optional[int] = None, + packed_document_lengths: Optional[tuple[int, ...]] = None, + attention_mask: Optional[torch.Tensor] = None, + draft_prefix=None, + global_step: int = 0, + total_steps: int | None = None, + alignment_ce: Optional[torch.Tensor] = None, + ) -> Tuple[ + torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, + dict, Tuple[torch.Tensor, torch.Tensor], + ]: + if last_hidden_states is None: + raise ValueError( + "DSpine requires Target last_hidden_states for its teacher distribution" + ) + self._prepare_draft_prefix( + input_ids, last_hidden_states, attention_mask, draft_prefix, + ctx_doc_ids, base_position_ids, packed_context_positions, + packed_document_lengths, + ) + bsz, seq_len = input_ids.shape + device = input_ids.device + anchors, keep = self._sample_anchor_positions( + seq_len, loss_mask, device, ctx_doc_ids=ctx_doc_ids, + injected_anchors=injected_anchors, + injected_keep_mask=injected_keep_mask, + anchor_seed=anchor_seed, + packed_document_lengths=packed_document_lengths, + attention_mask=attention_mask, + ) + n_blocks = anchors.shape[1] + offsets = torch.arange(self.block_size, device=device).view(1, 1, -1) + label_indices = anchors.unsqueeze(-1) + offsets + safe_indices = label_indices.clamp(max=seq_len - 1) + labels = torch.gather( + input_ids.unsqueeze(1).expand(-1, n_blocks, -1), 2, safe_indices + ) + supervised = ( + (label_indices < seq_len) + & keep.unsqueeze(-1) + & ( + torch.gather( + loss_mask.unsqueeze(1).expand(-1, n_blocks, -1), + 2, + safe_indices, + ) + > 0.5 + ) + ) + # The anchor row is context; only proposal positions 1..block_size-1 are supervised. + supervised = supervised[..., 1:].int().cumprod(dim=-1).bool() + weights = supervised.float() + if self.loss_decay_gamma is not None and self.loss_decay_gamma > 0: + proposal_depth = torch.arange( + self.block_size - 1, device=device, dtype=torch.float32 + ) + weights = weights * torch.exp(-proposal_depth / self.loss_decay_gamma) + + if not bool(self.draft_model.transfer_ready): + self.draft_model.initialize_transfer_space(lm_head_weight) + context_feature = self.draft_model.extract_context_feature(hidden_states_list) + noise = self._create_noise_embed(input_ids, anchors, keep) + context_pos, draft_pos = self._create_position_ids( + anchors, seq_len, base_position_ids=base_position_ids + ) + block_mask, dense_mask = self._block_mask( + anchors, keep, seq_len, bsz, attention_mask=attention_mask + ) + beta, replacement_probability = self.draft_model.dspine_config.schedule( + int(global_step), total_steps + ) + replace = None + if self.training and replacement_probability > 0: + replace = ( + torch.rand(anchors.shape, device=device) < replacement_probability + ) & keep + output = self.draft_model( + context_feature=context_feature, + draft_position_ids=draft_pos, + context_position_ids=context_pos, + block_mask=block_mask, + noise_embedding=noise, + block_token_ids=labels, + replace_mask=replace, + draft_attention_mask=dense_mask, + ) + + proposal_labels = labels[..., 1:].reshape(-1, self.block_size - 1) + proposal_weights = weights.reshape(-1, self.block_size - 1) + proposal_supervised = supervised.reshape(-1, self.block_size - 1) + hidden = output.hidden_states[..., 1:, :].reshape( + -1, self.block_size - 1, output.hidden_states.shape[-1] + ) + draft_logits = F.linear(hidden, lm_head_weight) + ce_per_token = F.cross_entropy( + draft_logits.reshape(-1, draft_logits.shape[-1]), + proposal_labels.reshape(-1), + reduction="none", + ).reshape(proposal_labels.shape) + flat_weights = proposal_weights.reshape(-1) + token_denominator = flat_weights.sum() + ce = (ce_per_token * proposal_weights).sum() + + target_indices = (safe_indices[..., 1:] - 1).clamp_min(0) + teacher_hidden = torch.gather( + last_hidden_states, 1, + target_indices.reshape(bsz, -1, 1).expand( + -1, -1, last_hidden_states.shape[-1] + ), + ).reshape(-1, self.block_size - 1, last_hidden_states.shape[-1]) + teacher_logits = F.linear(teacher_hidden, lm_head_weight) + teacher_probs = torch.softmax(teacher_logits.float(), dim=-1) + draft_probs = torch.softmax(draft_logits.float(), dim=-1) + l1 = ((draft_probs - teacher_probs).abs().sum(-1) * proposal_weights).sum() + + config = self.draft_model.dspine_config + # Inference refines the draft's own shortlist; the teacher only supplies + # probabilities for those candidate IDs. + candidates = draft_logits.topk(config.top_k, dim=-1).indices + pre_injection = output.pre_injection[..., 1:, :].reshape( + -1, self.block_size - 1, output.pre_injection.shape[-1] + ) + predecessors = labels[..., :-1].reshape(-1, self.block_size - 1) + refined = self.draft_model.refine(pre_injection, predecessors) + candidate_embeds = F.embedding(candidates, lm_head_weight) + scores = (refined.unsqueeze(-2) * candidate_embeds).sum(-1).float() + target_candidates = teacher_probs.gather(-1, candidates) + refinement, ref_ce, ref_l1, ref_ce_mass, ref_l1_mass = refinement_loss( + scores=scores, + candidates=candidates, + target_candidates=target_candidates, + proposal_labels=proposal_labels, + proposal_weights=proposal_weights, + proposal_supervised=proposal_supervised, + ce_weight=config.ce_weight, + mass_threshold=config.candidate_mass_threshold, + ) + + reference_codes = F.embedding( + proposal_labels, self.draft_model.transfer_codes + ).float() + layer_features = ( + output.layer_features[..., 1:, :] + .permute(1, 2, 3, 0, 4) + .reshape(-1, self.block_size - 1, output.layer_features.shape[0], + output.layer_features.shape[-1]) + ) + alignment = 1 - F.cosine_similarity( + layer_features.float(), reference_codes.unsqueeze(2), dim=-1 + ) + alignment = (alignment.mean(dim=-1) * proposal_weights).sum() + if alignment_ce is None: + alignment_ce = ce.detach() / token_denominator.clamp_min(1e-12) + alignment_ce = alignment_ce.detach() + numerator = ( + config.ce_weight * ce + + (1 - config.ce_weight) * l1 + + refinement + + beta * alignment_ce * alignment + ) + sequence_denominator = torch.tensor( + float(bsz), device=device, dtype=numerator.dtype + ) + loss = numerator / sequence_denominator + + with torch.no_grad(): + binary = proposal_supervised.float() + count = binary.sum().clamp(min=1.0) + correct = ( + (draft_logits.argmax(-1) == proposal_labels) & (binary > 0.5) + ) + accuracy = correct.float().sum() / count + count_pp = binary.sum(dim=0) + loss_pp = (ce_per_token * binary).sum(dim=0) / count_pp.clamp(min=1.0) + acc_pp = correct.float().sum(dim=0) / count_pp.clamp(min=1.0) + loss_per_position = torch.cat( + (loss_pp.new_zeros(1), loss_pp) + ) + acc_per_position = torch.cat( + (acc_pp.new_zeros(1), acc_pp) + ) + count_per_position = torch.cat( + (proposal_weights.new_zeros(1), count_pp) + ) + components = { + "dspine/backbone_ce": (ce.detach(), token_denominator.detach()), + "dspine/backbone_l1": (l1.detach(), token_denominator.detach()), + "dspine/refinement_ce": (ref_ce, ref_ce_mass), + "dspine/refinement_l1": (ref_l1, ref_l1_mass), + "dspine/refinement_loss": (refinement.detach(), sequence_denominator), + "dspine/alignment_loss": (alignment.detach(), token_denominator.detach()), + "dspine/alignment_ce": (alignment_ce, sequence_denominator), + "dspine/replacement_probability": ( + torch.tensor(replacement_probability, device=device), + torch.tensor(1.0, device=device), + ), + } + return ( + loss, accuracy, loss_per_position, acc_per_position, + count_per_position, components, (numerator, sequence_denominator.detach()), + ) diff --git a/aspec/models/ops/anchors.py b/aspec/models/ops/anchors.py index f0eeffb..df52bde 100644 --- a/aspec/models/ops/anchors.py +++ b/aspec/models/ops/anchors.py @@ -45,10 +45,19 @@ def _candidates(seq_len: int, loss_mask: torch.Tensor, block_size: int, device: if attention_mask.shape != loss_mask.shape: raise ValueError("Anchor attention_mask and loss_mask must have identical shapes") # Padded BSHD rows must have the same candidate domain as their native - # unpadded documents. Physical batch/bucket padding is not context. - valid = valid & attention_mask[:, :num_candidates].bool() & attention_mask[ - :, block_size - 1:block_size - 1 + num_candidates - ].bool() & attention_mask[:, block_size:block_size + 1].bool() + # unpadded documents. Physical batch/bucket padding is not context, so + # require the whole anchor block to lie inside each row's valid span. + mask = attention_mask.to(device=device).bool() + valid = valid & mask[:, :num_candidates] + if block_size > 1: + prefix = torch.cat( + (mask.new_zeros((mask.shape[0], 1)), mask.cumsum(dim=1)), dim=1 + ) + counts = ( + prefix[:, block_size:block_size + num_candidates] + - prefix[:, :num_candidates] + ) + valid = valid & (counts == block_size) indices = torch.arange(num_candidates, device=device).unsqueeze(0).expand(bsz, -1) return num_candidates, valid, valid.sum(dim=1), torch.where(valid, indices, seq_len + 1) diff --git a/docs/framework/REFERENCES.md b/docs/framework/REFERENCES.md index 838df17..ba4b6e4 100644 --- a/docs/framework/REFERENCES.md +++ b/docs/framework/REFERENCES.md @@ -27,6 +27,8 @@ the retained source identities; applicable license and notice texts are distribu | [Speculators](https://github.com/vllm-project/speculators) `3702320434bbdaa853f0846a66e6b6b8f1d97aec` | Adapted P-EAGLE model/loss and Qwen3 first-layer fusion; deterministic dense layout and ASpec input/observation boundary | | [Domino](https://github.com/jianuo-huang/Domino) `44e1e6912ba9d301899739a54bfda2ce8826980a` and [arXiv:2605.29707](https://arxiv.org/abs/2605.29707) | Public method and label-layout reference for the GRU correction head; independently implemented on the retained DFlash block backbone | | [SpecForge Domino](https://github.com/sgl-project/SpecForge/pull/571) merge `7de39e32fc845caf59bca9841595145d24e1796f` | Adapted Domino objective, predecessor alignment and label-shift handling (MIT); ASpec supplies configuration, fail-closed scope and DFlash integration | +| [DSpine](https://github.com/Tencent/DSpine) `75cade7ab0307fc2daac8eda95337705226b217e` and [arXiv:2609.36173](https://arxiv.org/abs/2609.36173) | Public method, architecture, transfer-code and refinement reference; independently implemented on the retained DFlash block backbone | +| [SpecForge DSpine](https://github.com/sgl-project/SpecForge/pull/965) merge `eaa6b03f6b4a65f38954fa0ebc13e59a8f295d02`, corrected by PR #1038 merge `1b5c0dde137a28447606ffb6078e01eddfa77980` | Adapted adjacent-injection/refinement objective normalization (MIT); ASpec supplies configuration, fail-closed scope and DFlash integration | | [Ling-3.0-flash](https://huggingface.co/inclusionAI/Ling-3.0-flash) `fcc60a52b34c69c6271d0ac8a8cb0815020b6a43` | Adapted MoE routing and independently retained reference class bodies; Apache-2.0 source headers preserved | | [EAGLE](https://github.com/SafeAILab/EAGLE), [GPT-NeoX](https://github.com/EleutherAI/gpt-neox) and Transformers through TorchSpec | Model/data helpers in `aspec/models/draft/base.py`, shared checkpoint reads in `aspec/models/checkpoint.py`, and `aspec/data/preprocessing.py`; original source headers retain the transitive attribution | diff --git a/docs/support.md b/docs/support.md index ee34c00..56dd9ec 100644 --- a/docs/support.md +++ b/docs/support.md @@ -13,6 +13,7 @@ and tests do not imply CPU training support. | EAGLE3 | Recurrent TTT, full/pruned vocabulary, GQA/MHA or materialized MLA; FA4 packing/CP | No EAGLE3 MoE, anchored mode or whole-model compile | | P-EAGLE core | Qwen3 full-vocabulary parallel model/loss, deterministic dense slots, eager/SDPA | Model/loss prerequisite only; no public trainer, COD sampler, resume, export or consumer validation; see [scope](user-guide/peagle.md) | | Domino | DFlash block backbone plus GRU causal correction head, mixed backbone/corrected CE, both documented label layouts; training, `lambda_base` curriculum, held-out corrected/backbone observations and exact recovery with FlexAttention, CP1, padded/non-packing | No packed/CP>1, MoE, sparse attention or MTP conditioning; SGLang/native export, strict reload, proposal consumer, a bounded SpecForge comparison and bounded SGLang decode acceptance are validated; harder data, longer convergence and a formal anchor-replay training mode remain pending; see [scope](user-guide/domino.md) | +| DSpine | DFlash block backbone plus adjacent-token injection, persistent transfer codes, last-write refinement and alignment/refinement objectives; dense full attention, padded, CP1, non-packing | Model/loss prerequisite only; no public trainer, exact-resume, recipe, export or consumer/acceptance validation; see [scope](user-guide/dspine.md) | | Medusa heads-only | Parallel full-vocabulary future-token heads on the frozen Target post-norm state; training, exact recovery and native export; greedy and typical/nucleus sampling candidate-tree acceptance via a standalone Hugging Face evaluator; SDPA CP1, MBS1, non-packing, REPLICATE, one node | No packing/CP or warmstart; no SGLang Medusa integration or production-serving claim; see [scope](user-guide/medusa.md) | | EAGLE4 | Dense and selected upstream MoE; Draft/candidate stages; packing/CP and native assets | Candidate Top-K forward-KL is explicitly implemented from public semantics, not an unpublished official recipe; no serving integration | | DFlash2 | Experimental full/causal/SWA training with Flex, cuDNN THD or FA4 packing/CP | Experimental objective; no claim to reproduce an official training recipe | diff --git a/docs/user-guide/algorithms.md b/docs/user-guide/algorithms.md index 7d433e4..f7432d1 100644 --- a/docs/user-guide/algorithms.md +++ b/docs/user-guide/algorithms.md @@ -74,6 +74,16 @@ examples (FlexAttention, CP1, non-packing, Store/TCP). The trainer supports a li Scope is dense full attention with padded inputs only. Native export, recipe catalog promotion, Target bindings and consumer/acceptance validation remain pending. +## DSpine + +The [DSpine model/loss API](dspine.md) adds adjacent-token injection, persistent +transfer codes and last-write candidate refinement on the retained DFlash block +backbone. The objective combines backbone CE/L1, refinement CE/L1 and a +transfer-code alignment term with an explicit warmup/replacement schedule. This +increment is model/loss only: dense full attention, padded inputs, CP1 and +non-packing. Trainer, recipe, exact resume, export and consumer/acceptance +validation remain pending. + ## EAGLE4: two stages The Draft stage trains the full recurrent model. The candidate stage freezes the entire Draft, diff --git a/docs/user-guide/dspine.md b/docs/user-guide/dspine.md new file mode 100644 index 0000000..2ce10f4 --- /dev/null +++ b/docs/user-guide/dspine.md @@ -0,0 +1,58 @@ +# DSpine Draft model and objective + +This is the model/loss prerequisite for [ASpec #37](https://github.com/inclusionAI/ASpec/issues/37). +It adds DSpine adjacent-token injection, persistent transfer codes and candidate +refinement on the retained DFlash block backbone. Trainer, recipe, exact resume, +export and serving are follow-ups; this page describes the tested model/loss scope +only. + +## References + +- [Tencent/DSpine](https://github.com/Tencent/DSpine) @ + `75cade7ab0307fc2daac8eda95337705226b217e` for the architecture, inference + implementation and published checkpoint layout. +- [SpecForge DSpine training](https://github.com/sgl-project/SpecForge/pull/965) + merge `eaa6b03f6b4a65f38954fa0ebc13e59a8f295d02` and the objective corrections in + [PR #1038](https://github.com/sgl-project/SpecForge/pull/1038) merge + `1b5c0dde137a28447606ffb6078e01eddfa77980`. +- SpecForge [issue #1170](https://github.com/sgl-project/SpecForge/issues/1170) + documents a stale-config hazard when replacing a draft config after construction. + ASpec reads the resolved `DSpineConfig` at use time and does not need a mutable + online-model alias. + +## Selected scope + +The first implementation targets one dense full-attention DFlash backbone such as +Qwen3-8B with padded inputs, `draft_context_parallel_size=1` and no packing. Native +MTP conditioning, MoE FFNs, sparse attention, packed documents and CP>1 fail closed. + +## Components + +- `DSpineConfig(DFlashConfig)` requires causal draft attention and validates the + transfer rank, message size, top-k width, replacement schedule and alignment + weights. +- `AdjacentInjection` owns the persistent `transfer_codes` table, per-layer readouts, + gated predecessor messages and per-layer feature writes. Each block's anchor code + and the previous position's feature condition the next position's write. +- `DSpineDraftModel.initialize_transfer_space` builds whitened token codes and + readout directions from the frozen Target output head. +- `DSpineDraftModel.refine` applies the exact last-write refinement used for candidate + rescoring. +- `DSpineModel` reuses ASpec anchor sampling, block masks, Target features and DFlash + reductions. It adds backbone CE/L1, candidate refinement CE/L1, transfer-code + alignment, the alignment warmup and the predecessor-replacement schedule. + +The current objective is dense full attention, padded, CP1, non-packing. The +trainer-side accumulation replay and exact-resume contract are not part of this +increment. + +## Validation and limits + +`tests/cpu/test_dspine.py` covers configuration fail-closed cases, transfer-space +initialization, finite forward/backward, adjacent-injection causality and packed-input +rejection. CPU numerical contracts do not establish Qwen3-8B convergence, GPU +throughput or decoding acceptance. + +The published DSpine checkpoint layout uses a `dflash_config` code bridge and a +serving-specific candidate sampler. Mapping those fields, trainer wiring, export, +consumer/acceptance and a bounded SpecForge comparison are follow-up work. diff --git a/tests/cpu/test_dspine.py b/tests/cpu/test_dspine.py new file mode 100644 index 0000000..e4b8849 --- /dev/null +++ b/tests/cpu/test_dspine.py @@ -0,0 +1,315 @@ +# Copyright 2026 Ant Group Co., Ltd. +# SPDX-License-Identifier: Apache-2.0 + +"""DSpine model/injection/loss contracts on CPU.""" + +import pytest +import torch + +from aspec.models.draft.dspine import ( + AdjacentInjection, + DSpineConfig, + DSpineDraftModel, + DSpineOptions, +) +from aspec.models.dspine import DSpineModel, refinement_loss +from aspec.models.ops.anchors import sample_anchor_positions + + +def make_config(**overrides): + raw = dict( + hidden_size=16, + intermediate_size=32, + num_hidden_layers=2, + num_attention_heads=2, + num_key_value_heads=1, + head_dim=8, + vocab_size=32, + num_target_layers=1, + target_hidden_size=16, + target_num_hidden_layers=4, + target_layer_ids=[1], + mask_token_id=31, + max_position_embeddings=128, + block_size=4, + dspine_config={ + "transfer_rank": 8, + "message_size": 8, + "top_k": 4, + "alignment_warmup_steps": 0, + "replacement_layers": 1, + "replacement_probability": 0.0, + }, + ) + raw.update(overrides) + return DSpineConfig(**raw) + + +def make_model(config=None): + config = config or make_config() + draft = DSpineDraftModel(config) + draft.freeze_embedding() + return DSpineModel( + draft, block_size=config.block_size, num_anchors=2, + attention_backend="sdpa", + ) + + +def make_inputs(seed=0, length=12, batch=1): + generator = torch.Generator().manual_seed(seed) + return { + "input_ids": torch.randint(0, 31, (batch, length), generator=generator), + "hidden_states_list": torch.randn(batch, length, 16, generator=generator), + "loss_mask": torch.ones(batch, length), + "lm_head_weight": torch.randn(32, 16, generator=generator), + "last_hidden_states": torch.randn(batch, length, 16, generator=generator), + } + + +def test_config_fails_closed_on_non_causal_and_invalid_rank(): + with pytest.raises(ValueError, match="causal"): + make_config(is_causal=False) + with pytest.raises(ValueError, match="transfer_rank"): + make_config(dspine_config={"transfer_rank": 32}) + with pytest.raises(ValueError, match="block_size"): + make_config(block_size=1) + + +def test_forward_initializes_transfer_space_and_backpropagates(): + torch.manual_seed(3) + model = make_model() + inputs = make_inputs() + loss, accuracy, loss_pp, acc_pp, count_pp, components, terms = model( + **inputs, global_step=0, total_steps=1, + ) + + assert torch.isfinite(loss) + assert loss_pp.shape == acc_pp.shape == count_pp.shape == (4,) + assert loss_pp[0] == 0 and acc_pp[0] == 0 + assert torch.equal(count_pp[0], torch.tensor(0.0)) + assert bool(model.draft_model.transfer_ready) + assert model.draft_model.transfer_codes.shape == (32, 8) + assert "dspine/backbone_ce" in components + assert terms[1] > 0 + + loss.backward() + gradients = [p.grad for p in model.parameters() if p.requires_grad] + assert gradients and all(g is not None and torch.isfinite(g).all() for g in gradients) + + +def test_transfer_space_codes_are_normalized_and_readouts_use_pca(): + model = make_model() + head = torch.randn(32, 16) + model.draft_model.initialize_transfer_space(head) + norms = torch.linalg.vector_norm(model.draft_model.transfer_codes.float(), dim=-1) + torch.testing.assert_close(norms, torch.ones_like(norms), atol=1e-4, rtol=1e-4) + for readout in model.draft_model.injection.readouts: + assert readout.weight.shape == (8, 16) + assert torch.isfinite(readout.weight).all() + + +def test_adjacent_injection_does_not_leak_future_tokens_backwards(): + options = DSpineOptions( + transfer_rank=8, message_size=8, top_k=4, + alignment_warmup_steps=0, replacement_layers=1, + replacement_probability=0.0, + ) + injection = AdjacentInjection(16, 1, options) + _randomize_injection(injection) + generator = torch.Generator().manual_seed(11) + hidden = torch.randn(1, 1, 4, 16, generator=generator) + token_ids = torch.randint(0, 32, (1, 1, 4), generator=generator) + codes = torch.randn(32, 8, generator=generator) + + replace = torch.ones(1, 1, dtype=torch.bool) + first = injection(hidden, 0, token_ids, codes, replace) + changed = hidden.clone() + changed[..., -1, :] += 10.0 + second = injection(changed, 0, token_ids, codes, replace) + + torch.testing.assert_close(first[..., :-1, :], second[..., :-1, :], atol=0, rtol=0) + assert not torch.equal(first[..., -1, :], second[..., -1, :]) + + predecessor_changed = token_ids.clone() + predecessor_changed[..., 1] = (predecessor_changed[..., 1] + 1) % 32 + third = injection(hidden, 0, predecessor_changed, codes, replace) + torch.testing.assert_close(first[..., :2, :], third[..., :2, :], atol=0, rtol=0) + assert not torch.equal(first[..., 2, :], third[..., 2, :]) + + +def _randomize_injection(injection, seed=31): + generator = torch.Generator().manual_seed(seed) + with torch.no_grad(): + for write in injection.writes: + write.weight.copy_(torch.randn(write.weight.shape, generator=generator) * 0.1) + injection.predecessor_gate.weight.copy_( + torch.randn(injection.predecessor_gate.weight.shape, generator=generator) * 0.1 + ) + + +def _reference_injection(injection, hidden, layer, token_ids, codes, replace): + import math + + import torch.nn.functional as F + + features = injection.feature(hidden, layer) + anchor = math.sqrt(injection.rank) * F.embedding(token_ids[..., :1], codes) + predecessors = torch.cat((anchor, features[..., 1:-1, :]), dim=-2) + if replace is not None and layer < injection.replacement_layers: + correct = math.sqrt(injection.rank) * F.embedding(token_ids[..., :-1], codes) + predecessors = torch.where(replace[..., None, None], correct, predecessors) + gate = torch.sigmoid( + injection.receiver_gate(features[..., 1:, :]) + + injection.predecessor_gate(predecessors) + + injection.bias + ) + delta = injection.writes[layer](gate * injection.message(predecessors)) + scale = ( + torch.linalg.vector_norm(hidden[..., 1:, :].float(), dim=-1, keepdim=True) + / math.sqrt(hidden.shape[-1]) + ).to(hidden.dtype) + return torch.cat((hidden[..., :1, :], hidden[..., 1:, :] + scale * delta), dim=-2) + + +def test_adjacent_injection_matches_independent_equation(): + options = DSpineOptions( + transfer_rank=8, message_size=8, top_k=4, + alignment_warmup_steps=0, replacement_layers=1, + replacement_probability=0.0, + ) + injection = AdjacentInjection(16, 2, options) + _randomize_injection(injection) + generator = torch.Generator().manual_seed(19) + hidden = torch.randn(1, 2, 4, 16, generator=generator) + token_ids = torch.randint(0, 32, (1, 2, 4), generator=generator) + codes = torch.randn(32, 8, generator=generator) + replace = torch.tensor([[True, False]]) + + actual = injection(hidden, 0, token_ids, codes, replace) + expected = _reference_injection(injection, hidden, 0, token_ids, codes, replace) + torch.testing.assert_close(actual, expected, atol=1e-6, rtol=1e-6) + + +def test_refine_matches_independent_equation(): + model = make_model() + model.draft_model.initialize_transfer_space(torch.randn(32, 16)) + generator = torch.Generator().manual_seed(23) + hidden = torch.randn(1, 2, 3, 16, generator=generator) + predecessors = torch.randint(0, 32, (1, 2, 3), generator=generator) + layer = len(model.draft_model.layers) - 1 + _randomize_injection(model.draft_model.injection) + actual = model.draft_model.refine(hidden, predecessors) + import math + + import torch.nn.functional as F + + receiver = model.draft_model.injection.feature(hidden, layer) + codes = math.sqrt(model.draft_model.injection.rank) * F.embedding( + predecessors, model.draft_model.transfer_codes + ) + expected = model.draft_model.final_norm( + model.draft_model.injection.write(hidden, receiver, codes, layer) + ) + torch.testing.assert_close(actual, expected, atol=1e-6, rtol=1e-6) + + +def test_refinement_loss_is_zero_for_equal_candidate_distributions(): + scores = torch.tensor([[[2.0, 1.0, 0.0], [2.0, 1.0, 0.0]]]) + target = torch.softmax(scores, dim=-1) + candidates = torch.tensor([[[4, 5, 6], [4, 5, 6]]]) + labels = torch.tensor([[4, 4]]) + weights = torch.ones_like(labels, dtype=torch.float32) + supervised = torch.ones_like(labels, dtype=torch.float32) + refinement, ref_ce, ref_l1, ce_mass, l1_mass = refinement_loss( + scores=scores, candidates=candidates, target_candidates=target, + proposal_labels=labels, proposal_weights=weights, + proposal_supervised=supervised, + ce_weight=0.1, mass_threshold=1e-4, + ) + assert ref_l1 == 0 + assert ce_mass == l1_mass == weights.sum() + torch.testing.assert_close(refinement, 0.1 * ref_ce * supervised.sum()) + + +def test_draft_forward_requires_a_block_or_dense_mask(): + model = make_model() + model.draft_model.initialize_transfer_space(torch.randn(32, 16)) + with pytest.raises(ValueError, match="block_mask or draft_attention_mask"): + model.draft_model( + context_feature=torch.randn(1, 12, 16), + draft_position_ids=torch.zeros(1, 8, dtype=torch.long), + context_position_ids=torch.zeros(1, 12, dtype=torch.long), + noise_embedding=torch.randn(1, 8, 16), + block_token_ids=torch.randint(0, 32, (1, 2, 4)), + ) + + +def test_block_mask_excludes_left_padding_but_keeps_valid_context(): + model = make_model() + anchors = torch.tensor([[4], [4]]) + keep = torch.ones(2, 1, dtype=torch.bool) + attention = torch.tensor([ + [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + ]) + _, dense = model._block_mask( + anchors, keep, attention.shape[1], 2, attention_mask=attention + ) + assert dense.shape == (2, 4, 16) + assert not dense[0, :, 0].any() + assert not dense[0, :, 1].any() + assert dense[0, :, 2].any() + assert dense[1, :, 0].any() + _, no_mask_dense = model._block_mask( + anchors, keep, attention.shape[1], 2, attention_mask=None + ) + assert no_mask_dense[..., 0].any() + + +def test_anchor_sampling_is_stable_under_left_and_right_padding(): + block_size = 4 + num_anchors = 2 + real_length = 7 + device = torch.device("cpu") + base_mask = torch.ones(1, real_length) + generator = torch.Generator(device=device).manual_seed(11) + base, base_keep = sample_anchor_positions( + real_length, base_mask, num_anchors, block_size, device, + generator=generator, + ) + + left_mask = torch.zeros(1, real_length + 5) + left_mask[:, 5:] = 1 + left_attention = left_mask.clone() + generator = torch.Generator(device=device).manual_seed(11) + left, left_keep = sample_anchor_positions( + real_length + 5, left_mask, num_anchors, block_size, device, + generator=generator, attention_mask=left_attention, + ) + assert left_keep.sum() == base_keep.sum() == num_anchors + assert (left[left_keep] - 5).tolist() == base[base_keep].tolist() + + right_mask = torch.zeros(1, real_length + 5) + right_mask[:, :real_length] = 1 + right_attention = right_mask.clone() + generator = torch.Generator(device=device).manual_seed(11) + right, right_keep = sample_anchor_positions( + real_length + 5, right_mask, num_anchors, block_size, device, + generator=generator, attention_mask=right_attention, + ) + assert right_keep.sum() == base_keep.sum() == num_anchors + assert right[right_keep].tolist() == base[base_keep].tolist() + + +def test_loss_terms_use_sequence_count_as_the_additive_denominator(): + model = make_model() + inputs = make_inputs(batch=2) + *_, terms = model(**inputs, global_step=0, total_steps=1) + assert torch.equal(terms[1], torch.tensor(2.0)) + + +def test_packed_inputs_are_rejected_before_backbone(): + model = make_model() + inputs = make_inputs() + with pytest.raises(NotImplementedError, match="padded, non-packed"): + model(**inputs, ctx_doc_ids=torch.zeros_like(inputs["input_ids"]))