Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / ops / _dsa_layout.py: 88%
50 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
1# Copyright 2026 Huawei Technologies Co., Ltd
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ============================================================================
15"""Shared logical document coordinates for the DSA operator families."""
17from __future__ import annotations
19from collections.abc import Callable
20from dataclasses import dataclass
22import torch
25Segment = tuple[int, int, int, int, int]
26ReduceSum = Callable[[torch.Tensor], torch.Tensor]
29@dataclass(frozen=True)
30class DsaQueryLayout:
31 """Logical document geometry in raw-query and compressed-key coordinates.
33 Each segment stores local query start/end, document key start/prefix end,
34 and the trailing raw tokens after the last complete block. Tensor starts
35 and bounds represent the same geometry for graph packing and eager reuse.
36 """
38 compress_ratio: int = 1
39 query_offset: int = 0
40 segments: tuple[Segment, ...] | None = None
41 segment_starts: torch.Tensor | None = None
42 minimum_key_indices: torch.Tensor | None = None
43 causal_upper: torch.Tensor | None = None
45 def raw_document_starts(self) -> tuple[tuple[int, int], ...]:
46 """Derive the raw token origin of each query segment."""
47 ratio = max(1, self.compress_ratio)
48 return tuple(
49 (start, self.query_offset + end - (key_end - key_start) * ratio - residual)
50 for start, end, key_start, key_end, residual in self.segments or ()
51 )
53 def compressed_bounds(self, query: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor | None]:
54 """Return each query's valid range in the compressed key bank."""
55 return _causal_key_bounds(
56 query, self.compress_ratio, self.query_offset, self.minimum_key_indices, self.segments, self.causal_upper,
57 )
60def _causal_key_bounds(
61 query: torch.Tensor, ratio: int, query_offset: int,
62 minimum_key_indices: torch.Tensor | None, segments: tuple | None,
63 causal_upper: torch.Tensor | None = None,
64) -> tuple[torch.Tensor, torch.Tensor | None]:
65 """Derive visibility from original query positions within each independently compressed document.
67 The returned upper bound always has shape ``[1, queries]`` (shared across
68 the batch), so chunked consumers slice it along the sequence dimension.
69 ``causal_upper`` is the packed per-query exclusive bound shared by eager and
70 graph execution; Python ``segments`` remain available for eager callers and
71 the fused native kernels.
72 """
73 batch_size, length = query.shape[:2]
74 if causal_upper is not None:
75 return causal_upper, minimum_key_indices
76 if segments is None:
77 positions = torch.arange(query_offset, query_offset + length, device=query.device)
78 return ((positions + 1) // ratio).unsqueeze(0), minimum_key_indices
79 upper = torch.empty(length, device=query.device, dtype=torch.long)
80 lower = torch.empty_like(upper)
81 for begin, end, key_start, key_end, residual in segments:
82 first = ratio * key_end + residual - (end - begin)
83 positions = torch.arange(first, first + end - begin, device=query.device)
84 upper[begin:end] = (positions + 1) // ratio
85 lower[begin:end] = key_start
86 return upper.unsqueeze(0), lower.unsqueeze(0).expand(batch_size, -1)
89def packed_segments(
90 query_ends: torch.Tensor, key_ends: torch.Tensor,
91) -> tuple[tuple[int, int, int, int], ...]:
92 """Return query/key ranges for packed documents from cumulative ends."""
93 q_ends, k_ends = query_ends.tolist(), key_ends.tolist()
94 if len(q_ends) != len(k_ends):
95 raise ValueError("Packed DSA query and key lengths must describe the same documents")
96 return tuple(zip([0, *q_ends[:-1]], q_ends, [0, *k_ends[:-1]], k_ends))
99def packed_causal_mask(query: torch.Tensor, key: torch.Tensor) -> torch.Tensor:
100 """Return the right-aligned causal mask for a single DSA document."""
101 q_pos = torch.arange(query.shape[0], device=query.device) + key.shape[0] - query.shape[0]
102 return torch.arange(key.shape[0], device=query.device)[None, :] <= q_pos[:, None]
105def selected_packed_keys(
106 key: torch.Tensor, indices: torch.Tensor, *, causal_end: torch.Tensor,
107) -> tuple[torch.Tensor, torch.Tensor]:
108 """Gather document-local key IDs in T,N,K,D layout and return validity."""
109 valid = (indices >= 0) & (indices < key.shape[0]) & (indices <= causal_end[:, None, None])
110 positions = indices.clamp(0, max(0, key.shape[0] - 1)).long()
111 heads = torch.arange(key.shape[1], device=key.device)[None, :, None]
112 return key[positions, heads], valid
115def selected_packed_scores(query: torch.Tensor, keys: torch.Tensor) -> torch.Tensor:
116 """Dot grouped query heads and selected keys in T,N,G,K layout."""
117 grouped = query.unflatten(1, (keys.shape[1], -1))
118 return torch.einsum("tngd,tnkd->tngk", grouped.float(), keys.float())