Diff Coverage

Diff: origin/master...HEAD, staged and unstaged changes

Source File Diff Coverage (%) Missing Lines
hyper_parallel/components/functional/sparse_flash_mla.py 100%  
hyper_parallel/components/modules/attention/compressed_sparse_attention2/__init__.py 100%  
hyper_parallel/components/modules/attention/compressed_sparse_attention2/compressed_sparse_attention2.py 100%  
hyper_parallel/components/modules/attention/compressed_sparse_attention2/compressed_sparse_attention2_family.py 100%  
hyper_parallel/components/modules/attention/compressed_sparse_attention2/cp_compressed_sparse_attention2.py 52.8% 137-143,148,187-190,198,255,359-360,369
hyper_parallel/components/modules/attention/compressed_sparse_attention2/indexer.py 84.2% 684-685,688
hyper_parallel/components/modules/attention/compressed_sparse_attention2/indexer_kl_loss.py 100%  
hyper_parallel/components/modules/attention/compressed_sparse_attention2/quantize_compressed_sparse_attention2.py 100%  
hyper_parallel/components/quantization/config.py 94.2% 191,210,270,280
hyper_parallel/components/quantization/quantizers/csa2/__init__.py 100%  
hyper_parallel/components/quantization/quantizers/csa2/csa2_cache.py 94.6% 55,79,140,162,164
hyper_parallel/components/quantization/quantizers/csa2/indexer_qk.py 46.9% 40-41,46-50,52-53,57,63-70,73,79,97-98,102,106,111-112
hyper_parallel/components/quantization/quantizers/csa2/main_kv.py 19.7% 41-45,50-52,56-57,59-60,62-65,67-70,72-77,79-80,86-92,95-101,103-109
hyper_parallel/components/quantization/quantizers/csa2/swa_kv.py 21.4% 41-42,47-50,55-59,61-64,68,70-77,82-92,97-99,101-106
hyper_parallel/components/quantization/tensor/csa2_cache_tensor.py 100%  
hyper_parallel/distributed/context_parallel/csa2_cache_transport.py 73.4% 97,118,121,125,160-164,166-169,172-175,194-197,214-221,223-227
hyper_parallel/trainer/config/parallelism.py 100%  
hyper_parallel/components/modules/attention/compressed_sparse_attention2/cp_compressed_sparse_attention2.py
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
        """Submit Full-layer K; Reindex reuses the already differentiable shared bank."""
        key = self._project_index_key(latent, cos, sin, index_key, key_position_embeddings)
        if not self.owns_key:
            return key
        if self._qk_policy is not None:
            key = CSA2CacheQuantizer("indexer_k").quantize(key)
        if isinstance(key, CSA2CacheTensor):
            group = self.cp_context.mesh.get_group()
            counts = None if block_plan is None else block_plan.counts
            return launch_packed_bank_gather(key, counts, group, self.cp_context.size)
        launch = self._launch_bank
        return launch(key, 1) if block_plan is None else launch_compressed_bank(key, block_plan.counts, launch)

    def _launch_bank(self, tensor: torch.Tensor, dim: int) -> Any:
        """Borrow the framework's differentiable asynchronous sequence gather."""
        return self.cp_context.launch_gather_sequence(tensor, dim=dim).collective

    def exchange_key(self, prepared: Any) -> torch.Tensor:
        """Wait only when the local/worker selection consumes Index K."""
        return prepared if isinstance(prepared, torch.Tensor) else prepared.wait()
183
184
185
186
187
188
189
190
191
192
193
194
            prepare_attention()
        prepared = self._prepare_dispatched(wave)
        key = self.exchange_key(prepared_key)
        # Recompute must preserve the first-pass cache for later consumers.
        index_key_cache = None
        if isinstance(key, CSA2CacheTensor):
            index_key_cache = key
            key = CSA2CacheQuantizer.dequantize(key)
        select = self._select_dispatched if self._result_region is None else self._result_region
        result = select(prepared, key)
        del prepared
        query = self._project_index_query(query_residual, cos, sin)
194
195
196
197
198
199
200
201
202
        query = self._project_index_query(query_residual, cos, sin)
        if weights.shape[-1] != query.shape[2]:
            raise ValueError("Indexer query and merge weights must have matching head counts")
        finish = self._finish_selection if self._wait_region is None else self._wait_region
        return CSA2IndexerOutput(finish(result), key, None, query, weights, index_key_cache=index_key_cache)

    def enable_selection_exclude(self) -> None:
        """Reuse input/selection/result transfers instead of waiting on consumed handles."""
        super().enable_selection_exclude()
251
252
253
254
255
256
257
258
259
        if self._parallel_bound:
            raise ValueError("CSA2 parallel resources are already bound")
        if getattr(binding.mesh_binding.mesh_context, "tp_size", 1) > 1:
            mesh = binding.mesh_binding.axis_mesh("tp")
            self._head_sum = partial(sum_head_scores, group=mesh.get_group())
        self._parallel_bound = True

    def head_reducer(self) -> Callable | None:
        """Provide head SUM before TopK and KL normalization."""
355
356
357
358
359
360
361
362
363
364
        return async_sequence_dispatch(tensor, sequence_dim, route, self.cp_context.mesh.get_group())

    def exchange_main(self, tensor: torch.Tensor, sequence_dim: int, route: Any) -> Any:
        """Launch the main compressed document prefix."""
        if isinstance(tensor, CSA2CacheTensor):
            return launch_packed_sequence_dispatch(tensor, sequence_dim, route,
                                                   self.cp_context.mesh.get_group())
        return async_sequence_dispatch(tensor, sequence_dim, route, self.cp_context.mesh.get_group())

    def _launch_compressed_bank(self, compressed: torch.Tensor, route: Any, plan: Any) -> Any:
365
366
367
368
369
370
371
372
373
        """Respect the compressed bank's actual owner counts and physical layout."""
        if isinstance(compressed, CSA2CacheTensor):
            group = self.cp_context.mesh.get_group()
            if route is not None:
                return self.exchange_main(compressed, 1, route)
            counts = None if plan is None else plan.counts
            return launch_packed_bank_gather(compressed, counts, group, self.cp_context.size)
        if route is not None:
            return self.exchange_main(compressed, 1, route)
hyper_parallel/components/modules/attention/compressed_sparse_attention2/indexer.py
680
681
682
683
684
685
686
687
688
689
690
691
692
        key = self.exchange_key(prepared_key)
        index_key_cache = None
        if isinstance(key, CSA2CacheTensor):
            # Preserve producer bytes while decoding the differentiable scoring key.
            index_key_cache = key
            key = CSA2CacheQuantizer.dequantize(key)
        elif self.owns_key and self._qk_policy is not None:
            # Local owners share one quantization between scoring and publication.
            key, index_key_cache = self._qk_policy.pack_owned_key(key)
        selected, candidates = self._run_selection(
            query, key, weights, candidate_blocks, query_offset, reduce_sum,
            minimum_key_indices, query_segments, causal_upper,
        )
hyper_parallel/components/quantization/config.py
187
188
189
190
191
192
193
194
195
    group: Literal[16] = MAIN_KV_GROUP_SIZE

    def __post_init__(self) -> None:
        if self.act_format != "fp4_e2m1":
            raise ValueError("main_kv.act_format must be 'fp4_e2m1'.")
        if self.scale_format not in ("e4m3", "e8m7"):
            raise ValueError("main_kv.scale_format must be 'e4m3' or 'e8m7' (BF16).")
        if isinstance(self.group, bool) or not isinstance(self.group, int) or self.group != MAIN_KV_GROUP_SIZE:
            raise ValueError("main_kv.group must be 16.")
206
207
208
209
210
211
212
213
    def __post_init__(self) -> None:
        if self.act_format != "fp8_e4m3":
            raise ValueError("swa_kv.act_format must be 'fp8_e4m3'.")
        if self.scale_format not in ("e8m0", "e8m7"):
            raise ValueError("swa_kv.scale_format must be 'e8m0' or 'e8m7' (BF16).")
        if isinstance(self.group, bool) or not isinstance(self.group, int) or self.group != SWA_KV_GROUP_SIZE:
            raise ValueError("swa_kv.group must be 32.")

266
267
268
269
270
271
272
273
274
            )
        typed_schemes = {}
        for name, scheme in self.dtype_schemes.items():
            if not isinstance(name, str) or not name:
                raise ValueError("LowPrecisionConfig.dtype_schemes keys must be non-empty strings.")
            scheme_type = _CSA2_FORMAT_TYPES.get(name, LowPrecisionDtypeScheme)
            if isinstance(scheme, Mapping):
                try:
                    scheme = scheme_type(**dict(scheme))
276
277
278
279
280
281
282
283
284
                    raise ValueError(
                        f"Invalid LowPrecisionConfig.dtype_schemes.{name}: {exc}"
                    ) from exc
            if not isinstance(scheme, scheme_type):
                raise ValueError(
                    f"LowPrecisionConfig.dtype_schemes.{name} must be a {scheme_type.__name__}."
                )
            typed_schemes[name] = scheme
        self.dtype_schemes = typed_schemes
hyper_parallel/components/quantization/quantizers/csa2/csa2_cache.py
51
52
53
54
55
56
57
58
59
                scale_format: CSA2ScaleFormat) -> CSA2CacheTensor:
        """Encode physical bytes and return a floating logical wrapper."""
        del ctx
        if cache_format == "indexer_k":
            packed = quantize_indexer_k(value)
        elif cache_format == "main_kv":
            packed = quantize_main_kv(value, scale_format)
        else:
            packed = quantize_swa_kv(value, scale_format)
75
76
77
78
79
80
81
82
        """Decode using the format and logical dtype stored on the cache."""
        del ctx
        width = cache.shape[-1]
        if cache.cache_format == "indexer_k":
            return dequantize_indexer_k(cache.packed, width, cache.dtype)
        if cache.cache_format == "main_kv":
            return dequantize_main_kv(cache.packed, width, cache.dtype, cache.scale_format)
        return dequantize_swa_kv(cache.packed, width, cache.scale_format)
136
137
138
139
140
141
142
143
144
    def __init__(self, cache_format: CSA2CacheFormat,
                 scale_format: Optional[CSA2ScaleFormat] = None) -> None:
        """Validate the storage format and resolve its default scale format."""
        if cache_format not in self._DEFAULT_SCALE:
            raise ValueError(f"Unsupported CSA2 cache format: {cache_format!r}.")
        effective_scale = self._DEFAULT_SCALE[cache_format] if scale_format is None else scale_format
        if effective_scale not in self._ALLOWED_SCALES[cache_format]:
            raise ValueError(f"Unsupported {cache_format} scale format: {effective_scale!r}.")
        self.cache_format = cache_format
158
159
160
161
162
163
164
165
166
167
        """Decode [B, Q, K] row indices; invalid IDs return zero and receive no gradient."""
        valid_main = cache.cache_format == "main_kv" and cache.ndim == 3
        valid_swa = cache.cache_format == "swa_kv" and cache.ndim == 4 and cache.shape[1] == 1
        if not (valid_main or valid_swa) or indices.ndim != 3:
            raise ValueError("Selected reads require [B, K, D] Main or [B, 1, K, D] SWA cache.")
        if indices.shape[0] != cache.shape[0]:
            raise ValueError("Selected cache indices must share the cache batch size.")
        if indices.dtype not in (torch.int32, torch.int64) or indices.device != cache.device:
            raise ValueError("Selected cache indices must be int32 or int64 on the cache device.")
        return _ReadSelectedCSA2Cache.apply(cache, indices)
hyper_parallel/components/quantization/quantizers/csa2/indexer_qk.py
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61


def _indexer_row_bytes(width: int) -> int:
    """Count E2M1 data bytes and pair-padded E8M0 scale bytes."""
    scale_slots = MX_SCALE_SLOTS * ((width // MX_BLOCK_SIZE_32 + 1) // 2)
    return width // MXFP4_VALUES_PER_BYTE + scale_slots


def quantize_indexer_k(key: Tensor) -> Tensor:
    """Encode Indexer K rows as E2M1 data followed by paired E8M0 scales."""
    width = key.shape[-1]
    if width <= 0 or width % MX_BLOCK_SIZE_32:
        raise ValueError("Indexer K width must be positive and divisible by 32.")
    if key.numel() == 0:
        return torch.empty((*key.shape[:-1], _indexer_row_bytes(width)),
                           dtype=torch.uint8, device=key.device)
    npu = import_module("torch_npu")
    data, scale = npu.npu_dynamic_mx_quant(
        key.reshape(-1, width).contiguous(), dst_type=npu.float4_e2m1fn_x2,
        block_size=MX_BLOCK_SIZE_32, round_mode="rint", scale_alg=MX_SCALE_ALG_OCP,
    )
    return torch.cat((data.reshape(*key.shape[:-1], width // MXFP4_VALUES_PER_BYTE),
                      scale.reshape(*key.shape[:-1], -1)), dim=-1)


def dequantize_indexer_k(packed: Tensor, logical_width: int, dtype: torch.dtype) -> Tensor:
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77


def dequantize_indexer_k(packed: Tensor, logical_width: int, dtype: torch.dtype) -> Tensor:
    """Decode packed Indexer K rows to the requested floating dtype."""
    if logical_width <= 0 or logical_width % MX_BLOCK_SIZE_32:
        raise ValueError("Indexer K width must be positive and divisible by 32.")
    if packed.numel() == 0:
        return torch.empty((*packed.shape[:-1], logical_width), dtype=dtype, device=packed.device)
    npu = import_module("torch_npu")
    scale_pairs = (logical_width // MX_BLOCK_SIZE_32 + 1) // 2
    data = packed[..., :logical_width // MXFP4_VALUES_PER_BYTE].contiguous()
    scale = packed[..., logical_width // MXFP4_VALUES_PER_BYTE:].reshape(
        *packed.shape[:-1], scale_pairs, MX_SCALE_SLOTS
    ).contiguous()
    values = npu.npu_anti_mx_quant(
        data.reshape(-1, logical_width // MXFP4_VALUES_PER_BYTE),
        scale.reshape(-1, scale_pairs, MX_SCALE_SLOTS),
        axis=-1, dst_type=_ANTI_QUANT_DST_TYPES[dtype],
        src_type=npu.float4_e2m1fn_x2,
75
76
77
78
79
80
81
82
83
        scale.reshape(-1, scale_pairs, MX_SCALE_SLOTS),
        axis=-1, dst_type=_ANTI_QUANT_DST_TYPES[dtype],
        src_type=npu.float4_e2m1fn_x2,
    )
    return values.reshape(*packed.shape[:-1], logical_width)


class _MXFP4QDQFunction(torch.autograd.Function):
    """Quantize and decode each Indexer query head, using an identity STE."""
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
                f"block_size {MX_BLOCK_SIZE_32}; no cross-row padding is allowed"
            )
        if x.numel() == 0:
            return x
        npu = import_module("torch_npu")
        packed, scale = npu.npu_dynamic_mx_quant(
            x.reshape(-1, width), dst_type=npu.float4_e2m1fn_x2,
            block_size=MX_BLOCK_SIZE_32, round_mode="rint", scale_alg=MX_SCALE_ALG_OCP,
        )
        values = npu.npu_anti_mx_quant(
            packed, scale, axis=-1, dst_type=_ANTI_QUANT_DST_TYPES[x.dtype],
            src_type=npu.float4_e2m1fn_x2,
        )
        return values.reshape(x.shape)

    @staticmethod
    def backward(ctx: Any, grad_output: Tensor) -> Tensor:
        """Pass gradients through the quantization error with an identity STE."""
        del ctx
        return grad_output


def indexer_qk_quantize_dequantize(query: Tensor) -> Tensor:
    """Apply MXFP4 QDQ per query head with identity STE gradients."""
hyper_parallel/components/quantization/quantizers/csa2/main_kv.py
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84


def _main_row_bytes(width: int, scale_format: str) -> int:
    """Count data and scale bytes, including the BF16-scale cache ABI padding."""
    scale_bytes = _BF16_SCALE_BYTES if scale_format == "e8m7" else _E4M3_SCALE_BYTES
    payload = width // MXFP4_VALUES_PER_BYTE + width // MAIN_KV_GROUP_SIZE * scale_bytes
    if scale_format == "e8m7":
        return (payload + _BF16_CACHE_ROW_ALIGNMENT - 1) // _BF16_CACHE_ROW_ALIGNMENT * _BF16_CACHE_ROW_ALIGNMENT
    return payload


def quantize_main_kv(kv: Tensor, scale_format: str = "e4m3") -> Tensor:
    """Encode Main KV using E2M1 values and group-16 E4M3 or BF16 scales."""
    width = kv.shape[-1]
    if width <= 0 or width % MAIN_KV_GROUP_SIZE:
        raise ValueError(
            f"Main KV last axis {width} is not divisible by group_size {MAIN_KV_GROUP_SIZE}; "
            "no cross-row padding is allowed"
        )
    if kv.numel() == 0:
        return torch.empty((*kv.shape[:-1], _main_row_bytes(width, scale_format)),
                           dtype=torch.uint8, device=kv.device)
    npu = import_module("torch_npu")
    grouped = kv.float().reshape(*kv.shape[:-1], width // MAIN_KV_GROUP_SIZE, MAIN_KV_GROUP_SIZE)
    # Preserve nonfinite groups so quantization cannot hide an overflow.
    amax = torch.nan_to_num(grouped.abs(), nan=float("inf"), posinf=float("inf")).amax(dim=-1)
    scales = amax / MXFP4_MAX_VALUE
    if scale_format == "e4m3":
        scales = scales.clamp(min=_MIN_E4M3_SCALE, max=FP8_E4M3_MAX)
    else:
        scales = scales.clamp_min(torch.finfo(torch.bfloat16).tiny)
    scale_values = torch.where(torch.isinf(amax), float("nan"), scales)
    if scale_format == "e4m3":
        scales = scale_values.to(torch.float8_e4m3fn)
    else:
        scales = scale_values.to(torch.bfloat16)
    normalized = grouped / scales.float().unsqueeze(-1)
    if scale_format == "e8m7":
        normalized = normalized.clamp(-MXFP4_MAX_VALUE, MXFP4_MAX_VALUE)
    data = npu.npu_dtype_cast(normalized, npu.float4_e2m1fn_x2)
    packed = torch.cat((data.reshape(*kv.shape[:-1], width // MXFP4_VALUES_PER_BYTE),
                        scales.view(torch.uint8)), dim=-1)
    padding = _main_row_bytes(width, scale_format) - packed.shape[-1]
    return torch.nn.functional.pad(packed, (0, padding)) if padding else packed


def dequantize_main_kv(packed: Tensor, logical_width: int, dtype: torch.dtype,
                       scale_format: str = "e4m3") -> Tensor:
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112

def dequantize_main_kv(packed: Tensor, logical_width: int, dtype: torch.dtype,
                       scale_format: str = "e4m3") -> Tensor:
    """Decode Main KV bytes and apply their group scales in the requested dtype."""
    if logical_width <= 0 or logical_width % MAIN_KV_GROUP_SIZE:
        raise ValueError("Main KV logical width must be positive and divisible by 16.")
    if packed.numel() == 0:
        return torch.empty((*packed.shape[:-1], logical_width), dtype=dtype, device=packed.device)
    npu = import_module("torch_npu")
    data = packed[..., :logical_width // MXFP4_VALUES_PER_BYTE].contiguous()
    scale_bytes = logical_width // MAIN_KV_GROUP_SIZE * (
        _BF16_SCALE_BYTES if scale_format == "e8m7" else _E4M3_SCALE_BYTES
    )
    scale_dtype = torch.bfloat16 if scale_format == "e8m7" else torch.float8_e4m3fn
    scale = packed[..., logical_width // MXFP4_VALUES_PER_BYTE:logical_width // MXFP4_VALUES_PER_BYTE + scale_bytes]
    scale = scale.contiguous().view(scale_dtype)
    values = npu.npu_dtype_cast(data, dtype, input_dtype=npu.float4_e2m1fn_x2)
    grouped = values.reshape(*data.shape[:-1], logical_width // MAIN_KV_GROUP_SIZE, MAIN_KV_GROUP_SIZE)
    if scale_format == "e8m7":
        if dtype == torch.bfloat16:
            # The cast owns this buffer; scaling cannot mutate packed storage.
            grouped.mul_(scale.unsqueeze(-1))
            return values
        return (grouped.float() * scale.float().unsqueeze(-1)).reshape(*data.shape[:-1], logical_width).to(dtype)
    if dtype == torch.bfloat16:
        grouped.mul_(scale.to(dtype).unsqueeze(-1))
        return values
    return (grouped * scale.to(dtype).unsqueeze(-1)).reshape(*data.shape[:-1], logical_width)


__all__ = ["quantize_main_kv", "dequantize_main_kv"]
hyper_parallel/components/quantization/quantizers/csa2/swa_kv.py
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110


def _scale_slots(width: int) -> int:
    """Round group-32 E8M0 scale slots to the native two-slot ABI."""
    groups = width // SWA_KV_GROUP_SIZE
    return (groups + MX_SCALE_SLOTS - 1) // MX_SCALE_SLOTS * MX_SCALE_SLOTS


def _swa_row_bytes(width: int, scale_format: str) -> int:
    """Count SWA data and scale bytes, including BF16-scale row padding."""
    if scale_format == "e8m0":
        return width + _scale_slots(width)
    payload = width + _BF16_SCALE_BYTES * width // SWA_KV_GROUP_SIZE
    return (payload + _BF16_CACHE_ROW_ALIGNMENT - 1) // _BF16_CACHE_ROW_ALIGNMENT * _BF16_CACHE_ROW_ALIGNMENT


def quantize_swa_kv(kv: Tensor, scale_format: str = "e8m0") -> Tensor:
    """Encode SWA KV rows as E4M3 values with group-32 E8M0 or BF16 scales."""
    width = kv.shape[-1]
    if width <= 0 or width % SWA_KV_GROUP_SIZE:
        raise ValueError("SWA KV last axis must be positive and divisible by 32.")
    if kv.numel() == 0:
        return torch.empty((*kv.shape[:-1], _swa_row_bytes(width, scale_format)),
                           dtype=torch.uint8, device=kv.device)
    if scale_format == "e8m0":
        flat = kv.reshape(-1, width).contiguous()
        npu = import_module("torch_npu")
        data, scale = npu.npu_dynamic_mx_quant(
            flat, dst_type=torch.float8_e4m3fn, block_size=MX_BLOCK_SIZE_32,
            scale_alg=MX_SCALE_ALG_CUBALS,
        )
        return torch.cat((data.view(torch.uint8).reshape(*kv.shape[:-1], width),
                          scale.reshape(*kv.shape[:-1], -1)), dim=-1)
    grouped = kv.float().reshape(*kv.shape[:-1], width // SWA_KV_GROUP_SIZE, SWA_KV_GROUP_SIZE)
    amax = torch.nan_to_num(grouped.abs(), nan=float("inf")).amax(dim=-1)
    scale = (amax / FP8_E4M3_MAX).clamp_min(torch.finfo(torch.bfloat16).tiny).to(torch.bfloat16)
    normalized = (grouped / scale.float().unsqueeze(-1)).clamp(-FP8_E4M3_MAX, FP8_E4M3_MAX)
    data = normalized.to(torch.float8_e4m3fn)
    packed = torch.cat((data.view(torch.uint8).reshape(*kv.shape[:-1], width), scale.view(torch.uint8)), dim=-1)
    padding = _swa_row_bytes(width, scale_format) - packed.shape[-1]
    return torch.nn.functional.pad(packed, (0, padding)) if padding else packed


def dequantize_swa_kv(packed: Tensor, logical_width: int, scale_format: str = "e8m0") -> Tensor:
    """Decode packed SWA rows to BF16 using the selected scale format."""
    if logical_width <= 0 or logical_width % SWA_KV_GROUP_SIZE:
        raise ValueError("SWA KV logical width must be positive and divisible by 32.")
    if packed.numel() == 0:
        return torch.empty((*packed.shape[:-1], logical_width), dtype=torch.bfloat16, device=packed.device)
    data = packed[..., :logical_width].contiguous()
    if scale_format == "e8m0":
        slots = _scale_slots(logical_width)
        scale = packed[..., logical_width:logical_width + slots]
        scale = scale.reshape(*data.shape[:-1], slots // MX_SCALE_SLOTS, MX_SCALE_SLOTS)
        npu = import_module("torch_npu")
        values = npu.npu_anti_mx_quant(
            data.reshape(-1, logical_width).view(torch.float8_e4m3fn),
            scale.reshape(-1, slots // MX_SCALE_SLOTS, MX_SCALE_SLOTS).contiguous(),
            src_type=torch.float8_e4m3fn, dst_type=15,  # BF16 output
        )
        groups = logical_width // SWA_KV_GROUP_SIZE
        invalid_scale = scale.reshape(*packed.shape[:-1], slots)[..., :groups] == _E8M0_NAN_SCALE
        decoded = values.reshape(*packed.shape[:-1], groups, SWA_KV_GROUP_SIZE)
        # Native E4M3 anti-MX maps NaN scales to zero; retain the overflow signal.
        decoded.masked_fill_(invalid_scale.unsqueeze(-1), float("nan"))
        return decoded.reshape(*packed.shape[:-1], logical_width)
    scale_bytes = _BF16_SCALE_BYTES * logical_width // SWA_KV_GROUP_SIZE
    scales = packed[..., logical_width:logical_width + scale_bytes].contiguous().view(torch.bfloat16)
    values = data.view(torch.float8_e4m3fn).to(torch.bfloat16)
    return (values.reshape(*data.shape[:-1], logical_width // SWA_KV_GROUP_SIZE, SWA_KV_GROUP_SIZE)
            * scales.unsqueeze(-1)).reshape(*data.shape[:-1], logical_width)


__all__ = ["quantize_swa_kv", "dequantize_swa_kv"]
hyper_parallel/distributed/context_parallel/csa2_cache_transport.py
 93
 94
 95
 96
 97
 98
 99
100
101

    def wait(self) -> CSA2CacheTensor:
        """Wait once and return the assembled cache in its original axis order."""
        if self.waited:
            raise RuntimeError("a packed sequence dispatch handle cannot be waited twice")
        self.waited = True
        output = _PackedSequenceDispatch.apply(
            self.cache, self.local, self.received, self.handle, self.route, self.group, self.sequence_dim,
        )
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
        route: Per-peer row ranges and splits for this batch.
        group: Process group in sequence-shard order.
    """
    if not -cache.ndim <= sequence_dim < cache.ndim:
        raise ValueError("sequence dispatch dimension is outside the input tensor dimensions")
    sequence_dim %= cache.ndim
    if cache.packed.shape[sequence_dim] != route.local_length:
        raise ValueError("sequence dispatch owner length does not match the bank's physical layout")
    # Materialize only the rows sent to peers; local rows can remain a view.
    local = cache.packed.movedim(sequence_dim, 0)
    if not route.needs_exchange:
        return _AsyncPackedSequenceDispatch(cache, local, None, None, None, route, group, sequence_dim)
    parts = [local.detach().narrow(0, offset, count)
             for offset, count in route.owner_ranges() if count]
    send = torch.cat(parts, dim=0) if parts else local.detach()[:0]
    received = local.new_empty((sum(route.output_splits), *local.shape[1:]))
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179

    @staticmethod
    def backward(ctx: Any, grad: Tensor) -> tuple[Tensor | None, ...]:
        """Restore rank padding and reduce-scatter gradients to the row owners."""
        gather_dim = ctx.gather_dim
        if ctx.slots is not None:
            padded_shape = (*grad.shape[:gather_dim], ctx.padded_total, *grad.shape[gather_dim + 1:])
            padded = grad.new_zeros(padded_shape)
            padded.index_add_(gather_dim, ctx.slots.long(), grad)
        else:
            padded = grad
        send = padded.movedim(gather_dim, 0).contiguous()
        received = grad.new_empty((ctx.padded_total // ctx.world_size, *send.shape[1:]))
        work = dist.reduce_scatter_tensor(
            received, send, op=dist.ReduceOp.SUM, group=ctx.group, async_op=True,
        )
        work.wait()
        local = received.movedim(0, gather_dim).contiguous()
        local = local.narrow(gather_dim, 0, ctx.original_rows)
        return local, None, None, None, None, None, None, None, None


@dataclass
class _AsyncPackedBankGather:
190
191
192
193
194
195
196
197
198
199
200
    waited: bool = False

    def wait(self) -> CSA2CacheTensor:
        """Wait once and return the compacted cache in rank order."""
        if self.waited:
            raise RuntimeError("a packed bank gather handle cannot be waited twice")
        self.waited = True
        return _PackedBankGather.apply(
            self.cache, self.work, self.output, self.slots, self.group,
            self.world_size, self.gather_dim, self.original_rows,
        )
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
        group: Process group in sequence-shard order.
        world_size: Number of ranks in the group.
        gather_dim: Axis containing the rows to gather.
    """
    if counts is not None and len(counts) != world_size:
        raise ValueError("packed bank gather owner counts must cover the CP group")
    original_rows = cache.packed.shape[gather_dim]
    send = cache.packed.movedim(gather_dim, 0).contiguous()
    if counts is not None:
        capacity = max(counts)
        if send.shape[0] != capacity:
            send = torch.cat((send, send.new_zeros((capacity - send.shape[0], *send.shape[1:]))), dim=0)
    else:
        capacity = original_rows
    output = send.new_empty((capacity * world_size, *send.shape[1:]))
    work = dist.all_gather_into_tensor(output, send, group=group, async_op=True)
    slots = _bank_slots(counts, cache.device) if counts is not None else None
    return _AsyncPackedBankGather(cache, work, output, group, world_size, slots, gather_dim, original_rows)


__all__ = ["launch_packed_sequence_dispatch", "launch_packed_bank_gather"]