Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 15 additions & 11 deletions hyper_parallel/components/modules/mla_attention.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,20 @@ def _project_latents(self, hidden_states: torch.Tensor) -> _MLALatents:
key_rope.view(batch_size, 1, sequence_length, self.qk_rope_head_dim),
)

def _expand_key_value(self, kv_nope: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
"""Expand cached or current KV latents into head-wise keys and values."""
kv_states = self.kv_b_proj(kv_nope).view(
kv_nope.shape[0],
kv_nope.shape[2],
self.num_heads,
self.qk_nope_head_dim + self.v_head_dim,
).transpose(1, 2)
return torch.split(
kv_states,
(self.qk_nope_head_dim, self.v_head_dim),
dim=-1,
)

def _project_attention_inputs(
self,
hidden_states: torch.Tensor,
Expand All @@ -262,17 +276,7 @@ def _project_attention_inputs(
kv_nope = latents.kv_nope
if past_key_values is not None:
kv_nope, key_rope = past_key_values.update(kv_nope, key_rope, self.layer_idx)
kv_states = self.kv_b_proj(kv_nope).view(
latents.batch_size,
kv_nope.shape[2],
self.num_heads,
self.qk_nope_head_dim + self.v_head_dim,
).transpose(1, 2)
key_nope, value_states = torch.split(
kv_states,
(self.qk_nope_head_dim, self.v_head_dim),
dim=-1,
)
key_nope, value_states = self._expand_key_value(kv_nope)
return (
torch.cat((latents.query_pass.transpose(1, 2), query_rope), dim=-1),
torch.cat((key_nope, key_rope.expand(-1, self.num_heads, -1, -1)), dim=-1),
Expand Down
12 changes: 8 additions & 4 deletions hyper_parallel/core/multicore/modules/_precision.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,15 @@
import torch


def preserve_fp32_parameters(
def preserve_fp32_tensors(
module: torch.nn.Module, transform: Callable[[torch.Tensor], torch.Tensor], names: Iterable[str],
) -> Callable[[torch.Tensor], torch.Tensor]:
"""Wrap Module._apply without rounding protected Parameters or their existing gradients.
"""Wrap Module._apply without rounding protected parameters, buffers or existing gradients.

Args:
module: Module holding the protected control Parameters.
module: Module holding the protected control tensors.
transform: Requested parameter device or dtype transformation.
names: Names of control Parameters which must retain FP32 values.
names: Local names of parameters or buffers which must retain FP32 values.
"""
protected = set()
for name in names:
Expand All @@ -51,3 +51,7 @@ def apply(tensor: torch.Tensor) -> torch.Tensor:
return tensor.to(device=converted.device, dtype=torch.float32)

return apply


# Keep the existing parameter-only entry point compatible.
preserve_fp32_parameters = preserve_fp32_tensors
3 changes: 3 additions & 0 deletions hyper_parallel/core/optimizer/swap_optimizer_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1916,6 +1916,9 @@ class SwapOptimizer(torch.optim.Optimizer):

def __init__(self, optimizer: Any, config: Any, adapter_factory: AdapterFactory) -> None:
"""Wrap a leaf with its family adapter and independent transfer runtime."""
# The pipeline calls adapter updates directly, bypassing the leaf's step hooks.
if optimizer._optimizer_step_pre_hooks or optimizer._optimizer_step_post_hooks:
raise ValueError("Optimizer-state swap does not support step hooks; disable swap before wrapping")
# Do not call ``torch.optim.Optimizer.__init__``: the wrapped base
# optimizer already owns param_groups/state/defaults. Inheriting keeps
# PyTorch LR schedulers and isinstance checks happy while this wrapper
Expand Down
64 changes: 46 additions & 18 deletions hyper_parallel/distributed/context_parallel/mla_context_parallel.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

from __future__ import annotations

from collections.abc import Sequence
from collections.abc import Callable, Sequence
from dataclasses import dataclass
from functools import lru_cache
import math
Expand Down Expand Up @@ -154,7 +154,7 @@ def mla_all_gather(tensor: torch.Tensor, sequence_dim: int, cp_mesh: Any) -> tor
return differentiable_all_gather_concat(tensor, cp_mesh.get_group(), cp_mesh.size(), sequence_dim)


def _apply_mla_rope(
def apply_mla_rope(
tensor: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None,
*,
Expand Down Expand Up @@ -186,6 +186,10 @@ def _apply_mla_rope(
return rotated.transpose(0, 1)


# Retain the original callback name for existing CP plans.
_apply_mla_rope = apply_mla_rope


def _validate_query_partition(causal, attention_mask):
"""Reject query-partition modes whose FA metadata contract is not implemented."""
if not causal or attention_mask is not None:
Expand Down Expand Up @@ -348,12 +352,13 @@ def _query(
latent: torch.Tensor,
positions: tuple[torch.Tensor, torch.Tensor] | None,
heads: int,
rotary_fn=_apply_mla_rope,
) -> torch.Tensor:
"""Expand and rotate the query through the managed TP-local projection module."""
projected = module.q_b_proj(latent)
projected = projected.view(*latent.shape[:2], heads, module.qk_head_dim)
content, rotary = projected.split((module.qk_nope_head_dim, module.qk_rope_head_dim), dim=-1)
rotary = _apply_mla_rope(rotary, positions, interleaved=module.rotary_interleaved)
rotary = rotary_fn(rotary, positions, interleaved=module.rotary_interleaved)
return torch.cat((content, rotary), dim=-1).transpose(1, 2)


Expand Down Expand Up @@ -411,11 +416,28 @@ def _validate_state(module: nn.Module, plan: MLACPPlan, state: MLAState) -> None
class MLAContextParallel:
"""Run CP over normalized latents; parameter-gradient reduction belongs to the trainer."""

def __init__(self, plan: MLACPPlan, cp_mesh: Any) -> None:
"""Bind a validated execution plan to the framework-owned CP mesh."""
def __init__(self, plan: MLACPPlan, cp_mesh: Any, *,
rotary_fn: Callable[..., torch.Tensor] | None = None,
attention_interface: Callable[..., tuple[torch.Tensor, Any]] | None = None) -> None:
"""Bind a validated execution plan to the framework-owned CP mesh.

Args:
plan: Validated MLA CP communication and head plan.
cp_mesh: Framework-owned CP mesh, or None for degree one.
rotary_fn: Optional local rotary callback; None uses generic RoPE.
attention_interface: Optional attention callback; None uses generic NPU attention.
It also receives ``mla_head_offset`` and ``mla_local_heads``: the position of its
heads among the TP-local heads, which Ulysses splits across CP ranks.
"""
if (1 if cp_mesh is None else cp_mesh.size()) != plan.cp_degree:
raise ValueError("MLACPPlan degree must match the CP mesh")
if rotary_fn is not None and not callable(rotary_fn):
raise TypeError("rotary_fn must be callable")
if attention_interface is not None and not callable(attention_interface):
raise TypeError("attention_interface must be callable")
self.plan = plan
self.rotary_fn = _apply_mla_rope if rotary_fn is None else rotary_fn
self.attention_interface = npu_fusion_attention_forward if attention_interface is None else attention_interface
self.cp_mesh = cp_mesh
rank = 0 if cp_mesh is None else cp_mesh.get_local_rank()
self.query_rank, self.head_rank = divmod(rank, plan.ulysses_degree)
Expand Down Expand Up @@ -463,22 +485,15 @@ def __call__(
lengths, key_lengths = partition.query_lengths, partition.key_lengths
positions = _positions(position_embeddings, state, dimensions.rope_dim)
_validate_state(module, self.plan, state)
rotated_key = _apply_mla_rope(
rotated_key = self.rotary_fn(
state.key_rope.unsqueeze(2), positions, interleaved=module.rotary_interleaved,
).squeeze(2)
if self.plan.overlap and degree > 1:
prepare = self._expanded_overlap if self.plan.strategy == "expanded_ulysses" else self._latent_overlap
query, key, value = prepare(module, state, positions, rotated_key, partition)
else:
query = _query(module, state.query_latent, positions, self.plan.local_heads)
if self.plan.strategy == "expanded_ulysses" or degree == 1:
query, key, value = self._expanded(module, state, query, rotated_key, partition)
else:
query, key, value = self._latent(module, state, query, rotated_key, partition)
output = npu_fusion_attention_forward(
query, key, value = self._attention_inputs(module, state, positions, rotated_key, partition)
output = self.attention_interface(
module, query, key, value, attention_mask, scaling=module.scaling,
is_causal=causal, actual_seq_qlen=lengths, actual_seq_kvlen=key_lengths,
pre_tokens=2147483647, next_tokens=0 if causal else 2147483647,
mla_head_offset=self.head_rank * self.plan.compute_heads, mla_local_heads=self.plan.local_heads,
)[0]
if self.plan.ulysses_degree > 1:
output = ulysses_head_to_seq(output, 1, 2, self.ulysses_mesh)
Expand All @@ -487,6 +502,19 @@ def __call__(
raise RuntimeError(f"MLA CP output has shape {tuple(output.shape)}, expected {expected}")
return output, None

def _attention_inputs(self, module, state, positions, rotated_key, partition):
"""Select one existing QKV preparation schedule before invoking local attention."""
if self.plan.overlap and self.plan.cp_degree > 1:
prepare = self._expanded_overlap if self.plan.strategy == "expanded_ulysses" else self._latent_overlap
query, key, value = prepare(module, state, positions, rotated_key, partition)
else:
query = _query(module, state.query_latent, positions, self.plan.local_heads, self.rotary_fn)
if self.plan.strategy == "expanded_ulysses" or self.plan.cp_degree == 1:
query, key, value = self._expanded(module, state, query, rotated_key, partition)
else:
query, key, value = self._latent(module, state, query, rotated_key, partition)
return query, key, value

def _expanded(self, module, state, query, key_rope, partition=None):
"""Pack unequal-width QKV into one sequence-to-head exchange."""
key, value = _key_value(module, state.kv_latent, key_rope, self.plan.local_heads, None)
Expand Down Expand Up @@ -537,7 +565,7 @@ def _expanded_overlap(self, module, state, positions, key_rope, partition=None):
pending_kv = async_ulysses_seq_to_head_launch(payload, 1, 2, self.ulysses_mesh)
else:
pending_kv = self._expanded_kv_launch(payload, partition)
query = _query(module, state.query_latent, positions, self.plan.local_heads)
query = _query(module, state.query_latent, positions, self.plan.local_heads, self.rotary_fn)
pending_query = (async_ulysses_seq_to_head_launch(query.transpose(1, 2), 1, 2, self.ulysses_mesh)
if use_ulysses else None)
payload = pending_kv.wait()
Expand All @@ -564,7 +592,7 @@ def _latent_overlap(self, module, state, positions, key_rope, partition=None):
partition = None
else:
pending_kv = async_cp_allgather_launch(payload, 1, self.cp_mesh)
query = _query(module, state.query_latent, positions, self.plan.local_heads)
query = _query(module, state.query_latent, positions, self.plan.local_heads, self.rotary_fn)
payload = pending_kv.wait()
pending_query = (async_ulysses_seq_to_head_launch(query.transpose(1, 2), 1, 2, self.ulysses_mesh)
if self.plan.ulysses_degree > 1 else None)
Expand Down
9 changes: 8 additions & 1 deletion hyper_parallel/models/_transformers/model_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -936,9 +936,16 @@ def _validate_model_state_dtype(
if id(tensor) not in external_ids and (tensor.is_floating_point() or id(tensor) in fp32_ids)
and tensor.dtype != (torch.float32 if id(tensor) in fp32_ids else target_dtype)
]
fp32_buffer_ids = {
id(buffer)
for module in model.modules()
for name, buffer in module.named_buffers(recurse=False, remove_duplicate=False)
if name in getattr(module, "fp32_buffer_names", ())
}
mismatched.extend(
name for name, tensor in model.named_buffers(remove_duplicate=False)
if tensor.is_floating_point() and tensor.dtype != target_dtype
if (tensor.is_floating_point() or id(tensor) in fp32_buffer_ids)
and tensor.dtype != (torch.float32 if id(tensor) in fp32_buffer_ids else target_dtype)
)
if mismatched:
raise RuntimeError(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

from __future__ import annotations

from collections.abc import Sequence
from collections.abc import Callable, Sequence
from functools import wraps
from typing import Any, Literal

Expand Down Expand Up @@ -84,6 +84,46 @@ def _validate_up_projections(target_module: MLAAttention, plan: MLACPPlan) -> No
raise ValueError("MLA CP must be installed before other up-projection forward adapters")


def _make_cp_forward(target_module: MLAAttention, runtime: MLAContextParallel) -> Callable:
"""Build the original forward contract around one explicit CP runtime."""
original = target_module.forward

@wraps(original)
def cp_forward(
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
attention_mask: torch.Tensor | None = None,
past_key_values: Any | None = None,
actual_seq_len: torch.Tensor | Sequence[int] | None = None,
**kwargs: Any,
) -> tuple[torch.Tensor, torch.Tensor | None]:
"""Route latent inputs through CP with the model's forward contract.

Args:
hidden_states: Local sequence shard in batch, sequence, hidden order.
position_embeddings: Optional RoPE cosine and sine for local tokens.
attention_mask: Optional global boolean mask, with True for allowed keys.
past_key_values: Must be None for CP training.
actual_seq_len: Optional cumulative global packed document ends.
**kwargs: Causal, packed and supported model forward options.

Returns:
Projected local-token output and None for attention weights.
"""
if past_key_values is not None:
raise ValueError("MLA CP training does not support a KV cache")
batch_size, sequence_length = hidden_states.shape[:-1]
attn_output, attn_weights = runtime(
target_module, *target_module.project_latent_inputs(hidden_states),
position_embeddings=position_embeddings, attention_mask=attention_mask,
actual_seq_len=actual_seq_len, **kwargs,
)
attn_output = attn_output.reshape(batch_size, sequence_length, -1).contiguous()
return target_module.o_proj(attn_output), attn_weights

return cp_forward


@inner_wrapper
def mla_cp_wrapper(
target_module: nn.Module,
Expand All @@ -96,6 +136,8 @@ def mla_cp_wrapper(
overlap: bool = False,
ulysses_degree: int | None = None,
kv_exchange: Literal["all_gather", "all_to_all_v"] = "all_gather",
rotary_fn: Callable[..., torch.Tensor] | None = None,
attention_interface: Callable[..., tuple[torch.Tensor, Any]] | None = None,
) -> list[_ForwardRewriteRequest]:
"""Install NPU MLA CP after replacement and TP sharding, before FSDP.

Expand All @@ -115,6 +157,8 @@ def mla_cp_wrapper(
ulysses_degree: Defaults to CP size; at TP1, one selects KV AllGather,
and intermediate CP divisors select Ulysses x AllGather.
kv_exchange: Full KV collection or selective causal-prefix distribution.
rotary_fn: Optional local rotary callback; None retains the generic implementation.
attention_interface: Optional attention callback; None retains the generic NPU path.

Returns:
Atomic forward rewrites preserving projection parameters and hooks.
Expand Down Expand Up @@ -142,41 +186,9 @@ def mla_cp_wrapper(
)
plan.validate_scale(target_module.scaling)
_validate_up_projections(target_module, plan)
original = target_module.forward
runtime = MLAContextParallel(plan, cp_mesh)

@wraps(original)
def cp_forward(
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
attention_mask: torch.Tensor | None = None,
past_key_values: Any | None = None,
actual_seq_len: torch.Tensor | Sequence[int] | None = None,
**kwargs: Any,
) -> tuple[torch.Tensor, torch.Tensor | None]:
"""Route latent inputs through CP with the model's forward contract.
runtime = MLAContextParallel(plan, cp_mesh, rotary_fn=rotary_fn, attention_interface=attention_interface)

Args:
hidden_states: Local sequence shard in batch, sequence, hidden order.
position_embeddings: Optional RoPE cosine and sine for local tokens.
attention_mask: Optional global boolean mask, with True for allowed keys.
past_key_values: Must be None for CP training.
actual_seq_len: Optional cumulative global packed document ends.
**kwargs: Causal, packed and supported model forward options.

Returns:
Projected local-token output and None for attention weights.
"""
if past_key_values is not None:
raise ValueError("MLA CP training does not support a KV cache")
batch_size, sequence_length = hidden_states.shape[:-1]
attn_output, attn_weights = runtime(
target_module, *target_module.project_latent_inputs(hidden_states),
position_embeddings=position_embeddings, attention_mask=attention_mask,
actual_seq_len=actual_seq_len, **kwargs,
)
attn_output = attn_output.reshape(batch_size, sequence_length, -1).contiguous()
return target_module.o_proj(attn_output), attn_weights
cp_forward = _make_cp_forward(target_module, runtime)

requests = [_ForwardRewriteRequest(
target_module, cp_forward,
Expand Down
2 changes: 2 additions & 0 deletions hyper_parallel/models/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,8 @@ def _resolve_custom_model_cls(arch_name: str) -> Optional[type]:
# registered from ``models/kimi_k26/``.
"kimik25": "kimi_k26",
"qwen35moetext": "qwen3_5_moe",
# Official model_type xing4_0 is served by the Xing4 adapter directory.
"xing40": "xing_4",
}

# normalized family directory name → registration module path; built lazily.
Expand Down
15 changes: 15 additions & 0 deletions hyper_parallel/models/xing_4/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Copyright 2026 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Official Xing4 training model and HyperParallel adapters."""
15 changes: 15 additions & 0 deletions hyper_parallel/models/xing_4/adapter/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Copyright 2026 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""HyperParallel adapter providers of the Xing4 family."""
Loading
Loading