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 intervals, local packed execution and chunk plans for linear attention.
16
17This dependency leaf is shared with functional adapters and model runtimes.
18Keep it independent of module-family registration, backends and collectives.
19"""
20from __future__ import annotations
21from bisect import bisect_left, bisect_right
22from dataclasses import dataclass, field
23from functools import lru_cache
24from typing import Any, Callable, Mapping, Sequence
25
26import torch
27
28
29# Bound retained interval views and their materialized chunk indices. Evicted
30# views can be rebuilt; this cache budget does not limit CP degree or documents.
31_MAX_CACHED_INTERVALS = 32
32
33
34@dataclass(frozen=True)
35class PackedChunkPlan:
36 """Read-only kernel indices for one local packed interval and chunk size."""
37
38 cu_seqlens: torch.Tensor
39 cu_seqlens_cpu: torch.Tensor
40 chunk_indices: torch.Tensor
41 chunk_offsets: torch.Tensor
42
43 def kwargs(self) -> dict[str, torch.Tensor]:
44 """Return the common FLA varlen arguments without copying device tensors."""
45 return {"cu_seqlens": self.cu_seqlens, "chunk_indices": self.chunk_indices}
46
47
48@dataclass(frozen=True, eq=False)
49class PackedDocumentInfo:
50 """Validated immutable document snapshot shared by a batch's interval views.
51
52 Identity hashing lets bounded CPU-plan caches reuse this snapshot without
53 hashing every document offset at every layer. Cache keys retain the object,
54 so distinct batches cannot collide through reuse of a Python object ID.
55 """
56
57 offsets: tuple[int, ...]
58
59 def __post_init__(self) -> None:
60 offsets = tuple(self.offsets)
61 if (
62 len(offsets) < 2
63 or offsets[0] != 0
64 or any(not isinstance(value, int) or isinstance(value, bool) for value in offsets)
65 or any(left >= right for left, right in zip(offsets, offsets[1:]))
66 ):
67 raise ValueError("Packed sample offsets must be strictly increasing integers starting at zero.")
68 object.__setattr__(self, "offsets", offsets)
69
70
71@dataclass(frozen=True)
72class PackedSequenceInfo:
73 """Own immutable sample offsets and a contiguous physical token interval.
74
75 Offsets are global within one CP group, including any explicitly declared
76 padding sample. Local CP cuts are fragments, never new sample resets.
77 Device plans contain read-only tensors; each invocation saves the tensors
78 it consumes so that ordinary autograd version checks remain effective.
79 """
80
81 global_offsets: tuple[int, ...] | PackedDocumentInfo
82 start: int
83 end: int
84 local_offsets: tuple[int, ...] = field(init=False)
85 documents: PackedDocumentInfo = field(init=False, repr=False, compare=False, hash=False)
86 _head_index: int = field(init=False, repr=False, compare=False, hash=False)
87 _tail_index: int = field(init=False, repr=False, compare=False, hash=False)
88 _plans: dict[tuple[torch.device, int], PackedChunkPlan] = field(
89 default_factory=dict, init=False, repr=False, compare=False, hash=False
90 )
91 _intervals: dict[tuple[int, int], PackedSequenceInfo] = field(
92 default_factory=dict, init=False, repr=False, compare=False, hash=False
93 )
94
95 def __post_init__(self) -> None:
96 documents = (self.global_offsets if isinstance(self.global_offsets, PackedDocumentInfo)
97 else PackedDocumentInfo(self.global_offsets))
98 offsets = documents.offsets
99 if (
100 not isinstance(self.start, int) or isinstance(self.start, bool)
101 or not isinstance(self.end, int) or isinstance(self.end, bool)
102 or not 0 <= self.start < self.end <= offsets[-1]
103 ):
104 raise ValueError("Packed token interval must be nonempty and covered by global sample offsets.")
105 head = bisect_right(offsets, self.start) - 1
106 tail = bisect_left(offsets, self.end) - 1
107 local = (0, *(value - self.start for value in offsets[head + 1:tail + 1]), self.end - self.start)
108 object.__setattr__(self, "global_offsets", offsets)
109 object.__setattr__(self, "local_offsets", local)
110 object.__setattr__(self, "documents", documents)
111 object.__setattr__(self, "_head_index", head)
112 object.__setattr__(self, "_tail_index", tail)
113
114 @property
115 def length(self) -> int:
116 """Return this interval's physical token count."""
117 return self.end - self.start
118
119 @property
120 def num_sequences(self) -> int:
121 """Return the number of nonempty local sample fragments."""
122 return len(self.local_offsets) - 1
123
124 @property
125 def continues_previous(self) -> bool:
126 """Whether the first fragment consumes the preceding interval's state."""
127 return self.start != self.global_offsets[self._head_index]
128
129 @property
130 def continues_next(self) -> bool:
131 """Whether the last fragment feeds the following interval's state."""
132 return self.end != self.global_offsets[self._tail_index + 1]
133
134 @property
135 def transfer_active(self) -> bool:
136 """Whether the preceding interval can affect this interval's exit."""
137 return self.continues_previous and self.num_sequences == 1
138
139 @property
140 def head(self) -> slice:
141 """Return the first fragment's local token slice."""
142 return slice(0, self.local_offsets[1])
143
144 @property
145 def tail(self) -> slice:
146 """Return the last fragment's local token slice."""
147 return slice(self.local_offsets[-2], self.length)
148
149 @property
150 def preceding_sample_tokens(self) -> int:
151 """Return how many earlier tokens belong to the first local sample."""
152 return self.start - self.global_offsets[self._head_index]
153
154 def interval(self, start: int, end: int) -> PackedSequenceInfo:
155 """Describe another contiguous interval without retaining artificial cuts.
156
157 Args:
158 start: Inclusive start of the token interval.
159 end: Exclusive end of the token interval.
160 """
161 key = (start, end)
162 if key == (self.start, self.end):
163 return self
164 if key not in self._intervals:
165 if len(self._intervals) == _MAX_CACHED_INTERVALS:
166 self._intervals.pop(next(iter(self._intervals)))
167 self._intervals[key] = PackedSequenceInfo(self.documents, start, end)
168 return self._intervals[key]
169
170 def ulysses(self, degree: int, local_rank: int) -> PackedSequenceInfo:
171 """Describe the token interval after consecutive-rank AllToAll.
172
173 Args:
174 degree: Number of ranks participating in the head/sequence exchange.
175 local_rank: Rank index in the Ulysses group.
176 """
177 if degree < 1 or not 0 <= local_rank < degree:
178 raise ValueError("Invalid Ulysses degree or local rank.")
179 start = self.start - local_rank * self.length
180 return self.interval(start, start + degree * self.length)
181
182 def materialize(self, device: torch.device, chunk_size: int) -> PackedChunkPlan:
183 """Prepare immutable indices once per batch, layout, device and chunk size.
184
185 Args:
186 device: Device on which to materialize sequence metadata.
187 chunk_size: Number of tokens in a recurrence chunk.
188 """
189 device = torch.device(device)
190 cache_key = (device, chunk_size)
191 if cache_key in self._plans:
192 return self._plans[cache_key]
193 if chunk_size < 1:
194 raise ValueError("chunk_size must be positive.")
195 counts = [
196 (end - start + chunk_size - 1) // chunk_size
197 for start, end in zip(self.local_offsets, self.local_offsets[1:])
198 ]
199 indices = [(sequence, chunk) for sequence, count in enumerate(counts) for chunk in range(count)]
200 offsets = [0]
201 for count in counts:
202 offsets.append(offsets[-1] + count)
203 cpu = torch.tensor(self.local_offsets, dtype=torch.int64)
204 plan = PackedChunkPlan(
205 cpu.to(device),
206 cpu,
207 torch.tensor(indices, device=device, dtype=torch.int64),
208 torch.tensor(offsets, device=device, dtype=torch.int64),
209 )
210 self._plans[cache_key] = plan
211 return plan
212
213 def first_state(self, state: torch.Tensor | None) -> torch.Tensor | None:
214 """Expand only a continued first fragment's state for a varlen kernel.
215
216 Args:
217 state: State tensor at the invocation boundary, or None for zero input.
218 """
219 if state is None or not self.continues_previous:
220 return None
221 if self.num_sequences == 1:
222 return state
223 return torch.cat((state, state.new_zeros((self.num_sequences - 1, *state.shape[1:]))))
224
225 def last_state(self, state: torch.Tensor | None) -> torch.Tensor | None:
226 """Expand a terminal state gradient into the last fragment slot.
227
228 Args:
229 state: State tensor at the invocation boundary, or None for zero input.
230 """
231 if state is None or not self.continues_next:
232 return None
233 if self.num_sequences == 1:
234 return state
235 return torch.cat((state.new_zeros((self.num_sequences - 1, *state.shape[1:])), state))
236
237
238@dataclass(frozen=True)
239class PackedSummaryExchangePlan:
240 """Host-only forward edges; reverse communication uses their transpose."""
241
242 send_counts: tuple[int, ...]
243 recv_counts: tuple[int, ...]
244 active: bool
245
246
247@lru_cache(maxsize=32)
248def _packed_summary_exchange_plan(documents: PackedDocumentInfo, length: int,
249 rank: int, size: int) -> PackedSummaryExchangePlan:
250 """Build summary counts for this rank's tail consumers and head producers."""
251 offsets = documents.offsets
252 if offsets[-1] != length * size:
253 raise ValueError("Sparse summaries require equal contiguous token shards covering the document offsets.")
254 start, end = rank * length, (rank + 1) * length
255 first = offsets[bisect_right(offsets, start) - 1] // length
256 last = (offsets[bisect_left(offsets, end)] - 1) // length
257 sends = tuple(int(rank < peer <= last) for peer in range(size))
258 receives = tuple(int(first <= peer < rank) for peer in range(size))
259 # A single global decision lets all ranks skip an empty collective together.
260 # Inspect rank cuts rather than walking a potentially much longer document list.
261 active = any(offsets[bisect_left(offsets, cut)] != cut for cut in range(length, length * size, length))
262 return PackedSummaryExchangePlan(sends, receives, active)
263
264
265def plan_packed_summary_exchange(info: PackedSequenceInfo, rank: int, size: int) -> PackedSummaryExchangePlan:
266 """Cache exact head/tail document dependencies without device metadata reads.
267
268 Args:
269 info: Host document metadata after any Ulysses token redistribution.
270 rank: Chronological rank within the state group.
271 size: Number of equal contiguous token shards in that group.
272 """
273 if not 0 <= rank < size or info.start != rank * info.length:
274 raise ValueError("Sparse summary metadata must match the chronological state-group rank.")
275 return _packed_summary_exchange_plan(info.documents, info.length, rank, size)
276
277
278def _offset_tuple(value: torch.Tensor | Sequence[int]) -> tuple[int, ...]:
279 """Snapshot user metadata so a later batch cannot mutate saved semantics."""
280 if isinstance(value, torch.Tensor):
281 if value.ndim != 1 or value.dtype not in (torch.int32, torch.int64):
282 raise ValueError("Cumulative sample offsets must be a one-dimensional integer tensor.")
283 return tuple(value.detach().cpu().tolist())
284 return tuple(value)
285
286
287def _global_offsets(info: PackedSequenceInfo | None, aliases: list) -> tuple[int, ...]:
288 """Check alias agreement before constructing or reusing local metadata."""
289 if info is not None and not isinstance(info, PackedSequenceInfo):
290 raise TypeError("packed_sequence_info must be PackedSequenceInfo.")
291 offsets = info.global_offsets if info is not None else _offset_tuple(aliases[0])
292 # Runtime q/k aliases share this immutable tuple; comparing the same tuple
293 # still walks its elements in Python, so skip only exact object identity.
294 if any(_offset_tuple(value) != offsets for value in aliases if value is not offsets):
295 raise ValueError("Packed sequence aliases disagree; provide one consistent set of global sample offsets.")
296 return offsets
297
298
299def resolve_packed_sequence(
300 arguments: Mapping[str, Any],
301 local_length: int,
302 *,
303 cp_rank: int = 0,
304 cp_size: int = 1,
305) -> PackedSequenceInfo | None:
306 """Normalize model-level aliases, all of which describe GLOBAL sample offsets.
307
308 Kernel-level cu_seqlens is derived from the returned local interval. Prefer
309 a prebuilt packed_sequence_info from the runtime adapter to avoid host reads
310 or per-layer validation of device metadata.
311
312 Args:
313 arguments: Per-forward keyword arguments carrying document boundaries.
314 local_length: Number of tokens owned by this CP rank.
315 cp_rank: Rank index within the CP mesh.
316 cp_size: Number of ranks in the CP mesh.
317 """
318 info = arguments.get("packed_sequence_info")
319 aliases = [
320 arguments[name]
321 for name in ("cu_seq_lens", "cu_seqlens", "cu_seq_lens_q", "cu_seq_lens_k")
322 if arguments.get(name) is not None
323 ]
324 if arguments.get("packed_seq_params") is not None or arguments.get("seq_idx") is not None:
325 raise ValueError(
326 "Use global cu_seq_lens or PackedSequenceInfo; implicit packed/seq_idx conversion is unsupported."
327 )
328 if info is None and not aliases:
329 return None
330 if not 0 <= cp_rank < cp_size:
331 raise ValueError("Invalid CP rank or size for packed sequence metadata.")
332 offsets = _global_offsets(info, aliases)
333 if info is None:
334 info = PackedSequenceInfo(offsets, cp_rank * local_length, (cp_rank + 1) * local_length)
335 if (
336 info.length != local_length
337 or info.start != cp_rank * local_length
338 or info.global_offsets[-1] != cp_size * local_length
339 ):
340 raise ValueError("Packed metadata must cover the chronological, equal-length CP token intervals.")
341 return info
342
343
344def local_sequence_offsets(
345 cu_seqlens: torch.Tensor | Sequence[int], tokens: int, *, require_cpu: bool = False,
346) -> tuple[int, ...]:
347 """Validate local document offsets without constructing a CP interval.
348
349 Args:
350 cu_seqlens: Local cumulative document boundaries.
351 tokens: Local packed token count.
352 require_cpu: Reject device metadata when the native ABI requires host offsets.
353 """
354 if isinstance(cu_seqlens, torch.Tensor):
355 if require_cpu and cu_seqlens.device.type != "cpu":
356 raise ValueError("Native cu_seqlens must be a CPU integer tensor or sequence.")
357 if cu_seqlens.ndim != 1 or cu_seqlens.dtype not in (torch.int32, torch.int64):
358 raise ValueError("cu_seqlens must be a one-dimensional integer tensor.")
359 cu_seqlens = cu_seqlens.detach().cpu().tolist()
360 offsets = tuple(cu_seqlens)
361 if (len(offsets) < 2 or offsets[0] != 0
362 or any(not isinstance(value, int) or isinstance(value, bool) for value in offsets)
363 or any(left >= right for left, right in zip(offsets, offsets[1:]))):
364 raise ValueError("Packed sample offsets must be strictly increasing integers starting at zero.")
365 if offsets[-1] != tokens:
366 raise ValueError("Local cumulative offsets must end at the input token count.")
367 return offsets
368
369
370def packed_eager(
371 operator: Callable[..., tuple[torch.Tensor, torch.Tensor | None]],
372 inputs: tuple[torch.Tensor, ...],
373 cu_seqlens: torch.Tensor | Sequence[int],
374 *,
375 initial_state: torch.Tensor | None = None,
376 output_final_state: bool = False,
377 **kwargs: Any,
378) -> tuple[torch.Tensor, torch.Tensor | None]:
379 """Evaluate the local eager recurrence independently per sample fragment.
380
381 Args:
382 operator: Local recurrence callable to evaluate for each document.
383 inputs: Token-aligned recurrence operands.
384 cu_seqlens: Cumulative document boundaries for packed tokens.
385 initial_state: Optional incoming-state slot for each local sample fragment.
386 output_final_state: Whether to return one outgoing state per local sample fragment.
387 """
388 if inputs[0].shape[0] != 1:
389 raise ValueError("Packed eager requires batch dimension one.")
390 offsets = local_sequence_offsets(cu_seqlens, inputs[0].shape[1])
391 if initial_state is not None and initial_state.shape[0] != len(offsets) - 1:
392 raise ValueError("Packed initial_state requires one slot per local sample fragment.")
393 outputs, finals = [], []
394 for index, (start, end) in enumerate(zip(offsets, offsets[1:])):
395 state = None if initial_state is None else initial_state[index : index + 1]
396 output, final = operator(
397 *(tensor[:, start:end] for tensor in inputs),
398 initial_state=state,
399 output_final_state=output_final_state,
400 **kwargs,
401 )
402 outputs.append(output)
403 if output_final_state:
404 finals.append(final)
405 return torch.cat(outputs, dim=1), torch.cat(finals) if output_final_state else None
406
407
408def local_chunk_metadata(
409 cu_seqlens: torch.Tensor | Sequence[int] | None, tokens: int, chunk_size: int = 64,
410) -> dict[str, tuple[int, ...]]:
411 """Build host offsets and flattened document/chunk pairs for local operators.
412
413 Args:
414 cu_seqlens: Host document offsets, or None for dense input.
415 tokens: Number of tokens in this invocation.
416 chunk_size: Number of tokens in a kernel chunk.
417
418 Returns:
419 Local cu_seqlens and flattened chunk_indices, or an empty dense descriptor.
420 """
421 if cu_seqlens is None:
422 return {}
423 if chunk_size < 1:
424 raise ValueError("chunk_size must be positive.")
425 offsets = local_sequence_offsets(cu_seqlens, tokens, require_cpu=True)
426 indices = tuple(value for seq, (begin, end) in enumerate(zip(offsets, offsets[1:]))
427 for chunk in range((end - begin + chunk_size - 1) // chunk_size) for value in (seq, chunk))
428 return {"cu_seqlens": offsets, "chunk_indices": indices}