Diff Coverage

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

Source File Diff Coverage (%) Missing Lines
hyper_parallel/components/functional/aggregate_hidden.py 100%  
hyper_parallel/components/functional/dsa_sparse_attention.py 100%  
hyper_parallel/components/functional/dsa_sparse_attention_rescale.py 13.5% 83-84,107,110,167,171-172,175-183,185,188-189,192-196,198-204,271
hyper_parallel/components/functional/grouped_matmul.py 90.0% 58
hyper_parallel/components/functional/mhc_post.py 100%  
hyper_parallel/components/functional/moe_token_permute.py 100%  
hyper_parallel/components/functional/moe_token_unpermute.py 100%  
hyper_parallel/components/functional/mome.py 100%  
hyper_parallel/components/functional/rms_norm.py 100%  
hyper_parallel/components/functional/rotary_embedding.py 81.2% 110,182,232
hyper_parallel/components/functional/sinkhorn.py 100%  
hyper_parallel/components/functional/sparse_flash_mla.py 100%  
hyper_parallel/components/functional/swiglu.py 92.3% 56,58
hyper_parallel/components/modules/attention/__init__.py 60.0% 34-37
hyper_parallel/components/modules/attention/grouped_query_attention/grouped_query_attention.py 100%  
hyper_parallel/components/modules/attention/multi_latent_attention/multi_latent_attention.py 66.7% 306-307
hyper_parallel/components/modules/common/rms_norm.py 100%  
hyper_parallel/components/modules/grouped_experts.py 14.3% 415-416,472,477-479
hyper_parallel/components/modules/mhc/mhc_post.py 100%  
hyper_parallel/components/modules/mhc/pipelined_mhc.py 100%  
hyper_parallel/components/modules/mlp/swiglu_mlp.py 100%  
hyper_parallel/components/modules/moe/grouped_experts/grouped_experts.py 100%  
hyper_parallel/components/modules/moe/router.py 100%  
hyper_parallel/components/modules/moe/shared_expert.py 100%  
hyper_parallel/components/ops/__init__.py 100%  
hyper_parallel/components/ops/auto_policy.py 100%  
hyper_parallel/components/ops/catalog.py 100%  
hyper_parallel/components/ops/factory.py 100%  
hyper_parallel/components/ops/impl/aggregate_hidden.py 94.9% 123,125,152
hyper_parallel/components/ops/impl/attention.py 95.8% 494-495
hyper_parallel/components/ops/impl/causal_conv1d.py 31.8% 115,122,137-139,146-151,157,166-167,169
hyper_parallel/components/ops/impl/deepseek_sparse_attention.py 63.2% 366-369,522-524
hyper_parallel/components/ops/impl/dsa_indexer.py 76.9% 298-300
hyper_parallel/components/ops/impl/dsa_indexer_kl.py 83.9% 446,615,629-631
hyper_parallel/components/ops/impl/gdn.py 57.1% 122,173-174,184-186
hyper_parallel/components/ops/impl/grouped_matmul.py 74.2% 122-123,140-141,148,166-168,171-172,174,184-185,187,189,256,271
hyper_parallel/components/ops/impl/grouped_swiglu.py 91.7% 129
hyper_parallel/components/ops/impl/kda.py 28.6% 330,335,396-397,407-417
hyper_parallel/components/ops/impl/mhc_post.py 100%  
hyper_parallel/components/ops/impl/moe_router.py 71.4% 149-150
hyper_parallel/components/ops/impl/moe_token_permute.py 100%  
hyper_parallel/components/ops/impl/moe_token_unpermute.py 100%  
hyper_parallel/components/ops/impl/rms_norm.py 100%  
hyper_parallel/components/ops/impl/rope.py 91.7% 275,294,296,299,301
hyper_parallel/components/ops/impl/sinkhorn.py 100%  
hyper_parallel/components/ops/impl/swiglu.py 41.7% 148-150,152,154-158,160-161,163,169,174
hyper_parallel/components/ops/registry.py 100%  
hyper_parallel/components/ops/spec.py 100%  
hyper_parallel/distributed/expert_parallel/ep_context.py 100%  
hyper_parallel/distributed/expert_parallel/experts.py 14.3% 159-162,164,359
hyper_parallel/distributed/expert_parallel/moonep_context.py 33.3% 104-105
hyper_parallel/components/functional/dsa_sparse_attention_rescale.py
79
80
81
82
83
84
85
86
87
88
    batch_size, sequence_length, num_heads,
):
    """Combine the two attention outputs using stable softmax weights."""
    sink_output = rearrange(sink_output, "s b (n d) -> b s n d", n=num_heads)
    softmax_max = softmax_max.transpose(0, 1).reshape(batch_size, sequence_length, num_heads)
    softmax_sum = softmax_sum.transpose(0, 1).reshape(batch_size, sequence_length, num_heads)
    sink_softmax_max = sink_softmax_max[:, :, :, 0].transpose(1, 2)
    sink_softmax_sum = sink_softmax_sum[:, :, :, 0].transpose(1, 2)
    combined_max = torch.maximum(softmax_max, sink_softmax_max)
    output_sum = softmax_sum * torch.exp(softmax_max - combined_max)
103
104
105
106
107
108
109
110
111
112
113
114
        rearrange(tensor, "b s n d -> (b s) n d")
        for tensor in (query_nope, compressed_kv, query_rope, key_rope)
    ]
    grad_output = rearrange(output_scale * grad_rescaled_output, "b s n d -> (b s) n d")
    output = rearrange(output, "b s n d -> (b s) n d")
    if query_rope.size(-1) > 0:
        grad_output = grad_output[:, :, :-query_rope.size(-1)]
        output = output[:, :, :-query_rope.size(-1)]
    gradients = torch.ops.custom.npu_sparse_flash_attention_grad_enhance(
        query_nope, compressed_kv, compressed_kv, topk_indices,
        grad_output.to(sink_key.dtype), output, softmax_max, softmax_sum, ctx.scale,
        sparse_block_size=1,
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
def _normalizer_backward(ctx, grad_output, saved_tensors):
    """Differentiate the two softmax masses used to merge sparse and sink attention."""
    query, key, q_rope, k_rope, sink_key, _, indices, maximum, total = saved_tensors[:9]
    alpha, beta, sparse_output, sink_output = saved_tensors[11:]
    mass_gradient = (
        (grad_output.float() * (sparse_output.float() - sink_output.float())).sum(-1)
        * alpha.squeeze(-1) * beta.squeeze(-1)
    )
    query, key, q_rope, k_rope = (tensor.flatten(0, 1).float() for tensor in (query, key, q_rope, k_rope))
    grad_query, grad_key, grad_q_rope, grad_k_rope = (
        torch.zeros_like(tensor) for tensor in (query, key, q_rope, k_rope)
    )
    mass_gradient = mass_gradient.flatten(0, 1)
    for qs, qe, ks, ke in packed_segments(ctx.actual_seq_qlen, ctx.actual_seq_kvlen):
        for start in range(qs, qe, 32):
            end = min(start + 32, qe)
            selected_indices = indices[start:end]
            causal_end = torch.arange(start, end, device=query.device) - qe + ke - ks
            selected, valid = selected_packed_keys(key[ks:ke], selected_indices, causal_end=causal_end)
            rotary, _ = selected_packed_keys(k_rope[ks:ke], selected_indices, causal_end=causal_end)
            scores = (selected_packed_scores(query[start:end], selected)
                      + selected_packed_scores(q_rope[start:end], rotary)) * ctx.scale
            probabilities = (
                scores.masked_fill(~valid.unsqueeze(2), -torch.inf) - maximum[:, start:end].transpose(0, 1)[..., None]
            ).exp() / total[:, start:end].transpose(0, 1)[..., None].clamp_min(torch.finfo(torch.float32).tiny)
            weights = probabilities * mass_gradient[start:end].unflatten(-1, scores.shape[1:3])[..., None] * ctx.scale
            for source, selected_keys, query_grad, key_grad in (
                (query, selected, grad_query, grad_key), (q_rope, rotary, grad_q_rope, grad_k_rope),
            ):
                query_grad[start:end] = torch.einsum("tngk,tnkd->tngd", weights, selected_keys).flatten(1, 2)
                rows = torch.einsum("tngk,tngd->tnkd", weights, source[start:end].unflatten(1, scores.shape[1:3]))
                positions = selected_indices.clamp(0, ke - ks - 1).long() + ks
                heads = torch.arange(key.shape[1], device=key.device)[None, :, None].expand_as(positions)
                key_grad.index_put_((positions.flatten(), heads.flatten()), rows.flatten(0, 2), accumulate=True)

    full_query = torch.cat((query, q_rope), dim=-1).reshape(*saved_tensors[0].shape[:-1], -1)
    sink_probabilities = (torch.einsum("bthd,bshd->bths", full_query, sink_key.float()) * ctx.scale).softmax(-1)
    sink_weights = -mass_gradient.reshape_as(saved_tensors[0][..., 0])[..., None] * sink_probabilities * ctx.scale
    sink_query_gradient = torch.einsum("bths,bshd->bthd", sink_weights, sink_key.float()).flatten(0, 1)
    sink_key_gradient = torch.einsum("bths,bthd->bshd", sink_weights, full_query)
    sink_q, sink_q_rope = sink_query_gradient.split((query.shape[-1], q_rope.shape[-1]), dim=-1)
    return (
        (grad_query + sink_q).reshape_as(saved_tensors[0]),
        grad_key.reshape_as(saved_tensors[1]),
        (grad_q_rope + sink_q_rope).reshape_as(saved_tensors[2]),
        grad_k_rope.reshape_as(saved_tensors[3]),
267
268
269
270
271
272
273
274
275
        ctx.scale = scale
        ctx.keep_prob = keep_prob
        ctx.actual_seq_qlen = actual_seq_qlen
        ctx.actual_seq_kvlen = actual_seq_kvlen
        ctx.mark_non_differentiable(softmax_max, softmax_sum)
        return rescaled_output, softmax_max, softmax_sum

    @staticmethod
    def backward(
hyper_parallel/components/functional/grouped_matmul.py
54
55
56
57
58
59
60
    if bias is None and group_type == 0 and group_list_type == 0 and not gemm_fusion:
        if group_list is not None:
            ends = torch.as_tensor(group_list, device=x.device, dtype=torch.int64)
            return selected_grouped_matmul(x, weight, ends)
    return npu_grouped_matmul(
        x, weight, bias, group_list, group_type, group_list_type, gemm_fusion, original_weight,
    )
hyper_parallel/components/functional/rotary_embedding.py
106
107
108
109
110
111
112
113
    if positions is None:
        return tensor
    cos, sin = (part.to(tensor.dtype) for part in positions)
    if cos.ndim == 2:
        cos, sin = cos.unsqueeze(0), sin.unsqueeze(0)
    if interleaved:
        return rope_interleaved_single(tensor, cos, sin, unsqueeze_dim=2)
    return rope(tensor, cos.unsqueeze(2), sin.unsqueeze(2))
178
179
180
181
182
183
184
185
186
        cos = cos.unsqueeze(-2)
        sin = sin.unsqueeze(-2)

    if use_fused_rotary_pos_emb and t.device.type != "cpu":
        torch_npu = require_package("torch_npu")
        rotary_mode = "interleave" if rotary_interleaved else "half"
        sequence_length, batch_size, num_heads, head_dim = t.shape
        if rotary_interleaved and batch_size > 1 and sequence_length > 1:
            t = torch_npu.npu_rotary_mul(
228
229
230
231
232
233
234
235
236
    cos_ = torch.cos(freqs).to(t.dtype)
    sin_ = torch.sin(freqs).to(t.dtype)

    rotary_mode = "interleave" if rotary_interleaved else "half"
    torch_npu = require_package("torch_npu")
    t = torch_npu.npu_rotary_mul(t.clone(), cos_, sin_, rotary_mode=rotary_mode)

    if t_pass is not None:
        return torch.cat((t, t_pass), dim=-1)
hyper_parallel/components/functional/swiglu.py
52
53
54
55
56
57
58
59
60
61
62
    Returns:
        Activated states in the declared computation dtype.
    """
    if activation_dtype not in ("input", "float32"):
        raise ValueError("activation_dtype must be input or float32")
    if isinstance(limit, bool) or not isinstance(limit, (int, float)) or not isfinite(limit):
        raise ValueError("SwiGLU limit must be finite")
    if activation_dtype == "float32":
        return swiglu_clamped(gate, up, limit)
    if limit > 0:
        gate, up = gate.clamp(max=limit), up.clamp(-limit, limit)
hyper_parallel/components/modules/attention/__init__.py
30
31
32
33
34
35
36
37
38
39
40
def _load_attention_member(name: str) -> Any:
    """Keep sequence-layout imports independent of attention family registration."""
    if name not in __all__:
        raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
    module = importlib.import_module(f"{__name__}.deepseek_sparse_attention")
    value = getattr(module, name)
    globals()[name] = value
    return value


__getattr__ = _load_attention_member
hyper_parallel/components/modules/attention/multi_latent_attention/multi_latent_attention.py
302
303
304
305
306
307
308
309
310
311
        """Keep the source-compatible YaRN factor and explicit scaling override."""
        rope_settings = getattr(config, "rope_parameters", None) or getattr(config, "rope_scaling", None) or {}
        if (rope_settings.get("rope_type", rope_settings.get("type", "default")) != "default"
                and rope_settings.get("mscale_all_dim", 0)):
            factor = rope_settings["factor"]
            mscale = 1.0 if factor <= 1 else 0.1 * rope_settings["mscale_all_dim"] * math.log(factor) + 1.0
            default *= mscale * mscale
        return getattr(config, "scaling", default)

    def reset_parameters(self) -> None:
hyper_parallel/components/modules/grouped_experts.py
411
412
413
414
415
416
417
418
419
420
            fc1_output = torch.matmul(permuted, gate_up_proj_2d)

        # down
        if not self.router_gating_in_fp32 and permuted_probs is not None:
            activated = self.activation_func(fc1_output)
            fc1_output = (activated * permuted_probs.reshape(*fc1_output.shape[:-1], 1)).to(activated.dtype)
        else:
            fc1_output = self.activation_func(fc1_output)

        if self.use_2d_experts:
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
    ) -> torch.Tensor:
        """Run grouped experts with the Transformers Experts interface."""
        hidden_shape = hidden_states.shape
        hidden_states_flat = hidden_states.view(-1, hidden_states.shape[-1])
        permuted_tokens, order, positions = moe_token_permute(  # pylint: disable=not-callable
            hidden_states_flat,
            top_k_index,
        )
        flatten_probs = top_k_weights.view(-1)
        permuted_probs = flatten_probs.index_select(0, order)
        ids = top_k_index.reshape(-1).long()
        tokens_per_expert = ids.new_zeros(self.num_experts).scatter_add_(0, ids, torch.ones_like(ids))
        expert_outputs = self.forward_expert_major(
            permuted_tokens,
            tokens_per_expert,
            permuted_probs,
hyper_parallel/components/ops/impl/aggregate_hidden.py
119
120
121
122
123
124
125
126
127
128
129
    ) -> torch.Tensor:
        """Run the aggregate-hidden forward operator."""
        reason = _check_omni(input_tensor)
        if reason is not None:
            raise ValueError(reason)
        if not input_tensor.numel():
            raise ValueError("Omni aggregation requires nonempty states")
        ctx.save_for_backward(input_tensor, weight, mask)
        return torch.ops.custom.npu_aggregate_hidden(input_tensor, weight, mask=mask)

    @staticmethod
148
149
150
151
152
153
154
155
156


def _check_omni(input_tensor: torch.Tensor) -> str | None:
    if input_tensor.dtype != torch.bfloat16:
        return "Omni aggregate_hidden requires BF16 inputs and weights"
    return None


def register_aggregate_hidden(registry: OpRegistry) -> None:
hyper_parallel/components/ops/impl/attention.py
490
491
492
493
494
495
496
497
498
499
    *, causal: bool, scale: float, dropout: float, window: int | None,
    lengths: AttentionLengths | None, query_offset: int | None,
) -> torch.Tensor:
    """Translate dense attention arguments for the NPU fusion kernel."""
    if lengths is not None and mask is not None:
        raise ValueError("packed NPU attention requires document ends without an external mask")
    options = {} if lengths is None else {"actual_q_len": lengths[0], "actual_kv_len": lengths[1]}
    if query_offset is not None and causal and lengths is None:
        if mask is not None and mask.ndim == 2:
            mask = mask.to(torch.bool)[:, None, None, :]
hyper_parallel/components/ops/impl/causal_conv1d.py
111
112
113
114
115
116
117
118
119

def _load_triton() -> CausalConv1dFn:
    require_package("triton.backends.ascend")
    require_symbol(require_package("fla.modules.conv", loader=import_fla_module), "causal_conv1d")
    return _implementation("triton")


def _load_ascendc() -> CausalConv1dFn:
    kernels = require_package("fla_npu.ops.ascendc")
118
119
120
121
122
123
124
125
126
def _load_ascendc() -> CausalConv1dFn:
    kernels = require_package("fla_npu.ops.ascendc")
    require_symbol(kernels, "causal_conv1d_fn")
    require_symbol(kernels, "causal_conv1d_bwd")
    return _implementation("ascendc")


def register_causal_conv1d(registry: OpRegistry) -> None:
    """Register dense and packed short convolution with a shared Torch reference."""
133
134
135
136
137
138
139
140
141
142
143
def _validate_fused_inputs(
    x: torch.Tensor, weight: torch.Tensor, bias: torch.Tensor | None = None, *, dilation: int = 1, backend: str
) -> None:
    """Reject unsupported inputs in the selected fused implementation."""
    reason = 'fused convolution requires nonempty batches and dilation one' if dilation != 1 or not x.numel() else None
    blocked = ()
    if (
        weight.shape[-1] not in (2, 3, 4)
        or x.shape[-1] % 16
        or x.dtype not in (torch.bfloat16, torch.float16)
        or (weight.dtype != x.dtype)
142
143
144
145
146
147
148
149
150
151
152
153
154
155
        or x.dtype not in (torch.bfloat16, torch.float16)
        or (weight.dtype != x.dtype)
        or (bias is not None and bias.dtype != x.dtype)
    ):
        blocked = (('ascendc', 'requires width 2/3/4, 16-aligned channels and matching BF16/FP16 dtypes'),)
    if reason is not None:
        raise ValueError(reason)
    for name, message in blocked:
        if name == {'triton': 'triton_ascend'}.get(backend, backend):
            raise ValueError(message)


def _implementation(backend: str) -> CausalConv1dFn:
    """Bind a fused implementation and validate its inputs on every invocation."""
153
154
155
156
157
158
159
160
161

def _implementation(backend: str) -> CausalConv1dFn:
    """Bind a fused implementation and validate its inputs on every invocation."""

    def run(
        x: torch.Tensor,
        weight: torch.Tensor,
        bias: torch.Tensor | None,
        info: PackedSequenceInfo | None = None,
162
163
164
165
166
167
168
169
        *,
        dilation: int = 1,
    ) -> torch.Tensor:
        """Execute the selected fused convolution without changing backend."""
        _validate_fused_inputs(x, weight, bias, dilation=dilation, backend=backend)
        return fused_causal_conv1d(x, weight, bias, info, dilation=dilation, backend=backend)

    return run
hyper_parallel/components/ops/impl/deepseek_sparse_attention.py
362
363
364
365
366
367
368
369
370
371
372
373
    return fused_packed_attention(x, key, query_rope, key_rope, topk_indices, scale, query_ends, key_ends)


def _load_cann_absorbed() -> PackedDeepseekSparseAttentionFn:
    extension = require_package("torch_npu")
    require_symbol(extension, "npu_sparse_flash_attention")
    if not hasattr(extension, "npu_sparse_flash_attention_grad"):
        require_symbol(require_package("cann_ops_transformer.ops"), "sparse_flash_attention_grad")
    return _cann_absorbed


def _load_omni_sink() -> PackedDeepseekSparseAttentionFn:
518
519
520
521
522
523
524
525
526
527
528
    layout: DsaQueryLayout, global_sequence_length: int, raw_key_offset: int = 0,
    main_key_offset: int = 0, global_key_length: int | None = None,
) -> torch.Tensor:
    """Run compressed-bank sparse MLA through the CANN adapter."""
    reason = _attention_input_error(x, layout, window, topk_indices, global_sequence_length, global_key_length)
    if reason is not None:
        raise ValueError(reason)
    del global_sequence_length, global_key_length
    output = sparse_flash_mla(
        x, raw_key, compressed_key, topk_indices, sinks, scale, layout.compress_ratio, window,
        layout.query_offset, layout.segments, raw_key_offset, main_key_offset, layout.raw_document_starts(),
hyper_parallel/components/ops/impl/dsa_indexer.py
294
295
296
297
298
299
300
301
302
303
304
    layout: DsaQueryLayout, sparse_count: int, query_chunk_size: int = 256,
    reduce_sum: ReduceSum | None = None,
) -> torch.Tensor:
    """Select compressed causal TopK keys with the CANN LI V2 kernel."""
    reason = _indexer_input_error(x, layout, reduce_sum)
    if reason is not None:
        raise ValueError(reason)
    del reduce_sum
    _validate_indexer_inputs(x, key, merge_weight, layout, query_chunk_size)
    validate_indexer_tensors(x, key, merge_weight)
    return lightning_indexer(x, key, merge_weight, layout.compress_ratio, min(sparse_count, key.shape[1]),
hyper_parallel/components/ops/impl/dsa_indexer_kl.py
442
443
444
445
446
447
448
449
450

def _load_cann_packed_kl() -> PackedDsaKlFn:
    extension = require_package("torch_npu")
    require_symbol(extension, "npu_sparse_lightning_indexer_grad_kl_loss")
    return _cann_packed_kl


def _cann_packed_kl(*args: Any, **kwargs: Any) -> torch.Tensor:
    """Return stable sparse KL with CANN's precomputed student gradients."""
611
612
613
614
615
616
617
618
619
    x: torch.Tensor, index_key: torch.Tensor, topk_indices: torch.Tensor,
    layout: DsaQueryLayout | None, reduce_sum: ReduceSum | None,
) -> str | None:
    """Explain why the CANN KL candidate cannot represent this call."""
    if layout is None or _indexer_input_error(x, layout, reduce_sum) is not None:
        return "fused KL requires BF16 D=128, ordinary TopK512, document segments and no TP reduction"
    if x.shape[2] not in (8, 16, 32, 64) or not min(512, index_key.shape[1]) <= topk_indices.shape[-1] <= 512:
        return "fused KL requires supported head counts and ordinary TopK512 indices"
    return None
625
626
627
628
629
630
631
632
633
634
635
    sinks: torch.Tensor, *, attention_scale: float, loss_coeff: float, query_chunk_size: int = 256,
    reduce_sum: ReduceSum | None = None, layout: DsaQueryLayout | None = None,
) -> torch.Tensor:
    """Validate compressed selections and invoke the fused CANN KL adapter."""
    reason = _indexer_kl_input_error(x, index_key, topk_indices, layout, reduce_sum)
    if reason is not None:
        raise ValueError(reason)
    del reduce_sum
    if query_chunk_size <= 0:
        raise ValueError(f"query_chunk_size must be positive, got {query_chunk_size}")
    indices = _mask_compressed_keys(topk_indices, layout, x)
hyper_parallel/components/ops/impl/gdn.py
118
119
120
121
122
123
124
125
126
        info: PackedSequenceInfo | None = None,
    ) -> torch.Tensor:
        """Run zero-state GDN with per-call document boundaries."""
        if backend != "eager":
            _validate_fused_inputs(x, key, value, gate, beta, chunk_size=chunk_size)
        offsets = None
        if info is not None:
            offsets = info.materialize(x.device, chunk_size).cu_seqlens if backend == "triton" else info.local_offsets
        output, _ = chunk_gated_delta_rule(
169
170
171
172
173
174
175
176
177
178
    *,
    chunk_size: int = 64,
) -> None:
    """Reject unsupported inputs in the selected fused implementation."""
    reason = None
    if (
        chunk_size != 64
        or x.shape[-1] != 128
        or value.shape[-1] != 128
        or (x.dtype != torch.bfloat16)
180
181
182
183
184
185
186
        or (value.dtype != x.dtype)
        or (beta.dtype != x.dtype)
        or (gate.dtype != torch.float32)
    ):
        reason = 'fused GDN requires chunk size 64, head dimension 128, BF16 Q/K/V/beta and FP32 gate'
    if reason is not None:
        raise ValueError(reason)
hyper_parallel/components/ops/impl/grouped_matmul.py
118
119
120
121
122
123
124
125
126
127
            group_list_type=group_list_type
        )

        if group_list_data_type == 0:
            ctx.save_for_backward(x, weight)
            ctx.group_list = group_list
        else:
            ctx.save_for_backward(x, weight, group_list)

        ctx.original_weight = original_weight
136
137
138
139
140
141
142
143
144
145
        torch_npu = require_package("torch_npu")
        grad_outputs = grad_outputs.contiguous()

        if ctx.group_list_data_type == 0:
            x, weight = ctx.saved_tensors
            group_list = ctx.group_list
        else:
            x, weight, group_list = ctx.saved_tensors

        original_weight = ctx.original_weight
144
145
146
147
148
149
150
151
152

        original_weight = ctx.original_weight

        if isinstance(group_list, (list, tuple)):
            group_list_tensor = torch.tensor(group_list, device=x.device, dtype=torch.int64)
        else:
            group_list_tensor = group_list

        dx_list = torch_npu.npu_grouped_matmul(
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178

        grad_weight = None
        use_fusion = False
        if ctx.gemm_fusion:
            if hasattr(original_weight, 'main_grad'):
                if original_weight.main_grad is not None:
                    use_fusion = True

        if use_fusion:
            n_size = original_weight.main_grad.shape[-1]
            main_grad_view = original_weight.main_grad.view(-1, n_size)

            torch_npu.npu_grouped_matmul_add_(
                main_grad_view,
                x,
                grad_outputs,
                group_list_tensor,
180
181
182
183
184
185
186
187
188
189
190
191
192
193
                transpose_weight=False,
                group_type=2
            )

            if getattr(weight, 'zero_out_wgrad', False):
                grad_weight = torch.zeros_like(weight)
            else:
                grad_weight = torch.empty_like(weight)

            original_weight.grad_added_to_main_grad = True
        else:
            numel = x.nelement()
            if (
                not torch.compiler.is_compiling()
252
253
254
255
256
257
258
259
260
    require_symbol(require_package("torch_npu"), "npu_grouped_matmul")

    def run(x: torch.Tensor, weight: torch.Tensor, group_list: torch.Tensor) -> torch.Tensor:
        """Translate cumulative row boundaries for the selected grouped matmul kernel."""
        return npu_grouped_matmul(
            x, weight, bias=None, group_list=group_list.to(torch.int64), group_type=0, group_list_type=0,
        )

    return run
267
268
269
270
271
272
273
274
    def run(x: torch.Tensor, weight: torch.Tensor, group_list: torch.Tensor) -> torch.Tensor:
        """Translate cumulative row boundaries for the selected grouped matmul kernel."""
        reason = check_torch_grouped_mm(x)
        if reason is not None:
            raise ValueError(reason)
        return torch._grouped_mm(x, weight, offs=group_list.to(torch.int32))  # pylint: disable=protected-access

    return run
hyper_parallel/components/ops/impl/grouped_swiglu.py
125
126
127
128
129
130
131
132
133
) -> torch.Tensor:
    """Apply grouped expert SwiGLU with optional intermediate routing weights."""
    reason = check_torch_grouped_mm(x)
    if reason is not None:
        raise ValueError(reason)
    if x.shape[0] == 0:
        return _empty_output(x, w1, w2, w3, scores)
    offs = counts.cumsum(0, dtype=torch.int32)
    # Transpose views preserve the parameter storage across pending forwards.
hyper_parallel/components/ops/impl/kda.py
326
327
328
329
330
331
332
333
334
335
336
337
338
339
        scale: float | None = None,
        info: PackedSequenceInfo | None = None,
    ) -> torch.Tensor:
        """Run the selected fused KDA kernel with per-call document boundaries."""
        _validate_fused_inputs(
            x, key, value, gate, beta, lower_bound=lower_bound, chunk_size=chunk_size, backend=backend
        )
        offsets = None
        if info is not None:
            offsets = info.materialize(x.device, chunk_size).cu_seqlens if backend == "triton" else info.local_offsets
        output, _ = chunk_kda(
            x,
            key,
            value,
392
393
394
395
396
397
398
399
400
401
    chunk_size: int = 64,
    backend: str,
) -> None:
    """Reject unsupported inputs in the selected fused implementation."""
    reason = None
    if (
        lower_bound is None
        or not -5.0 <= lower_bound < 0
        or chunk_size != 64
        or (x.shape[-1] != 128)
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
        or (x.dtype != torch.bfloat16)
        or (key.dtype != x.dtype)
        or (value.dtype != x.dtype)
    ):
        reason = 'fused KDA requires a safe gate, chunk size 64, head dimension 128 and BF16 Q/K/V'
    blocked = []
    if gate.dtype != x.dtype or beta.dtype != x.dtype:
        blocked.append(('triton_ascend', 'requires BF16 gate and beta'))
    if x.shape[2] != value.shape[2]:
        blocked.append(('ascendc', 'requires matching Q/K/V head counts'))
    if reason is not None:
        raise ValueError(reason)
    for name, message in blocked:
        if name == {'triton': 'triton_ascend'}.get(backend, backend):
            raise ValueError(message)
hyper_parallel/components/ops/impl/moe_router.py
145
146
147
148
149
150
151
152
153
154
        x: torch.Tensor, weight: torch.Tensor, bias: torch.Tensor, vision_bias: torch.Tensor | None,
        image_mask: torch.Tensor | None, top_k: int, scoring_func: str, scale: float,
    ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
        """Apply MegaGate using the shared learned routing contract."""
        if scoring_func != "sqrtsoftplus" or x.ndim != 3 or x.numel() == 0:
            raise ValueError("MegaGate requires nonempty batched tokens and sqrtsoftplus scoring")
        del scoring_func
        return mega_gate(
            x, weight, bias, _plan_for_device(x.device), vision_bias=vision_bias,
            image_mask=None if image_mask is None else image_mask.reshape(-1).contiguous(),
hyper_parallel/components/ops/impl/rope.py
271
272
273
274
275
276
277
278
279
            sin.reshape(batch_size * seq_length, 1, 1, head_dim),
            rotary_mode="interleave",
        ).reshape(seq_length, batch_size, num_heads, head_dim)
    else:
        rotated = torch_npu.npu_rotary_mul(
            sequence_first.clone(),
            cos.unsqueeze(-2),
            sin.unsqueeze(-2),
            rotary_mode="interleave",
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
    x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, *, unsqueeze_dim: int = 1,
) -> torch.Tensor:
    """Adapt one adjacent-pair tensor to the NPU rotation kernel."""
    if unsqueeze_dim not in (1, 2):
        raise ValueError("NPU interleaved RoPE supports unsqueeze_dim 1 or 2")
    if cos.ndim == 2:
        cos, sin = cos.unsqueeze(0), sin.unsqueeze(0)
    rotary_dim = cos.shape[-1]
    if rotary_dim != sin.shape[-1] or rotary_dim % 2 or rotary_dim > x.shape[-1]:
        raise ValueError("RoPE requires matching, even frequency dimensions within the input head dimension")
    if not rotary_dim:
        return x
    rotated, tail = x.split((rotary_dim, x.shape[-1] - rotary_dim), dim=-1)
    # Transformers repeats frequency half-bands; the NPU expects adjacent pairs.
    cos = cos[..., : rotary_dim // 2].repeat_interleave(2, dim=-1)
    sin = sin[..., : rotary_dim // 2].repeat_interleave(2, dim=-1)
hyper_parallel/components/ops/impl/swiglu.py
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167


def _load_npu() -> SwiGLUFn:
    """Load the NPU SwiGLU adapter preserving native intermediate rounding."""
    extension = require_package("torch_npu")
    require_symbol(extension, "npu_swiglu")
    kernel = extension.npu_swiglu

    def run(x: torch.Tensor, dim: int = -1) -> torch.Tensor:
        """Preserve native's rounded SiLU intermediate before multiplying by Up."""
        if x.shape[dim] % 2:
            raise ValueError("SwiGLU requires an evenly packed Gate/Up dimension")
        if x.dtype not in (torch.float16, torch.bfloat16):
            return kernel(x, dim=dim)
        gate, up = x.chunk(2, dim=dim)
        # A single fused product rounds only once; native rounds SiLU as well.
        activated = kernel(torch.cat((gate, torch.ones_like(gate)), dim=dim), dim=dim)
        return activated * up

    return run


def _load_npu_clamped() -> ClampedSwiGLUFn:
    kernel = _load_npu()
165
166
167
168
169
170
171
172
173
174
175
176
177
178

def _load_npu_clamped() -> ClampedSwiGLUFn:
    kernel = _load_npu()

    def run(x: torch.Tensor, up: torch.Tensor, limit: float) -> torch.Tensor:
        """Clamp separate projections in FP32 and apply the packed activation kernel."""
        gate, up = _clamp(x, up, limit)
        return kernel(torch.cat((gate, up), dim=-1), dim=-1)

    return run


def register_swiglu(registry: OpRegistry) -> None:
    """Register packed and clamped SwiGLU under the same selection key."""
hyper_parallel/distributed/expert_parallel/experts.py
155
156
157
158
159
160
161
162
163
164
165
166
167
168
        if callable(grouped_forward):
            sorted_output = grouped_forward(sorted_states, local_expert_counts)
        else:
            gate_weight, up_weight, down_weight = resolve_swiglu_weights(experts)
            if up_weight is None:
                boundaries = local_expert_counts.cumsum(0)
                packed = grouped_matmul(sorted_states, gate_weight.transpose(1, 2), boundaries)
                sorted_output = grouped_matmul(swiglu(packed), down_weight.transpose(1, 2), boundaries)
            else:
                sorted_output = grouped_swiglu(
                    sorted_states, gate_weight, down_weight, up_weight, local_expert_counts,
                )
        output = torch.empty_like(sorted_output)
        output[token_order] = sorted_output
355
356
357
358
359
360
361
362
363
        and flattened_states.device.type == "npu" and keep is None
    )
    unpermute_indices = None
    if use_fused_moe_token_permute_and_unpermute:
        dispatched_states, dispatch_order, unpermute_indices = moe_token_permute(
            flattened_states, topk_indices,
        )
    else:
        # Global IDs are contiguous across destination ranks.
hyper_parallel/distributed/expert_parallel/moonep_context.py
100
101
102
103
104
105
106
107
108
109
            rows = torch.arange(counts.numel(), device=counts.device).repeat_interleave(
                counts, output_size=hidden.shape[0],
            )
            ids = torch.empty_like(rows).scatter_(0, receive_order, rows)
            hidden, _, inverse = moe_token_permute(hidden.contiguous(), ids.unsqueeze(-1))
            inverse = inverse.to(torch.int32)
        else:
            hidden = hidden.index_select(0, receive_order)
            inverse = torch.empty_like(receive_order, dtype=torch.int32).scatter_(
                0, receive_order, torch.arange(receive_order.numel(), device=receive_order.device, dtype=torch.int32),