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"""Document boundaries and packed CSA2 coordinates."""
16
17from __future__ import annotations
18
19from dataclasses import dataclass, field
20from typing import Any
21from functools import lru_cache
22
23import torch
24from torch.utils._pytree import register_pytree_node
25
26
27
28@dataclass(frozen=True)
29class DocumentBlockPlan:
30 """Complete compression blocks in one local document bank."""
31
32 ratio: int
33 blocks: tuple[tuple[int, int], ...]
34
35 def indices(self, device: torch.device) -> tuple[torch.Tensor, torch.Tensor]:
36 """Return pooling rows and original block-start positions."""
37 return _document_block_indices(self, device)
38
39
40@lru_cache(maxsize=8)
41@torch.inference_mode(False)
42def _document_block_indices(plan: DocumentBlockPlan, device: torch.device) -> tuple:
43 starts = [torch.arange(start, start + count * plan.ratio, plan.ratio, device=device)
44 for start, count in plan.blocks]
45 starts = torch.cat(starts) if starts else torch.empty(0, device=device, dtype=torch.long)
46 rows = (starts.unsqueeze(1) + torch.arange(plan.ratio, device=device)).flatten()
47 return rows.long(), starts.long()
48
49
50@dataclass(frozen=True)
51class SharedCompressedPackedSequence:
52 """Compact sample boundaries for one contiguous CP query shard."""
53
54 cu_seq_lens: torch.Tensor
55 local_query_start: int
56 local_query_length: int
57 global_sequence_length: int
58 _prepared_starts: dict[torch.device, torch.Tensor] = field(
59 default_factory=dict, init=False, repr=False, compare=False
60 )
61 _prepared_minima: dict[tuple[torch.device, int], torch.Tensor] = field(
62 default_factory=dict, init=False, repr=False, compare=False
63 )
64 _prepared_bounds: dict[tuple[torch.device, int], torch.Tensor] = field(
65 default_factory=dict, init=False, repr=False, compare=False
66 )
67 _packing_alignment: int = field(default=0, init=False, repr=False, compare=False)
68 _compression_rope: dict[int, tuple] = field(default_factory=dict, init=False, repr=False, compare=False)
69 _snapshot: dict[str, Any] = field(default_factory=dict, init=False, repr=False, compare=False)
70 _prepared_positions: dict[torch.device, torch.Tensor] = field(
71 default_factory=dict, init=False, repr=False, compare=False
72 )
73 _prepared_masks: dict[torch.device, torch.Tensor] = field(
74 default_factory=dict, init=False, repr=False, compare=False
75 )
76 _indexer_segments: dict[int, tuple[tuple[int, int, int, int, int], ...]] = field(
77 default_factory=dict, init=False, repr=False, compare=False
78 )
79
80 _prepared_sequences: dict[torch.device, torch.Tensor] = field(
81 default_factory=dict, init=False, repr=False, compare=False
82 )
83 _use_prepared_packing_inputs: bool = field(default=False, init=False, repr=False, compare=False)
84 _restored_from_packing_tensors: bool = field(default=False, init=False, repr=False, compare=False)
85
86 def prepare_packing_geometry(self, device: torch.device) -> None:
87 """Prepare CP1 graph metadata independently of compression or indexing.
88
89 The runtime calls this before capture. Eager retains its real boundaries;
90 graph inputs carry token-shaped metadata, not a variable document list.
91 """
92 if self.local_query_start != 0 or self.local_query_length != self.global_sequence_length:
93 return
94 self.segment_start_mask(device)
95 object.__setattr__(self, "_use_prepared_packing_inputs", True)
96
97 def router_metadata(self, device: torch.device) -> tuple[torch.Tensor, int]:
98 """Return document IDs and storage capacity; empty rows do not affect the mean."""
99 count = self.local_query_length if self._restored_from_packing_tensors else self.cu_seq_lens.numel() - 1
100 return self._prepared_sequences[torch.device(device)], count
101
102 def prepare(self, device: torch.device, compress_ratios: tuple[int, ...]) -> SharedCompressedPackedSequence:
103 """Prepare an owned boundary snapshot, reused until the input is mutated.
104
105 Normal in-place tensor updates invalidate the cached snapshot. Existing
106 consumers retain their owned geometry. Prepared tensors are read-only;
107 callers must not mutate boundaries through ``.data`` or external storage.
108 Inference tensors without a version counter are always snapshotted anew.
109
110 Args:
111 device: Device on which tensors and prepared geometry are consumed.
112 compress_ratios: Compression ratios used by the layers in this forward.
113 """
114 device = torch.device(device)
115 # Torch exposes tensor mutation tracking only through its version counter.
116 version = None if self.cu_seq_lens.is_inference() else self.cu_seq_lens._version # pylint: disable=protected-access
117 if version is not None and self._snapshot.get("version") == version:
118 prepared: SharedCompressedPackedSequence = self if self._snapshot.get("owned") else self._snapshot["value"]
119 else:
120 prepared = type(self)(
121 self.cu_seq_lens.detach().clone(), self.local_query_start,
122 self.local_query_length, self.global_sequence_length,
123 )
124 SharedCompressedPackedSequence._mark_owned(prepared)
125 self._snapshot.clear()
126 self._snapshot.update(version=version, value=prepared)
127 SharedCompressedPackedSequence._prepare_owned_metadata(prepared, device, compress_ratios)
128 return prepared
129
130 def _mark_owned(self) -> None:
131 """Record the owned tensor's mutation counter for subsequent layer reuse."""
132 if not self.cu_seq_lens.is_inference():
133 # Torch has no public read API for its tensor mutation counter.
134 self._snapshot.update(owned=True, version=self.cu_seq_lens._version) # pylint: disable=protected-access
135
136 def _prepare_owned_metadata(self, device: torch.device, compress_ratios: tuple[int, ...]) -> None:
137 """Populate caches on the owned snapshot, never on caller-owned boundaries."""
138 starts = self.local_segment_starts(device)
139 self._prepared_starts[device] = starts
140 if device not in self._prepared_sequences:
141 self._prepared_sequences[device] = torch.bucketize(
142 self.local_positions(device).squeeze(0), self.cu_seq_lens.to(device=device)[1:], right=True,
143 ).unsqueeze(0)
144 for ratio in set(compress_ratios):
145 self.validate_compression_ratio(ratio)
146 if ratio > 0 and (device, ratio) not in self._prepared_minima:
147 if self._restored_from_packing_tensors:
148 raise ValueError(
149 "graph packing inputs carry no compressed-key metadata for ratio "
150 f"{ratio}; configure every active model compress ratio on the "
151 "runtime input adapter (compress_ratios) so the graph boundary "
152 "can prepare it"
153 )
154 self._prepared_minima[(device, ratio)] = self.minimum_key_indices(device, ratio)
155
156 def local_positions(self, device: torch.device) -> torch.Tensor:
157 """Return the immutable local interval's global token positions."""
158 device = torch.device(device)
159 if device not in self._prepared_positions:
160 self._prepared_positions[device] = torch.arange(
161 self.local_query_start, self.local_query_start + self.local_query_length, device=device,
162 ).unsqueeze(0)
163 return self._prepared_positions[device]
164
165 def segment_start_mask(self, device: torch.device) -> torch.Tensor:
166 """Reuse the per-batch sample-start mask across model forwards."""
167 device = torch.device(device)
168 if device not in self._prepared_masks:
169 self._prepared_masks[device] = self.local_positions(device) == self.local_segment_starts(device)
170 return self._prepared_masks[device]
171
172 def document_boundaries(self) -> tuple[int, ...]:
173 """Reuse the owned batch's host boundaries for routing across layers."""
174 if "boundaries" not in self._snapshot:
175 self._snapshot["boundaries"] = tuple(self.cu_seq_lens.detach().cpu().tolist())
176 return self._snapshot["boundaries"]
177
178 def indexer_segments(self, ratio: int) -> tuple[tuple[int, int, int, int, int], ...]:
179 """Describe packed Q intervals and completed K prefixes without per-layer synchronization.
180
181 Args:
182 ratio: Compression ratio used to express each document's key prefix.
183 """
184 if self._restored_from_packing_tensors:
185 raise NotImplementedError(
186 "graph packing inputs do not carry Python document segments; the "
187 "reference selection consumes per-token tensor bounds instead"
188 )
189 if ratio not in self._indexer_segments:
190 self.validate_compression_ratio(ratio)
191 boundaries = self.document_boundaries()
192 local_start = self.local_query_start
193 local_end = local_start + self.local_query_length
194 segments = []
195 key_base = 0
196 for sample_start, sample_end in zip(boundaries, boundaries[1:]):
197 start, end = max(local_start, sample_start), min(local_end, sample_end)
198 if start < end:
199 segments.append((start-local_start, end-local_start, key_base,
200 key_base+(end-sample_start)//ratio, (end-sample_start) % ratio))
201 key_base += (sample_end-sample_start)//ratio
202 self._indexer_segments[ratio] = tuple(segments)
203 return self._indexer_segments[ratio]
204
205 def minimum_key_indices(
206 self, device: torch.device, compress_ratio: int, segment_starts: torch.Tensor | None = None,
207 ) -> torch.Tensor:
208 """Return the first compressed key belonging to each query's sample.
209
210 Args:
211 device: Device on which tensors and prepared geometry are consumed.
212 compress_ratio: Compression ratio of the consuming layer.
213 segment_starts: Optional precomputed global sample starts for local queries.
214 """
215 if compress_ratio <= 0:
216 raise ValueError("minimum_key_indices requires a positive compression ratio")
217 cached = self._prepared_minima.get((torch.device(device), compress_ratio))
218 if cached is not None:
219 return cached
220 self.validate_compression_ratio(compress_ratio)
221 del segment_starts
222 device = torch.device(device)
223 # Pure tensor arithmetic from cu_seq_lens, identical for eager and the
224 # graph boundary: count each document's complete blocks, then take the
225 # exclusive cumsum as the document's global compressed-key base.
226 boundaries = self.cu_seq_lens.to(device=device, dtype=torch.long)
227 documents = self._prepared_sequences.get(device)
228 if documents is None:
229 documents = torch.bucketize(
230 self.local_positions(device).squeeze(0), boundaries[1:], right=True,
231 ).unsqueeze(0)
232 counts = (boundaries[1:] - boundaries[:-1]) // compress_ratio
233 offsets = torch.cat((counts.new_zeros(1), counts.cumsum(dim=0)[:-1]))
234 return offsets.index_select(0, documents.squeeze(0)).unsqueeze(0)
235
236 def causal_key_upper_bounds(
237 self, device: torch.device, compress_ratio: int,
238 ) -> torch.Tensor:
239 """Return the exclusive upper bound of compressed keys visible to each query.
240
241 Both execution modes share one derivation: a query at document-local
242 position ``p`` sees compressed keys ``[document base, base + (p+1)//ratio)``.
243 The result is a ``[1, local queries]`` tensor, so graph capture replays it
244 across batches whose document count and lengths differ.
245
246 Args:
247 device: Device on which tensors and prepared geometry are consumed.
248 compress_ratio: Compression ratio of the consuming layer.
249 """
250 if compress_ratio <= 0:
251 raise ValueError("causal_key_upper_bounds requires a positive compression ratio")
252 key = (torch.device(device), compress_ratio)
253 cached = self._prepared_bounds.get(key)
254 if cached is None:
255 device = torch.device(device)
256 minima = self.minimum_key_indices(device, compress_ratio)
257 cached = minima + (
258 (self.local_positions(device) - self.local_segment_starts(device) + 1) // compress_ratio
259 )
260 self._prepared_bounds[key] = cached
261 return cached
262
263 def local_segment_starts(self, device: torch.device) -> torch.Tensor:
264 """Return each local query's global packed-sample start position.
265
266 Args:
267 device: Device on which tensors and prepared geometry are consumed.
268 """
269 cached = self._prepared_starts.get(torch.device(device))
270 if cached is not None:
271 return cached
272 if self.local_query_start < 0 or self.local_query_length < 0 or (
273 self.local_query_start + self.local_query_length > self.global_sequence_length
274 ):
275 raise ValueError("packed local query interval must lie within the global sequence")
276 boundaries = self.cu_seq_lens.to(dtype=torch.long)
277 if boundaries.ndim != 1 or boundaries.numel() < 2 or int(boundaries[0]) != 0:
278 raise ValueError("packed cu_seq_lens must be one-dimensional and start with zero")
279 if int(boundaries[-1]) != self.global_sequence_length:
280 raise ValueError(
281 "packed cu_seq_lens must cover global_sequence_length: "
282 f"{int(boundaries[-1])} versus {self.global_sequence_length}"
283 )
284 if torch.any(boundaries[1:] <= boundaries[:-1]):
285 raise ValueError("packed cu_seq_lens must be strictly increasing")
286 boundaries = boundaries.to(device=device)
287 query_positions = self.local_positions(device).squeeze(0)
288 segment_ids = torch.bucketize(query_positions, boundaries[1:], right=True)
289 return boundaries[:-1].index_select(0, segment_ids).unsqueeze(0)
290
291 @staticmethod
292 def validate_compression_ratio(compress_ratio: int) -> None:
293 """Validate the ratio; complete block planning handles natural document lengths."""
294 if compress_ratio < 0:
295 raise ValueError("compression ratio must be nonnegative")
296
297 def is_compression_aligned(self, compress_ratio: int) -> bool:
298 """Report whether every document boundary lies on a complete-block edge.
299
300 Eager reads the real boundaries; graph packing inputs read the alignment
301 the graph boundary validated before capture. Both answer the same
302 question for the same batch.
303
304 Args:
305 compress_ratio: Compression ratio of the consuming layer.
306 """
307 if compress_ratio <= 1:
308 return True
309 if self._restored_from_packing_tensors:
310 return 0 < self._packing_alignment and self._packing_alignment % compress_ratio == 0
311 return not any(boundary % compress_ratio for boundary in self.document_boundaries())
312
313 def compressed_key_length(self, compress_ratio: int) -> int:
314 """Return the total number of complete compressed keys in the batch.
315
316 For alignment-validated graph packing inputs the contiguous count equals
317 the per-document sum; eager keeps exact arithmetic for natural lengths.
318
319 Args:
320 compress_ratio: Compression ratio of the consuming layer.
321 """
322 ratio = max(1, compress_ratio)
323 if self._restored_from_packing_tensors:
324 return self.local_query_length // ratio
325 boundaries = self.document_boundaries()
326 return sum((end - start) // ratio for start, end in zip(boundaries, boundaries[1:]))
327
328 def block_plan(self, ratio: int) -> Any:
329 """Return complete local document blocks; CP ownership is planned by its member."""
330 if self._restored_from_packing_tensors or ratio <= 1:
331 return None
332 boundaries = self.document_boundaries()
333 if self.local_query_length % ratio == 0 and all(value % ratio == 0 for value in boundaries):
334 return None
335 if self.local_query_start or self.local_query_length != self.global_sequence_length:
336 raise ValueError("local document block planning requires the complete local sequence")
337 blocks = tuple((start, (end - start) // ratio) for start, end in zip(boundaries, boundaries[1:])
338 if (end - start) // ratio)
339 return DocumentBlockPlan(ratio, blocks)
340
341 def cached_compressed_positions(self, ratio: int, embeddings: tuple) -> tuple | None:
342 """Read a batch-local position cache without launching communication."""
343 cos, sin = embeddings
344 versions = tuple(None if value.is_inference() else value._version for value in embeddings) # pylint: disable=protected-access
345 cached = self._compression_rope.get(ratio)
346 if (cached is not None and cached[0] is cos and cached[1] is sin and cached[2] == versions
347 and None not in versions and not cos.requires_grad and not sin.requires_grad):
348 return cached[3]
349 return None
350
351 def cache_compressed_positions(self, ratio: int, embeddings: tuple, positions: tuple) -> None:
352 """Retain only non-differentiable position metadata for the same source tensors."""
353 if any(value.requires_grad for value in embeddings):
354 return
355 versions = tuple(None if value.is_inference() else value._version for value in embeddings) # pylint: disable=protected-access
356 self._compression_rope[ratio] = (*embeddings, versions, positions)
357
358 def compressed_positions(self, plan: Any, embeddings: tuple) -> tuple:
359 """Select local block-start positions without any tensor exchange."""
360 cached = self.cached_compressed_positions(plan.ratio, embeddings)
361 if cached is not None:
362 return cached
363 rows = plan.indices(embeddings[0].device)[1]
364 positions = tuple(value.index_select(1, rows) for value in embeddings)
365 self.cache_compressed_positions(plan.ratio, embeddings, positions)
366 return positions
367
368 def raw_document_starts(self) -> tuple:
369 """Keep raw token coordinates separate from compact compressed-key IDs."""
370 if self._restored_from_packing_tensors:
371 # Only the fused attention kernel consumes these Python
372 # coordinates; fused execution is gated out of graph mode.
373 return ()
374 first, last = self.local_query_start, self.local_query_start + self.local_query_length
375 return tuple((max(first, start)-first, start)
376 for start, end in zip(self.document_boundaries(), self.document_boundaries()[1:])
377 if max(first, start) < min(last, end))
378
379
380 def pytree_flatten(self) -> tuple[list[Any], tuple]:
381 """Expose packing tensors with a schema independent of document count and S."""
382 if self._use_prepared_packing_inputs:
383 return [self._prepared_starts, self._prepared_positions,
384 self._prepared_masks, self._prepared_sequences,
385 self._prepared_minima], ("packing", self._packing_alignment)
386 return [self.cu_seq_lens], (self.local_query_start, self.local_query_length, self.global_sequence_length)
387
388 @classmethod
389 def pytree_unflatten(cls, children: Any, context: tuple) -> SharedCompressedPackedSequence:
390 """Restore prepared metadata without reading boundary values during capture."""
391 if context[0] != "packing":
392 return cls(children[0], *context)
393 starts, positions, masks, sequences, minima = children
394 reference = next(iter(starts.values()))
395 length = reference.shape[-1]
396 packed = cls(reference.new_empty(0), 0, length, length)
397 packed._prepared_starts.update(starts)
398 packed._prepared_positions.update(positions)
399 packed._prepared_masks.update(masks)
400 packed._prepared_sequences.update(sequences)
401 packed._prepared_minima.update(minima)
402 object.__setattr__(packed, "_packing_alignment", context[1])
403 object.__setattr__(packed, "_use_prepared_packing_inputs", True)
404 object.__setattr__(packed, "_restored_from_packing_tensors", True)
405 packed._mark_owned()
406 return packed
407
408class GraphPackedSequence(SharedCompressedPackedSequence):
409 """Tensor-only packing inputs created exclusively at the graph boundary.
410
411 The subclass is a registration marker: only graph-boundary inputs are
412 flattened as pytree nodes, so eager FSDP keeps treating packed inputs as
413 opaque leaves that retain real boundaries and caches. Every semantic lives
414 in the shared base, including the compressed-key metadata that lets the
415 graph carry indexer and compressor execution with the same code path.
416 """
417
418
419register_pytree_node(GraphPackedSequence, GraphPackedSequence.pytree_flatten,
420 GraphPackedSequence.pytree_unflatten)