diff --git a/hyper_parallel/components/modules/mla_attention.py b/hyper_parallel/components/modules/mla_attention.py index 8732ffeccb..def08ff71d 100644 --- a/hyper_parallel/components/modules/mla_attention.py +++ b/hyper_parallel/components/modules/mla_attention.py @@ -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, @@ -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), diff --git a/hyper_parallel/core/multicore/modules/_precision.py b/hyper_parallel/core/multicore/modules/_precision.py index 62bf9c149e..a628bc81cb 100644 --- a/hyper_parallel/core/multicore/modules/_precision.py +++ b/hyper_parallel/core/multicore/modules/_precision.py @@ -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: @@ -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 diff --git a/hyper_parallel/core/optimizer/swap_optimizer_base.py b/hyper_parallel/core/optimizer/swap_optimizer_base.py index 19f6f7f8e9..d1049172ca 100644 --- a/hyper_parallel/core/optimizer/swap_optimizer_base.py +++ b/hyper_parallel/core/optimizer/swap_optimizer_base.py @@ -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 diff --git a/hyper_parallel/distributed/context_parallel/mla_context_parallel.py b/hyper_parallel/distributed/context_parallel/mla_context_parallel.py index c3b1bfd562..8858d3fce5 100644 --- a/hyper_parallel/distributed/context_parallel/mla_context_parallel.py +++ b/hyper_parallel/distributed/context_parallel/mla_context_parallel.py @@ -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 @@ -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, *, @@ -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: @@ -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) @@ -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) @@ -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) @@ -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) @@ -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() @@ -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) diff --git a/hyper_parallel/models/_transformers/model_builder.py b/hyper_parallel/models/_transformers/model_builder.py index 0d09901270..e86557fd53 100644 --- a/hyper_parallel/models/_transformers/model_builder.py +++ b/hyper_parallel/models/_transformers/model_builder.py @@ -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( diff --git a/hyper_parallel/models/deepseek_v3/adapter/distributed/context_parallel.py b/hyper_parallel/models/deepseek_v3/adapter/distributed/context_parallel.py index 5cd822016b..a4b3a35502 100644 --- a/hyper_parallel/models/deepseek_v3/adapter/distributed/context_parallel.py +++ b/hyper_parallel/models/deepseek_v3/adapter/distributed/context_parallel.py @@ -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 @@ -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, @@ -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. @@ -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. @@ -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, diff --git a/hyper_parallel/models/registry.py b/hyper_parallel/models/registry.py index 58fff82348..fdcacb1600 100644 --- a/hyper_parallel/models/registry.py +++ b/hyper_parallel/models/registry.py @@ -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. diff --git a/hyper_parallel/models/xing_4/__init__.py b/hyper_parallel/models/xing_4/__init__.py new file mode 100644 index 0000000000..c037792e09 --- /dev/null +++ b/hyper_parallel/models/xing_4/__init__.py @@ -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.""" diff --git a/hyper_parallel/models/xing_4/adapter/__init__.py b/hyper_parallel/models/xing_4/adapter/__init__.py new file mode 100644 index 0000000000..27747ab924 --- /dev/null +++ b/hyper_parallel/models/xing_4/adapter/__init__.py @@ -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.""" diff --git a/hyper_parallel/models/xing_4/adapter/builder.py b/hyper_parallel/models/xing_4/adapter/builder.py new file mode 100644 index 0000000000..5d5ac4e9da --- /dev/null +++ b/hyper_parallel/models/xing_4/adapter/builder.py @@ -0,0 +1,111 @@ +# 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. +# ============================================================================ +"""Build the Xing4 model from the recipe's configuration fields.""" + +from __future__ import annotations + +from typing import Any + +from transformers import PreTrainedModel + +from hyper_parallel.models import HyperAutoModelForCausalLM +from hyper_parallel.models.xing_4.transformer.configuration_xing4_0 import Xing4_0Config + +__all__ = ["build_model"] + +#: Training fields the model reads and the bundled inference configuration has no default for. +_REQUIRED_FIELDS = ("mhc_init_gating_factor", "mhc_layernorm_epsilon") +#: The same, for the routed layers; required only when the geometry builds an MoE. +_REQUIRED_MOE_FIELDS = ("moe_aux_loss_coeff", "moe_router_bias_update_rate", + "moe_router_enable_expert_bias", "use_pad_tokens") +#: Recipe spellings this adapter translates onto the bundled configuration's field names. +_FIELD_ALIASES = (("num_residual_streams", "hc_mult"), + ("mhc_sinkhorn_iterations", "hc_sinkhorn_iters"), + ("router_jitter_noise", "moe_input_jitter_eps")) + + +def build_model(*, config: dict[str, Any], **options: Any) -> PreTrainedModel: + """Build and parallelize the model through the shared builder. + + Args: + config: Model configuration with HF fields and HP training options. + **options: Construction options the Trainer passes to the shared builder. + + Returns: + The constructed, parallelized model. + """ + return HyperAutoModelForCausalLM.from_config(create_config(config), **options) + + +def create_config(config: dict[str, Any]) -> Xing4_0Config: + """Accept HF configuration fields and equivalent training aliases. + + ``PretrainedConfig`` keeps an unknown keyword as a plain attribute, so a recipe spelling this + function does not translate would be stored and never read. Translation, not validation, is + therefore the job here; a malformed value fails where it is used. + + Args: + config: Model fields supplied by the training recipe. + + Returns: + The bundled HF configuration carrying HP training options. + + Raises: + ValueError: If a field arrives under two names with different values, if the recipe + requests a routing mode this adapter does not implement, or if a training field the + model reads has no value. + """ + values = dict(config) + for recipe_name, hf_name in _FIELD_ALIASES: + if recipe_name not in values: + continue + value = values.pop(recipe_name) + if values.setdefault(hf_name, value) != value: + raise ValueError(f"Conflicting {recipe_name} and {hf_name}") + # The router reads this unconditionally; the bundled inference configuration has no field for it. + values.setdefault("moe_input_jitter_eps", 0.0) + # The bundled router is the learned top-k one; these select other routing modes entirely. + if values.get("moe_n_hash_layers", 0) or values.get("moe_router_force_expert_balance", False): + raise ValueError("Xing4 uses the official learned top-k router") + # get_is_hf_model selects the custom-model path from architectures[0]; without this the shared + # builder would construct a Transformers class instead of the registered training model. + values["architectures"] = ["Xing4ForCausalLM"] + # The recipe spells the residual-mixing bounds as one pair; the bundled configuration splits + # them. Its default is the reference configuration's [-30, 30], so the bundled forward clamps + # unless the recipe nulls both bounds. The fused mHC operators take no bound and refuse a + # configured clamp at the point they are installed. + clamp = values.pop("hc_sinkhorn_clamp", None) + if clamp is not None: + bounds = tuple(clamp) + if len(bounds) != 2 or not bounds[0] < bounds[1]: + raise ValueError(f"hc_sinkhorn_clamp must be an increasing [low, high] pair, got {clamp!r}") + for name, bound in zip(("mhc_h_res_clamp_min", "mhc_h_res_clamp_max"), bounds): + if values.setdefault(name, bound) != bound: + raise ValueError(f"Conflicting hc_sinkhorn_clamp and {name}") + result = Xing4_0Config(**values) + if not hasattr(result, "attention_softmax_scale"): + result.attention_softmax_scale = None + required = list(_REQUIRED_FIELDS) + if result.num_nextn_predict_layers: + required.append("mtp_loss_factor") + if result.n_routed_experts is not None and ( + result.num_hidden_layers + result.num_nextn_predict_layers > result.first_k_dense_replace): + required.extend(_REQUIRED_MOE_FIELDS) + missing = [name for name in required if getattr(result, name, None) is None] + if missing: + raise ValueError(f"Xing4 training configuration requires: {', '.join(missing)}") + if result.use_cache: + raise ValueError("The training recipe must explicitly disable the KV cache") + return result diff --git a/hyper_parallel/models/xing_4/adapter/conversion/__init__.py b/hyper_parallel/models/xing_4/adapter/conversion/__init__.py new file mode 100644 index 0000000000..1c14ad4119 --- /dev/null +++ b/hyper_parallel/models/xing_4/adapter/conversion/__init__.py @@ -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. +# ============================================================================ +"""Xing4 module conversion providers.""" diff --git a/hyper_parallel/models/xing_4/adapter/conversion/module_replacement.py b/hyper_parallel/models/xing_4/adapter/conversion/module_replacement.py new file mode 100644 index 0000000000..a9540d02d7 --- /dev/null +++ b/hyper_parallel/models/xing_4/adapter/conversion/module_replacement.py @@ -0,0 +1,350 @@ +# 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. +# ============================================================================ +"""NPU replacements for Xing4 attention, experts and hyper-connections.""" + +# pylint: disable=forbidden-backend-import + +from __future__ import annotations + +from collections.abc import Mapping +from functools import partial +from typing import Any + +import torch +from torch import nn +from transformers.activations import ACT2FN + +from hyper_parallel.components.checkpoint import weight_conversion +from hyper_parallel.components.checkpoint.conversion_ops import ConcatenateWithSections +from hyper_parallel.components.checkpoint.weight_conversion import Transpose, WeightConverter +from hyper_parallel.components.functional.mhc_pre import mhc_pre +from hyper_parallel.components.functional.npu_fusion_attention import ( + _prepare_fusion_attention_context, PACKED_SEQUENCE_ARGUMENTS, +) +from hyper_parallel.components.functional.rotary_embedding import ( + apply_rotary_pos_emb_interleave as fused_rotary, +) +from hyper_parallel.components.modules.rms_norm import RMSNorm +from hyper_parallel.components.modules.grouped_experts import GroupedExperts +from hyper_parallel.components.modules.mla_attention import MLAAttention +from hyper_parallel.models.replacement import module_replacement as register_module_replacement +from hyper_parallel.models.xing_4.adapter.moe import Xing4MLP +from hyper_parallel.models.xing_4.transformer.modeling_xing4_0 import ( + Xing4_0HyperConnection, Xing4_0MLP, apply_rotary_pos_emb_interleave, +) + +__all__ = ["Xing4MLAAttention", "Xing4GroupedExperts", "Xing4FusedHyperConnection"] + + +def fusion_attention_with_logit_maxima(module: nn.Module, query: torch.Tensor, key: torch.Tensor, + value: torch.Tensor, attention_mask: torch.Tensor | None, + **kwargs: Any) -> tuple[torch.Tensor, None]: + """Run causal TND attention and accumulate maxima for QK clipping. + + Query/key are BNSD, value is BNSV, and output is BSNV. CP supplies + packed sequence boundaries and the head range within the TP shard.""" + del attention_mask + if kwargs.get("indices") is not None or kwargs.get("dropout", 0.0): + raise ValueError("Xing4 MLA requires dense attention with dropout=0") + batch, heads, sequence = query.shape[:3] + options = dict(kwargs) + head_offset = options.pop("mla_head_offset", 0) + local_heads = options.pop("mla_local_heads", heads) + if not options.get("is_causal", getattr(module, "is_causal", True)): + raise ValueError("Xing4 training requires causal attention") + if not any(options.get(name) is not None for name in PACKED_SEQUENCE_ARGUMENTS): + if sequence != key.shape[2]: + raise ValueError("Unequal Xing4 CP query/key lengths require global sequence boundaries") + options["actual_seq_len"] = tuple(range(sequence, batch * sequence + 1, sequence)) + context = _prepare_fusion_attention_context(module, query, key, value, None, options) + # Configuration and conversion do not require the optional NPU extension. + import torch_npu # pylint: disable=import-outside-toplevel + + output, softmax_max = torch_npu.npu_fusion_attention( + context.query, context.key, context.value, heads, context.input_layout, + pse=None, padding_mask=None, atten_mask=context.attention_mask, scale=kwargs["scaling"], + pre_tockens=context.pre_tokens, next_tockens=context.next_tokens, keep_prob=1.0, + inner_precise=0, sparse_mode=context.sparse_mode, actual_seq_qlen=context.query_lengths, + actual_seq_kvlen=context.key_lengths, softmax_layout="TND")[:2] + with torch.no_grad(): + # TND softmax statistics have token, head and redundant-lane axes. + if softmax_max.ndim != 3 or softmax_max.shape[1] != heads: + raise ValueError(f"Expected (T, {heads}, 8) softmax_max for TND fusion attention, " + f"got shape {tuple(softmax_max.shape)}.") + maximum = softmax_max.amax(dim=(0, 2)) + if heads != local_heads: + # Ulysses owns a subset of TP-local heads; QK clipping's MAX reduction joins them. + placed = maximum.new_full((local_heads,), float("-inf")) + placed[head_offset:head_offset + heads] = maximum + maximum = placed + module.max_logits = maximum if module.max_logits is None else torch.maximum(module.max_logits, maximum) + return output.view(batch, sequence, heads, -1), None + + +@register_module_replacement +class Xing4MLAAttention(MLAAttention): + """Fuse MLA projections with FP32 rotary channels and per-head maxima.""" + + def __init__(self, *, module: nn.Module, module_fqn: str = "", + context: Mapping[str, Any] | None = None) -> None: + """Retain source weights and select the configured rotary implementation.""" + super().__init__(module=module, module_fqn=module_fqn, context=context, + attention_interface=fusion_attention_with_logit_maxima) + self.q_a_layernorm = RMSNorm(module=self.q_a_layernorm) + self.kv_a_layernorm = RMSNorm(module=self.kv_a_layernorm) + if not self.linear_qkv.weight.is_meta: + with torch.no_grad(): + split = self._q_latent_output_size + self.linear_qkv.weight[:split].copy_(module.q_a_proj.weight) + self.linear_qkv.weight[split:].copy_(module.kv_a_proj_with_mqa.weight) + self.apply_rotary_pos_emb_interleave = ( + fused_rotary if getattr(self.config, "apply_rope_fusion", False) else apply_rotary_pos_emb_interleave + ) + # Per-head logit maxima since the last QK clipping, folded in by the attention interface. + self.max_logits: torch.Tensor | None = None + + def _project_attention_inputs(self, hidden_states: torch.Tensor, + position_embeddings: tuple[torch.Tensor, torch.Tensor] | None, + past_key_values: Any | None) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Reuse latent and KV projections, rounding RoPE at each concatenation.""" + if position_embeddings is None or past_key_values is not None: + raise ValueError("Xing4 MLA requires RoPE tables and no KV cache") + latents = self._project_latents(hidden_states) + query_rope, key_rope = self.apply_rotary_pos_emb_interleave( + latents.query_rope.float(), latents.key_rope.float(), *position_embeddings, + ) + key_nope, value = self._expand_key_value(latents.kv_nope) + query_pass = latents.query_pass.transpose(1, 2) + query = torch.cat((query_pass, query_rope.to(query_pass.dtype)), dim=-1) + key = torch.cat((key_nope, key_rope.to(key_nope.dtype).expand(-1, self.num_heads, -1, -1)), dim=-1) + return query, key, value + + +def _expert_weights(module: nn.Module) -> tuple[Any, list[tuple[nn.Parameter, nn.Parameter, nn.Parameter]]]: + """Read per-expert projections and reject incompatible source modules.""" + if not isinstance(module, nn.ModuleList) or len(module) == 0: + raise ValueError("Xing4 grouped experts require a nonempty ModuleList") + config = getattr(module, "config", None) + if config is None: + config = getattr(module[0], "config", None) + if config is None or getattr(config, "hidden_act", None) != "silu": + raise ValueError("Xing4 grouped experts require the source SiLU configuration") + if any(True for _ in module.named_buffers(remove_duplicate=False)): + raise ValueError("Xing4 grouped experts cannot discard source buffers") + for child in module.modules(): + if "forward" in vars(child): + raise ValueError("Xing4 grouped experts cannot migrate instance forward overrides") + if any("hook" in name and isinstance(value, Mapping) and value for name, value in vars(child).items()): + raise ValueError("Xing4 grouped experts cannot migrate source module hooks") + # Packing preserves only these exact expert, projection and activation implementations. + expert_type = type(module[0]) + if expert_type not in (Xing4_0MLP, Xing4MLP) or any( + type(expert) is not expert_type for expert in module): # pylint: disable=unidiomatic-typecheck + raise ValueError("Xing4 grouped experts require a uniform supported expert class") + policy = ( + getattr(module[0], "limit", None), + getattr(module[0], "activation_compute_dtype", None), + bool(getattr(config, "use_fused_swiglu", True)), + ) + for expert in module: + expert_config = getattr(expert, "config", None) + expert_policy = ( + getattr(expert, "limit", None), + getattr(expert, "activation_compute_dtype", None), + bool(getattr(expert_config, "use_fused_swiglu", True)), + ) + if getattr(expert_config, "hidden_act", None) != "silu" or expert_policy != policy: + raise ValueError("Xing4 grouped experts require uniform activation policy") + if expert_type is Xing4MLP: + # Xing4MLP loads this optional API only when the extended policy is used. + from hyper_parallel.components.functional.activation_swiglu import ( # pylint: disable=import-outside-toplevel + swiglu_from_projections, + ) + if any(expert._swiglu is not swiglu_from_projections for expert in module): # pylint: disable=protected-access + raise ValueError("Xing4 grouped experts require the standard SwiGLU implementation") + weights = [] + expected_names = set() + expected_activation = type(ACT2FN["silu"]) + for index, expert in enumerate(module): + if type(getattr(expert, "act_fn", None)) is not expected_activation: # pylint: disable=unidiomatic-typecheck + raise ValueError("Xing4 grouped experts require the standard SiLU activation") + projections = [] + for name in ("gate_proj", "up_proj", "down_proj"): + projection = getattr(expert, name, None) + # pylint: disable-next=unidiomatic-typecheck + if type(projection) is not nn.Linear or projection.bias is not None: + raise ValueError(f"Xing4 expert {index} requires bias-free Linear {name}") + projections.append(projection.weight) + expected_names.add(f"{index}.{name}.weight") + weights.append(tuple(projections)) + named = dict(module.named_parameters(remove_duplicate=False)) + if set(named) != expected_names or len({id(value) for value in named.values()}) != len(named): + raise ValueError("Xing4 expert parameters contain unsupported extras or aliases") + storages = [value.untyped_storage() for value in named.values()] + if len({id(storage) for storage in storages}) != len(storages): + raise ValueError("Xing4 expert parameters with shared storage cannot be packed independently") + return config, weights + + +def _validate_expert_weights( + config: Any, weights: list[tuple[nn.Parameter, nn.Parameter, nn.Parameter]], +) -> tuple[int, int]: + """Require uniform projection shapes, dtype, device and gradient ownership.""" + first_gate, _, first_down = weights[0] + if first_gate.ndim != 2: + raise ValueError("Xing4 expert gate weight must be a matrix") + intermediate_size, hidden_size = first_gate.shape + if hidden_size <= 0 or intermediate_size <= 0: + raise ValueError("Xing4 expert dimensions must be positive") + count = len(weights) + for name, expected in (("hidden_size", hidden_size), ("moe_intermediate_size", intermediate_size), + ("n_routed_experts", count), ("num_local_experts", count)): + actual = getattr(config, name, None) + if actual is not None and actual != expected: + raise ValueError(f"Xing4 expert config {name}={actual} does not match {expected}") + for gate, up, down in weights: + if (tuple(gate.shape) != (intermediate_size, hidden_size) + or tuple(up.shape) != (intermediate_size, hidden_size) + or tuple(down.shape) != (hidden_size, intermediate_size)): + raise ValueError("Xing4 experts must have identical gate, up and down dimensions") + if any(value.device != first_gate.device or value.dtype != first_gate.dtype for value in (gate, up, down)): + raise ValueError("Xing4 expert weights must share one dtype and device") + if gate.requires_grad != first_gate.requires_grad or up.requires_grad != first_gate.requires_grad: + raise ValueError("packing gate/up weights requires identical requires_grad flags") + if down.requires_grad != first_down.requires_grad: + raise ValueError("packing down weights requires identical requires_grad flags") + return hidden_size, intermediate_size + + +@register_module_replacement +class Xing4GroupedExperts(GroupedExperts): + """Pack the official ModuleList into shared grouped-GEMM parameters. + + Eager weights are copied once. Meta weights use the reversible checkpoint + mappings. Replacement precedes optimizer construction.""" + + def __init__( + self, + *, + module: nn.Module, + module_fqn: str = "", + context: Mapping[str, Any] | None = None, + ) -> None: + """Validate, pack and install expert weights in the shared grouped module.""" + config, weights = _expert_weights(module) + hidden_size, intermediate_size = _validate_expert_weights(config, weights) + count = len(weights) + gate, _, down = weights[0] + packed_gate = nn.Parameter( + gate.new_empty((count, hidden_size, 2 * intermediate_size)), requires_grad=gate.requires_grad + ) + packed_down = nn.Parameter( + down.new_empty((count, intermediate_size, hidden_size)), requires_grad=down.requires_grad + ) + if not gate.is_meta: + with torch.no_grad(): + for index, (gate_weight, up_weight, down_weight) in enumerate(weights): + packed_gate[index, :, :intermediate_size].copy_(gate_weight.transpose(0, 1)) + packed_gate[index, :, intermediate_size:].copy_(up_weight.transpose(0, 1)) + packed_down[index].copy_(down_weight.transpose(0, 1)) + carrier = nn.Module() + carrier.config = config + carrier.num_local_experts = count + carrier.hidden_size = hidden_size + carrier.intermediate_size = intermediate_size + carrier.has_gate = True + carrier.is_concatenated = True + carrier.is_transposed = True + carrier.limit = getattr(module[0], "limit", None) + carrier.activation_compute_dtype = getattr(module[0], "activation_compute_dtype", None) + carrier.gate_up_proj = packed_gate + carrier.down_proj = packed_down + carrier.train(module.training) + super().__init__(module=carrier, module_fqn=module_fqn, context=context) + + if carrier.limit is not None or carrier.activation_compute_dtype is not None: + expected = { + "clamp_limit": carrier.limit, + "compute_dtype": carrier.activation_compute_dtype, + "use_fused": bool(getattr(config, "use_fused_swiglu", True)), + } + activation = self.activation_func + if not isinstance(activation, partial) or any( + activation.keywords.get(name) != value for name, value in expected.items()): + raise ValueError("GroupedExperts must support the requested SwiGLU clamp and compute dtype") + + def forward(self, *args: torch.Tensor, **kwargs: torch.Tensor) -> torch.Tensor: + """Preserve the ModuleList replacement call contract for the shared builder.""" + return super().forward(*args, **kwargs) + + def make_transforms(self) -> list[WeightConverter]: + """Return reversible mappings for every original expert projection.""" + # Prefer HP's dimension-preserving reverse operation when available. + merge_experts = getattr(weight_conversion, "MergeModulelist", None) + if merge_experts is None: + from transformers.core_model_loading import MergeModulelist # pylint: disable=import-outside-toplevel + + if 1 in (self.hidden_size, self.intermediate_size): + raise ValueError("Singleton expert dimensions require the dimension-preserving MergeModulelist") + merge_experts = MergeModulelist + pack = ConcatenateWithSections((self.intermediate_size, self.intermediate_size), dim=1) + return [ + WeightConverter( + source_patterns=[r"*.gate_proj.weight", r"*.up_proj.weight"], + target_patterns="gate_up_proj", + operations=[merge_experts(dim=0), pack, Transpose(-2, -1)], + ), + WeightConverter( + source_patterns=r"*.down_proj.weight", + target_patterns="down_proj", + operations=[merge_experts(dim=0), Transpose(-2, -1)], + ), + ] + + +@register_module_replacement +class Xing4FusedHyperConnection(Xing4_0HyperConnection): + """Adapt official mHC parameters to the shared NPU pre operation.""" + + def __init__(self, *, module: Xing4_0HyperConnection, module_fqn: str = "", + context: Mapping[str, Any] | None = None) -> None: + """Keep official parameter names, values and ownership. + + Raises: + ValueError: If the configuration clamps the residual-mixing logits. ``mhc_pre`` takes + no bound, so selecting it on a clamped configuration would drop the clamp without + reporting it; nulling both bounds selects the unclamped operator explicitly. + """ + nn.Module.__init__(self) + del context + if module.mhc_h_res_clamp_min is not None or module.mhc_h_res_clamp_max is not None: + raise ValueError( + f"the fused mHC operator has no clamp, but {module_fqn or 'this hyper-connection'} " + f"is configured with [{module.mhc_h_res_clamp_min}, {module.mhc_h_res_clamp_max}]; " + "set mhc_h_res_clamp_min and mhc_h_res_clamp_max to null to select it" + ) + self.hc_mult, self.hc_sinkhorn_iters, self.hc_eps = module.hc_mult, module.hc_sinkhorn_iters, module.hc_eps + self.input_norm = module.input_norm + self.hc_fn, self.hc_base, self.hc_scale = module.hc_fn, module.hc_base, module.hc_scale + self.train(module.training) + + def forward(self, hidden_streams: torch.Tensor) -> tuple[torch.Tensor, ...]: + """Run the fused pre operator and preserve its residual-gradient output.""" + hidden, post, mix, residual = mhc_pre( + hidden_streams.flatten(2), self.hc_fn, self.hc_scale, self.hc_base, self.hc_mult, + sinkhorn_iters=self.hc_sinkhorn_iters, norm_eps=self.input_norm.eps, hc_eps=self.hc_eps) + # Keep the pre operator's residual output in the graph: its backward + # consumes the post gradient through grad_x_post. + return post, mix, hidden, residual.unflatten(-1, (self.hc_mult, hidden.shape[-1])) diff --git a/hyper_parallel/models/xing_4/adapter/distributed/__init__.py b/hyper_parallel/models/xing_4/adapter/distributed/__init__.py new file mode 100644 index 0000000000..796ae5a3f5 --- /dev/null +++ b/hyper_parallel/models/xing_4/adapter/distributed/__init__.py @@ -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. +# ============================================================================ +"""Xing4 EP/CP rule providers.""" diff --git a/hyper_parallel/models/xing_4/adapter/distributed/context_parallel.py b/hyper_parallel/models/xing_4/adapter/distributed/context_parallel.py new file mode 100644 index 0000000000..7bdbbdb7eb --- /dev/null +++ b/hyper_parallel/models/xing_4/adapter/distributed/context_parallel.py @@ -0,0 +1,158 @@ +# 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. +# ============================================================================ +"""Xing4 contracts for the shared MLA CP runtime and contiguous training shards.""" + +from __future__ import annotations + +# pylint: disable=forbidden-backend-import + +from collections.abc import Callable, Mapping +from functools import wraps +from typing import Any, Literal + +import torch +import torch.distributed as dist +from torch import nn + +from hyper_parallel.core.utils.communication import differentiable_all_reduce, gather_counts_via_all_gather +from hyper_parallel.distributed._builder.forward_rewriter import _ForwardRewriteRequest +from hyper_parallel.distributed.context_parallel.mla_context_parallel import MLACPStrategy, apply_mla_rope +from hyper_parallel.distributed.recipe_spec import inner_wrapper +from hyper_parallel.models.deepseek_v3.adapter.distributed.context_parallel import mla_cp_wrapper +from hyper_parallel.models.replacement import method_replacement +from hyper_parallel.models.xing_4.adapter.conversion.module_replacement import ( + Xing4MLAAttention, fusion_attention_with_logit_maxima, +) +from hyper_parallel.models.xing_4.adapter.moe import Xing4MoE + + +def _rotary(tensor: torch.Tensor, positions: tuple[torch.Tensor, torch.Tensor] | None, + *, interleaved: bool = False) -> torch.Tensor: + """Preserve official FP32 interleaved RoPE for the runtime's BSND tensors.""" + if positions is None or not interleaved: + raise ValueError("Xing4 CP requires interleaved RoPE and local position embeddings") + return apply_mla_rope(tensor.float(), positions, interleaved=True).to(tensor.dtype) + + +@inner_wrapper +def xing4_mla_cp_wrapper(target_module: nn.Module, mesh: Any, tp_mesh: Any, + cp_mesh: Any, ep_mesh: Any, *, strategy: MLACPStrategy = "expanded_ulysses", + overlap: bool = False, ulysses_degree: int | None = None, + kv_exchange: Literal["all_gather", "all_to_all_v"] = "all_gather") -> list: + """Select the shared MLA CP plan through a ``when: cp`` forward rule. + + Ulysses is the default and composes with TP when the local head count is + divisible by CP. At TP1, ``ulysses_degree=1`` selects the shared KV AllGather + plan. The enclosing training model accepts only implicit causal sequences; + its HF-generated local mask must not replace the CP runtime's global mask. + + Args: + target_module: Optimized Xing4 MLA attention. + mesh: Full framework mesh. + tp_mesh: Tensor parallel mesh, or None. + cp_mesh: Active context parallel mesh. + ep_mesh: Expert parallel mesh, or None. + strategy: Expanded QKV or expanded Q with latent KV exchange. + overlap: Overlap input communication with independent projections. + ulysses_degree: Head redistribution degree; None uses the CP size. + kv_exchange: Full KV collection or selective causal-prefix distribution. + + Returns: + Atomic forward rewrites from the shared MLA runtime. + """ + if not isinstance(target_module, Xing4MLAAttention) or cp_mesh is None: + raise ValueError("Xing4 CP requires an active CP mesh and the MLA module replacement") + requests = mla_cp_wrapper( + target_module, mesh, tp_mesh, cp_mesh, ep_mesh, strategy=strategy, overlap=overlap, + ulysses_degree=ulysses_degree, kv_exchange=kv_exchange, + rotary_fn=_rotary, attention_interface=fusion_attention_with_logit_maxima, + ) + original = requests[0].forward + + @wraps(original) + def forward(hidden_states: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None, + attention_mask: torch.Tensor | None = None, **kwargs: Any) -> tuple[torch.Tensor, None]: + """Use the CP runtime's global causal mask instead of the HF local-shard mask.""" + del attention_mask + return original(hidden_states, position_embeddings=position_embeddings, attention_mask=None, **kwargs) + + requests[0] = _ForwardRewriteRequest(target_module, forward, requests[0].companion_attrs) + return requests + + +@inner_wrapper +def xing4_moe_cp_wrapper(target_module: Xing4MoE, mesh: Any, tp_mesh: Any, + cp_mesh: Any, ep_mesh: Any) -> list: + """Bind sequence-wise router statistics without replacing the MoE computation.""" + del mesh, tp_mesh, ep_mesh + if not isinstance(target_module, Xing4MoE) or cp_mesh is None: + raise ValueError("Xing4 router statistics require an MoE module and an active CP mesh") + if target_module.gate.aux_loss_cp_group is not None: + raise ValueError("Xing4 MoE CP group is already configured") + target_module.gate.aux_loss_cp_group = cp_mesh.get_group() + return [] + + +def _cp_mesh(context: Mapping[str, Any]) -> Any: + """Resolve the same mesh used by TextParallelBatch's contiguous CP sharder.""" + mesh = getattr(context.get("mesh_context"), "cp_mesh", None) + if mesh is None or mesh.size() <= 1 or mesh.get_group() is None: + raise ValueError("Xing4 sequence methods require an active CP mesh") + return mesh + + +@method_replacement +def xing4_cp_shift_tokens(*, module: nn.Module, method_fqn: str, + original_method: Callable, context: Mapping[str, Any]) -> Callable: + """Replace ``model.shift_tokens`` with the next-shard token exchange. + + Only IDs and labels are exchanged. Repeating this one-token shift for each + MTP depth handles depths exceeding a shard's length without wrapping the + global sequence tail. Communication uses the shared explicit-wait helper. + """ + del module, method_fqn + mesh = _cp_mesh(context) + group, rank, size = mesh.get_group(), mesh.get_local_rank(), mesh.size() + + @wraps(original_method) + def shift_tokens(tokens: torch.Tensor, pad_value: int) -> torch.Tensor: + """Shift within the global sequence, padding only its final shard.""" + first = gather_counts_via_all_gather(tokens[:, 0].contiguous(), group, size) + tail = first[rank + 1] if rank + 1 < size else torch.full_like(first[0], pad_value) + return torch.cat((tokens[:, 1:], tail.unsqueeze(1)), dim=1) + + return shift_tokens + + +@method_replacement +def xing4_cp_mean_loss(*, module: nn.Module, method_fqn: str, + original_method: Callable, context: Mapping[str, Any]) -> Callable: + """Replace ``model.mean_loss`` with a global sequence objective. + + Each MTP depth has its own valid-token denominator. Trainer retains its + ordinary foundation-token weighting across microbatches and DP replicas; + its DP/CP normalization and FSDP gradient averaging must not be repeated here. + """ + del module, method_fqn + group = _cp_mesh(context).get_group() + + @wraps(original_method) + def mean_loss(loss_sum: torch.Tensor, count: torch.Tensor) -> torch.Tensor: + """Average this prediction depth across its CP shards.""" + global_count = count.clone() + dist.all_reduce(global_count, group=group) + return differentiable_all_reduce(loss_sum, "sum", group) / global_count.clamp_min(1) + + return mean_loss diff --git a/hyper_parallel/models/xing_4/adapter/distributed/expert_parallel.py b/hyper_parallel/models/xing_4/adapter/distributed/expert_parallel.py new file mode 100644 index 0000000000..0fc1f39a14 --- /dev/null +++ b/hyper_parallel/models/xing_4/adapter/distributed/expert_parallel.py @@ -0,0 +1,47 @@ +# 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. +# ============================================================================ +"""Expert-parallel execution of the Xing4 MoE layers. + +Recipes bind :func:`xing4_ep_compute_fn` to the MoE modules with a +``when: ep`` ``plan_overrides`` entry. +""" + +from collections.abc import Callable +from typing import Any + +from hyper_parallel.components.modules.grouped_experts import GroupedExperts +from hyper_parallel.distributed.expert_parallel.experts import SHARED_MERGE_MODES +from hyper_parallel.distributed.expert_parallel.recipes import build_ep_compute +from hyper_parallel.distributed.recipe_spec import local_compute + +__all__ = ["xing4_ep_compute_fn"] + + +@local_compute +def xing4_ep_compute_fn(*, module: Any, mesh: Any, tp_mesh: Any, cp_mesh: Any, + ep_mesh: Any, fix_router: bool = False) -> Callable: + """Dispatch routed experts while retaining local shared experts and router state. + + ``fix_router`` balances dispatch indices for benchmarks; safe-token padding + and statistics from the learned router keep their separate semantics. + """ + del mesh, tp_mesh, cp_mesh + if not isinstance(module.experts, GroupedExperts): + raise ValueError("Xing4 EP requires the grouped experts replacement before binding the executor") + module.ep_executor = build_ep_compute( + module, ep_mesh, router_fn=type(module).route, archetype_key="xing4", + expected_attrs=["gate", "experts", "shared_experts"], combine=SHARED_MERGE_MODES["none"], + use_grouped_gemm=True, fix_router=fix_router) + return type(module).forward diff --git a/hyper_parallel/models/xing_4/adapter/moe.py b/hyper_parallel/models/xing_4/adapter/moe.py new file mode 100644 index 0000000000..63b107a18b --- /dev/null +++ b/hyper_parallel/models/xing_4/adapter/moe.py @@ -0,0 +1,204 @@ +# 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. +# ============================================================================ +"""Training objectives around the official Xing4 router, experts and MLPs.""" +from collections.abc import Callable +from typing import Any + +import torch +import torch.distributed as dist +from torch import nn + +from hyper_parallel.components.functional.aux_loss import aux_loss_auto_scale +from hyper_parallel.core.activation_memory.recompute_state import is_recomputing +from hyper_parallel.core.multicore.modules._precision import preserve_fp32_tensors +from hyper_parallel.core.utils.communication import differentiable_all_reduce +from hyper_parallel.models.xing_4.transformer.modeling_xing4_0 import ( + Xing4_0MLP, Xing4_0MoE, Xing4_0TopkRouter, +) + + +class Xing4Router(Xing4_0TopkRouter): + """HF learned selection with the recipe's training state and objectives.""" + + fp32_buffer_names = ("e_score_correction_bias",) + + def __init__(self, config: Any, source: nn.Module) -> None: + """Retain the HF weights and register all resumable routing state.""" + super().__init__(config) + self.weight = source.weight + self.e_score_correction_bias = source.e_score_correction_bias + self.padding = config.n_routed_experts if config.use_pad_tokens else 0 + self.aux_loss_coeff = config.moe_aux_loss_coeff + self.aux_loss_cp_group = None + # Reset every optimizer step, so the checkpoint never needs to carry them. + self.register_buffer("_token_counts", torch.zeros(self.num_experts, dtype=torch.int64), + persistent=False) + self.input_jitter_eps = config.moe_input_jitter_eps + self.last_aux_loss = None + self.enable_expert_bias = config.moe_router_enable_expert_bias + self.expert_bias_update_rate = config.moe_router_bias_update_rate + + def _apply(self, fn: Callable, recurse: bool = True) -> "Xing4Router": + """Keep load-balancing bias updates in FP32 during model dtype conversion.""" + return super()._apply(preserve_fp32_tensors(self, fn, self.fp32_buffer_names), recurse=recurse) + + def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Route real tokens once; safe-token padding consumes neither jitter nor counts.""" + real_hidden = hidden_states[:, self.padding:] + flat = real_hidden.reshape(-1, hidden_states.shape[-1]).float() + if self.training and self.input_jitter_eps: + flat = flat * (1.0 + (2.0 * torch.rand_like(flat) - 1.0) * self.input_jitter_eps) + logits, weights, indices = super().forward(flat) + scores = logits.sigmoid() + if self.training and self.aux_loss_coeff: + weights = self._attach_balance_loss(weights, scores, batch_size=hidden_states.shape[0]) + else: + self.last_aux_loss = None + if self.training and self.enable_expert_bias and not is_recomputing(): + counts = torch.zeros_like(self._token_counts).scatter_add_( + 0, indices.reshape(-1), torch.ones_like(indices.reshape(-1), dtype=torch.int64)) + self._token_counts.add_(counts) + if self.padding: + batch = hidden_states.shape[0] + padding = torch.arange(self.padding * self.top_k, device=indices.device) + padding = (padding.view(1, self.padding, self.top_k) % self.num_experts).expand(batch, -1, -1) + indices = torch.cat((padding, indices.reshape(batch, -1, self.top_k)), dim=1).reshape(-1, self.top_k) + weights = torch.cat((weights.new_zeros(batch, self.padding, self.top_k), + weights.reshape(batch, -1, self.top_k)), dim=1).reshape(-1, self.top_k) + return logits, weights.to(hidden_states.dtype), indices + + def _attach_balance_loss(self, weights: torch.Tensor, scores: torch.Tensor, batch_size: int) -> torch.Tensor: + """Inject ``coeff * E * mean_b(sum_i(f_bi * P_bi))`` through the routing weights. + + ``f_bi`` counts unbiased top-k affinities per sequence, independently of the expert-load bias. ``P_bi`` averages + the normalized affinities within each sequence. The sequence objectives are averaged over + the batch. + + Args: + weights: Routing weights of the real tokens. + scores: Router affinities of every expert. + batch_size: Number of independent sequences before flattening the tokens. + """ + selected_indices = scores.topk(self.top_k, dim=-1, sorted=False).indices + selected = selected_indices.reshape(batch_size, -1) + counts = scores.new_zeros(batch_size, self.num_experts).scatter_add_( + 1, selected, torch.ones_like(selected, dtype=scores.dtype)) + if getattr(self, 'aux_loss_cp_group', None) is None: + load = counts / selected.shape[1] + affinity = (scores / (scores.sum(dim=-1, keepdim=True) + 1e-20)).reshape( + batch_size, -1, self.num_experts).mean(dim=1) + else: + normalized = (scores / (scores.sum(dim=-1, keepdim=True) + 1e-20)).reshape( + batch_size, -1, self.num_experts) + group = self.aux_loss_cp_group + with torch.no_grad(): + counts = counts.detach() + dist.all_reduce(counts, group=group) + tokens = counts.new_tensor(normalized.shape[1]) + dist.all_reduce(tokens, group=group) + load = counts / (tokens * self.top_k) + affinity = differentiable_all_reduce(normalized.sum(dim=1), "sum", group) / tokens + loss = (affinity * load).sum(dim=-1).mean() * self.num_experts + self.last_aux_loss = loss.detach() + return aux_loss_auto_scale(weights, loss * self.aux_loss_coeff) + + + @property + def tokens_per_expert(self) -> torch.Tensor: + """Expose the persistent counts to the shared MoE monitor.""" + return self._token_counts + + @torch.no_grad() + def update_expert_bias(self, lr: float, num_recomputations: int = 1) -> None: + """Apply one load-based update after the optimizer step.""" + del num_recomputations + counts = self._token_counts + self.e_score_correction_bias.add_((counts.sum() - counts * self.num_experts).sign(), alpha=lr) + counts.zero_() + + +class Xing4MLP(Xing4_0MLP): + """Retain HF projections with an optional training activation policy.""" + + def __init__(self, source: nn.Module) -> None: + """Adopt the HF parameters without creating a second weight owner.""" + nn.Module.__init__(self) # pylint: disable=non-parent-init-called + self.config = source.config + self.hidden_size = source.hidden_size + self.intermediate_size = source.intermediate_size + self.gate_proj, self.up_proj, self.down_proj = source.gate_proj, source.up_proj, source.down_proj + # Only the optional clipped/compute-dtype policy needs the extended SwiGLU API. + from hyper_parallel.components.functional.activation_swiglu import ( # pylint: disable=import-outside-toplevel + swiglu_from_projections, + ) + self.act_fn = source.act_fn + self._swiglu = swiglu_from_projections + self.limit = getattr(self.config, "swiglu_limit", None) + dtype_name = getattr(self.config, "swiglu_compute_dtype", None) + self.activation_compute_dtype = getattr(torch, dtype_name) if dtype_name is not None else None + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Apply the configured shared SwiGLU policy to the HF projections.""" + activation = self._swiglu( + self.gate_proj(x), self.up_proj(x), clamp_limit=self.limit, + compute_dtype=self.activation_compute_dtype, + use_fused=bool(getattr(self.config, "use_fused_swiglu", True))) + return self.down_proj(activation) + + +def adapt_mlp(mlp: nn.Module) -> nn.Module: + """Apply the training activation policy when requested.""" + config = mlp.config + if getattr(config, "swiglu_limit", None) is None and getattr(config, "swiglu_compute_dtype", None) is None: + return mlp + return Xing4MLP(mlp) + + +class Xing4MoE(Xing4_0MoE): + """Reuse the HF MoE facade and experts with explicit training extensions.""" + + def __init__(self, config: Any, source: nn.Module) -> None: + """Retain HF experts and add the training router and EP execution boundary.""" + nn.Module.__init__(self) # pylint: disable=non-parent-init-called + self.config = config + self.experts = nn.ModuleList(adapt_mlp(expert) for expert in source.experts) + self.gate = Xing4Router(config, source.gate) + self.shared_experts = adapt_mlp(source.shared_experts) + self.num_experts = config.n_routed_experts + self.top_k = config.num_experts_per_tok + self.padding = config.n_routed_experts if config.use_pad_tokens else 0 + self.ep_executor = None + + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + """Reuse HF expert computation, with optional padding and EP dispatch.""" + padded = hidden_states + if self.padding: + padded = torch.cat((padded.new_zeros(padded.shape[0], self.padding, padded.shape[-1]), padded), dim=1) + if self.ep_executor is not None: + routed = self.ep_executor(self, padded) + return routed[:, self.padding:] + self.shared_experts(hidden_states) + return super().forward(padded)[:, self.padding:] + + def moe(self, hidden_states: torch.Tensor, topk_indices: torch.Tensor, + topk_weights: torch.Tensor) -> torch.Tensor: + """Select the HF per-expert or declared grouped-expert implementation.""" + if isinstance(self.experts, nn.ModuleList): + return super().moe(hidden_states, topk_indices, topk_weights) + return self.experts(hidden_states, topk_indices, topk_weights) + + def route(self, hidden: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + """Expose the same once-only router contract to the expert-parallel executor.""" + _, weights, indices = self.gate(hidden) + return indices, weights diff --git a/hyper_parallel/models/xing_4/adapter/optim/__init__.py b/hyper_parallel/models/xing_4/adapter/optim/__init__.py new file mode 100644 index 0000000000..183b6af952 --- /dev/null +++ b/hyper_parallel/models/xing_4/adapter/optim/__init__.py @@ -0,0 +1,19 @@ +# 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. +# ============================================================================ +"""Xing4 optimizer adapter entry points.""" + +from hyper_parallel.models.xing_4.adapter.optim.muon import build_optimizer, clip_qk + +__all__ = ["build_optimizer", "clip_qk"] diff --git a/hyper_parallel/models/xing_4/adapter/optim/muon.py b/hyper_parallel/models/xing_4/adapter/optim/muon.py new file mode 100644 index 0000000000..0aeede7cee --- /dev/null +++ b/hyper_parallel/models/xing_4/adapter/optim/muon.py @@ -0,0 +1,173 @@ +# 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. +# ============================================================================ +"""Muon for Xing4: AdamW decay groups and QK clipping after each step.""" + +# pylint: disable=forbidden-backend-import + +from __future__ import annotations + +from collections.abc import Sequence +from typing import Any + +import torch +import torch.distributed as dist +from torch import nn + +from hyper_parallel.components.optim.builders import Muon +from hyper_parallel.core.dtensor.dtensor import DTensor, distribute_tensor +from hyper_parallel.core.dtensor.placement_types import Replicate, Shard +from hyper_parallel.models.xing_4.adapter.optim.muon_layout import Xing4MuonLayout + +__all__ = ["build_optimizer", "clip_qk"] + + +_MUON_LAYOUTS = ("native", "mindformers_pynative") + + +def build_optimizer(*, model: nn.Module, muon_config: dict[str, Any], adamw_config: dict[str, Any], + qk_clip_threshold: float = 0.0, muon_layout: str = "native") -> Muon: + """Build framework Muon with Xing4 decay groups and optional QK clipping. + + ``native`` uses whole matrices; ``mindformers_pynative`` uses logical + matrix callbacks and requires fused linear_qkv attention. AdamW excludes + one-dimensional parameters and biases from decay. A zero threshold disables + QK clipping. With clipping enabled, both MLA up-projections must be + trainable Muon parameters; optimizer-state swap does not support their hook. + + Args: + model: Model after recipe module replacements. + muon_config: Framework Muon options. + adamw_config: Fallback AdamW options. + qk_clip_threshold: Maximum allowed per-head attention logit. + muon_layout: Whole-matrix or logical-matrix grouping. + + Returns: + The framework optimizer builder. + + Raises: + ValueError: If the layout or its projection ownership is incompatible. + """ + if muon_layout not in _MUON_LAYOUTS: + raise ValueError(f"Unknown Xing4 muon_layout: {muon_layout!r}; expected one of {_MUON_LAYOUTS}") + options = dict(muon_config) + if muon_layout == "mindformers_pynative": + options = _with_logical_layout(options, model) + # The AdamW grouping matches name fragments; full names select exactly the 1-D parameters. + no_decay = ["bias", *(name for name, parameter in model.named_parameters() if parameter.ndim == 1)] + builder = Muon(muon_config=options, adamw_config=dict(adamw_config), model=model, + no_decay_params=no_decay) + if qk_clip_threshold > 0: + attention = [module for module in model.modules() + if hasattr(module, "q_b_proj") and hasattr(module, "kv_b_proj")] + muon = builder.get_optimizer().optimizers_dict["muon"] + owned = {id(parameter) for group in muon.param_groups for parameter in group["params"]} + if not attention or any( + not projection.weight.requires_grad or id(projection.weight) not in owned + for module in attention for projection in (module.q_b_proj, module.kv_b_proj)): + raise ValueError("QK clipping requires trainable q_b_proj and kv_b_proj weights owned by Muon") + # The FP32 main-weight wrapper copies model weights back after the leaf step. + muon.register_step_post_hook( + lambda _optimizer, _args, _kwargs: clip_qk(attention, qk_clip_threshold) + ) + return builder + + +def _with_logical_layout(options: dict[str, Any], model: nn.Module) -> dict[str, Any]: + """Bind the layout callbacks after validating ownership and fused attention.""" + owned = {"reshape_fn", "ns_transform_fn"} + conflicts = sorted(key for key in options if key.removeprefix("muon_") in owned) + if conflicts: + raise ValueError(f"muon_layout='mindformers_pynative' owns {sorted(owned)}; " + f"remove {conflicts} from muon_config") + # linear_qkv only exists after Xing4MLAAttention replaces the original attention; + # without it, q_b_proj/kv_b_proj alone would silently keep the unfused K/V latent + # projection on the whole-matrix path instead of the logical layout. + names = [name for name, _ in model.named_parameters()] + linear_qkv = sum(1 for name in names if name.endswith(".self_attn.linear_qkv.weight")) + q_b_proj = sum(1 for name in names if name.endswith(".self_attn.q_b_proj.weight")) + if not linear_qkv or linear_qkv != q_b_proj: + raise ValueError("mindformers_pynative requires the fused linear_qkv attention " + f"(found {linear_qkv} linear_qkv.weight vs {q_b_proj} q_b_proj.weight)") + layout = Xing4MuonLayout.from_config(model.config) + return {**options, "reshape_fn": layout.reshape_fn, "ns_transform_fn": layout.ns_transform_fn} + + +@torch.no_grad() +def clip_qk(attention: Sequence[nn.Module], threshold: float) -> None: + """Reduce head maxima globally, scale projection rows, and clear recorded maxima. + + For s = threshold / max(maximum, threshold), Q no-RoPE and K rows use + sqrt(s), Q RoPE rows use s, and V rows are unchanged. All ranks must + provide the same modules and global-head ordering for the MAX reduction. + + Args: + attention: MLA modules that recorded maxima during forward. + threshold: Positive target maximum. + + Raises: + RuntimeError: If attention did not record maxima. + ValueError: If a TP shard does not own contiguous complete heads. + """ + maxima = [getattr(module, "max_logits", None) for module in attention] + if any(maximum is None for maximum in maxima): + raise RuntimeError("QK clipping requires the logit maxima recorded by the NPU fused attention") + maxima = [_at_global_heads(module, maximum) for module, maximum in zip(attention, maxima)] + flat = torch.cat(maxima) + if dist.is_available() and dist.is_initialized(): + dist.all_reduce(flat, op=dist.ReduceOp.MAX) + for module, maximum in zip(attention, flat.split([maximum.numel() for maximum in maxima])): + scale = threshold / maximum.clamp_min(threshold) + _scale_head_rows(module.q_b_proj.weight, scale, module.qk_nope_head_dim, scale, module.qk_rope_head_dim) + _scale_head_rows(module.kv_b_proj.weight, scale, module.qk_nope_head_dim, torch.ones_like(scale), + module.v_head_dim) + module.max_logits = None + + +def _at_global_heads(module: nn.Module, maximum: torch.Tensor) -> torch.Tensor: + """Place local maxima at global positions for contiguous row-sharded TP heads.""" + weight = module.q_b_proj.weight + heads = weight.shape[0] // (module.qk_nope_head_dim + module.qk_rope_head_dim) + if maximum.numel() == heads: + return maximum + names = (weight.device_mesh.mesh_dim_names or ()) if isinstance(weight, DTensor) else () + tp_dim = names.index("tp") if "tp" in names else None + if (tp_dim is None or weight.placements[tp_dim] != Shard(0) + or maximum.numel() * weight.device_mesh.size(tp_dim) != heads): + raise ValueError("Partial QK maxima require contiguous projection-head TP shards") + placed = maximum.new_full((heads,), float("-inf")) + start = weight.device_mesh.get_local_rank(tp_dim) * maximum.numel() + placed[start:start + maximum.numel()] = maximum + return placed + + +def _scale_head_rows(weight: torch.Tensor, scale: torch.Tensor, nope_dim: int, tail_scale: torch.Tensor, + tail_dim: int) -> None: + """Scale each head's ``nope_dim`` rows by ``sqrt(scale)`` and its next ``tail_dim`` rows by ``tail_scale``. + + As in MindFormers, only the FP32 main copy is scaled when there is one; the optimizer then + copies it back into the parameter. + """ + factors = torch.cat((scale.sqrt()[:, None].expand(-1, nope_dim), tail_scale[:, None].expand(-1, tail_dim)), + dim=-1).reshape(-1, 1) + tensor = getattr(weight, "main_param", None) + tensor = weight if tensor is None else tensor + if isinstance(tensor, DTensor): + # A row factor is shared across every column shard of the projection. + placements = tuple(Replicate() if isinstance(p, Shard) and p.dim % tensor.ndim == 1 else p + for p in tensor.placements) + local = distribute_tensor(factors.to(tensor.dtype), tensor.device_mesh, placements).to_local() + tensor.to_local().mul_(local) + else: + tensor.mul_(factors.to(tensor.dtype)) diff --git a/hyper_parallel/models/xing_4/adapter/optim/muon_layout.py b/hyper_parallel/models/xing_4/adapter/optim/muon_layout.py new file mode 100644 index 0000000000..9c9dfe688d --- /dev/null +++ b/hyper_parallel/models/xing_4/adapter/optim/muon_layout.py @@ -0,0 +1,139 @@ +# 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. +# ============================================================================ +"""Logical MLA/MLP matrix boundaries for framework Muon callbacks. + +Head grouping follows townwish4git's JTMuonLayout (hf1s/hyper-parallel#303). +""" + +from __future__ import annotations + +from dataclasses import dataclass, fields +from functools import cached_property +from typing import Any + +import torch # pylint: disable=forbidden-backend-import + +from hyper_parallel.core.optimizer.muon import NSInputTransform + + +@dataclass(frozen=True) +class Xing4MuonLayout: + """Describe complete logical matrices for the Muon callbacks. + + Tensor-parallel fragments must contain complete matrix axes; independent + expert batches may stay local. The framework scales each logical matrix. + """ + + q_lora_rank: int + kv_lora_rank: int + qk_nope_head_dim: int + qk_rope_head_dim: int + v_head_dim: int + num_attention_heads: int + hidden_size: int + intermediate_size: int + moe_intermediate_size: int + n_shared_experts: int = 0 + + def __post_init__(self) -> None: + """Validate matrix dimensions before constructing the optimizer.""" + for item in fields(self): + value = getattr(self, item.name) + minimum = 0 if item.name == "n_shared_experts" else 1 + if not isinstance(value, int) or isinstance(value, bool) or value < minimum: + raise ValueError(f"Xing4 Muon layout requires integer {item.name} >= {minimum}") + + @classmethod + def from_config(cls, config: Any) -> "Xing4MuonLayout": + """Read logical-matrix dimensions from a model configuration. + + Args: + config: Configuration containing MLA and expert dimensions. + + Returns: + A validated matrix layout. + """ + return cls(**{item.name: getattr(config, item.name, item.default) for item in fields(cls)}) + + @staticmethod + def _check_shape(name: str, tensor: torch.Tensor, shape: tuple[int, ...]) -> None: + """Require a complete logical matrix, including its non-split axis.""" + if tuple(tensor.shape) != shape: + raise ValueError(f"Unexpected Xing4 Muon shape for {name}: {tuple(tensor.shape)}; expected {shape}") + + @cached_property + def _row_sections(self) -> dict[str, tuple[int, ...]]: + """Map parameter suffixes to contiguous logical row sizes.""" + shared_rows = self.n_shared_experts * self.moe_intermediate_size + return { + "self_attn.linear_qkv.weight": (self.q_lora_rank, self.kv_lora_rank, self.qk_rope_head_dim), + "mlp.linear_fc1.weight": (self.intermediate_size, self.intermediate_size), + "shared_experts.linear_fc1.weight": (shared_rows, shared_rows), + } + + def reshape_fn(self, name: str, tensor: torch.Tensor) -> list[torch.Tensor]: + """Split fused rows or expert channels into storage-sharing views. + + Args: + name: Full model parameter name. + tensor: Complete logical gradient or local expert batch. + + Returns: + Matrix views for independent Muon updates. + """ + if name.endswith(".mlp.experts.gate_up_proj"): + if tensor.shape[0] == 0: + raise ValueError(f"Xing4 Muon requires a nonempty expert batch for {name}") + self._check_shape(name, tensor, (tensor.shape[0], self.hidden_size, 2 * self.moe_intermediate_size)) + return list(tensor.split(self.moe_intermediate_size, dim=-1)) + rows = self._row_sections.get(".".join(name.split(".")[-3:])) + if rows is None: + return [tensor] + self._check_shape(name, tensor, (sum(rows), self.hidden_size)) + return list(tensor.split(rows, dim=0)) + + def ns_transform_fn(self, name: str, tensor: torch.Tensor) -> NSInputTransform | None: + """Gather channels across heads and restore native rows after NS. + + Q splits no-RoPE/RoPE; KV splits key/value. Expert gate/up occupy the + last axis and are handled by reshape_fn instead. + + Args: + name: Full model parameter name. + tensor: Complete MLA projection gradient. + + Returns: + Matrix groups and their inverse mapping, or None for other weights. + """ + if name.endswith(".self_attn.q_b_proj.weight"): + first, second, columns = self.qk_nope_head_dim, self.qk_rope_head_dim, self.q_lora_rank + elif name.endswith(".self_attn.kv_b_proj.weight"): + first, second, columns = self.qk_nope_head_dim, self.v_head_dim, self.kv_lora_rank + else: + return None + heads = self.num_attention_heads + width = first + second + self._check_shape(name, tensor, (heads * width, columns)) + grouped = tensor.view(heads, width, columns) + pieces = [grouped[:, :first].contiguous().view(heads * first, columns), + grouped[:, first:].contiguous().view(heads * second, columns)] + + def restore(updates: list[torch.Tensor], output: torch.Tensor) -> None: + """Scatter complete group updates without changing their per-matrix scale.""" + destination = output.view(heads, width, columns) + destination[:, :first].copy_(updates[0].view(heads, first, columns)) + destination[:, first:].copy_(updates[1].view(heads, second, columns)) + + return NSInputTransform(tensors=pieces, restore=restore) diff --git a/hyper_parallel/models/xing_4/adapter/registration.py b/hyper_parallel/models/xing_4/adapter/registration.py new file mode 100644 index 0000000000..fd65159330 --- /dev/null +++ b/hyper_parallel/models/xing_4/adapter/registration.py @@ -0,0 +1,107 @@ +# 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. +# ============================================================================ +"""Register the Xing4 model and its adapter. + +Expert parallelism and the optimizer are selected by the recipe through +``plan_overrides`` and the ``optimizer`` target. +""" + +from typing import Any + +from hyper_parallel.models.adapter_spec import ModelAdapterSpec, RecomputePolicy +from hyper_parallel.models.registry import register_custom_model, register_model_adapter + + +def build_recompute_policy() -> RecomputePolicy: + """Expose whole decoder and MTP blocks; layer selection remains a recipe choice.""" + return RecomputePolicy(region_patterns=("model.layers.*", "mtp.layers.*")) + + +def get_fsdp_excluded_subtrees(model: Any) -> tuple[str, ...]: + """Use the declared MTP depths instead of inferring nested decoder units.""" + return () if model.mtp is None else ("mtp",) + + +def get_fsdp_wrap_modules(model: Any) -> tuple[str, ...]: + """Keep each MTP depth's parameters under the module that calls its decoder.""" + return (() if model.mtp is None else + tuple(f"mtp.layers.{name}" for name, _ in model.mtp.layers.named_children())) + + +def build_parameter_sharding_rules() -> list[tuple[list[str], Any]]: + """Declare Xing4 MLA roles before the generic naming rules. + + The mHC, stream-collapse head and MTP fusion parameters are declared + replicated by the recipe's ``plan_overrides``. + + Returns: + Name patterns and their parameter roles. + """ + # Discovery imports this module without requiring the distributed runtime. + from hyper_parallel.distributed.tensor_parallel.param_role import ( # pylint: disable=import-outside-toplevel + ParamRole, + ) + + return [ + (["linear_qkv"], ParamRole.REPLICATED), + (["q_b_proj", "kv_b_proj"], ParamRole.COLWISE), + ] + + +def _load_replacements(): + """Return the family's replacement-factory module (lazy provider).""" + from hyper_parallel.models.xing_4.adapter.conversion import ( # pylint: disable=import-outside-toplevel + module_replacement, + ) + + return module_replacement + + +def _load_context_parallel(): + """Load the recipe-selected CP wrappers without importing the runtime at discovery.""" + from hyper_parallel.models.xing_4.adapter.distributed import ( # pylint: disable=C0415 + context_parallel, + ) + return context_parallel + + +def _load_expert_parallel(): + """Load the recipe-selected shared EP executor adapter lazily.""" + from hyper_parallel.models.xing_4.adapter.distributed import ( # pylint: disable=C0415 + expert_parallel, + ) + return expert_parallel + + +register_custom_model( + "Xing4ForCausalLM", + "hyper_parallel.models.xing_4.adapter.training", + "Xing4ForCausalLM", +) + +XING4_ADAPTER_SPEC = ModelAdapterSpec( + architecture="Xing4ForCausalLM", + model_type="xing4_0", + replacements=_load_replacements, + context_parallel=_load_context_parallel, + expert_parallel=_load_expert_parallel, + recompute=build_recompute_policy, + sharding_rules=build_parameter_sharding_rules, + fsdp_wrap_modules=get_fsdp_wrap_modules, + fsdp_excluded_subtrees=get_fsdp_excluded_subtrees, +) +register_model_adapter(XING4_ADAPTER_SPEC) + +__all__ = ["XING4_ADAPTER_SPEC"] diff --git a/hyper_parallel/models/xing_4/adapter/training.py b/hyper_parallel/models/xing_4/adapter/training.py new file mode 100644 index 0000000000..d70d0f54c5 --- /dev/null +++ b/hyper_parallel/models/xing_4/adapter/training.py @@ -0,0 +1,293 @@ +# 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. +# ============================================================================ +"""Teacher-forced LM/MTP training over the official Xing4 backbone.""" +import math +from functools import partial +from typing import Any + +import torch +import torch.nn.functional as F +from torch import nn +from transformers.masking_utils import create_causal_mask +from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS +from transformers.utils import ModelOutput + +from hyper_parallel.components.functional.mhc_post import mhc_post +from hyper_parallel.components.losses.chunked_cross_entropy import chunked_cross_entropy +from hyper_parallel.components.modules.mtp import MTPLayer, build_mtp +from hyper_parallel.data.constants import IGNORE_INDEX +from hyper_parallel.models.materialization import register_rebuildable_buffer +from hyper_parallel.models.xing_4.adapter.moe import Xing4MoE, Xing4Router, adapt_mlp +from hyper_parallel.models.xing_4.transformer.configuration_xing4_0 import Xing4_0Config +from hyper_parallel.models.xing_4.transformer.modeling_xing4_0 import ( + Xing4_0DecoderLayer, Xing4_0ForCausalLM, Xing4_0HyperConnection, + Xing4_0Model, Xing4_0MoE, Xing4_0PreTrainedModel, Xing4_0RMSNorm, +) + +#: mHC coefficient initialization of the reference implementation's ``reset_parameter``: a +#: projection narrower than ``initializer_range``, and offsets whose mixing section starts the +#: Sinkhorn input near the identity, so each stream initially carries its own residual. +_MHC_PROJECTION_INIT_STD = 1e-4 + + +def _mhc_bias(streams: int, like: torch.Tensor) -> torch.Tensor: + """Return the pre gates, post gates and flattened mixing matrix ``hc_base`` holds. + + Args: + streams: Number of residual streams, ``config.hc_mult``. + like: Tensor supplying the device and dtype of the result. + """ + options = {"device": like.device, "dtype": like.dtype} + return torch.cat((torch.full((streams,), -math.log(3.0), **options), + torch.zeros(streams, **options), + ((torch.eye(streams, **options) - 1.0) * 5.0).flatten())) + + +class Xing4DecoderLayer(Xing4_0DecoderLayer): + """Keep HF submodules and expose its inline residual mixing for replacement.""" + + def __init__(self, config: Any, layer_idx: int, source: nn.Module | None = None) -> None: + """Retain HF attention, norms and feed-forward weights.""" + nn.Module.__init__(self) + source = Xing4_0DecoderLayer(config, layer_idx) if source is None else source + self.hidden_size = source.hidden_size + self.self_attn = source.self_attn + self.mlp = (Xing4MoE(config, source.mlp) if isinstance(source.mlp, Xing4_0MoE) + else adapt_mlp(source.mlp)) + self.input_layernorm = source.input_layernorm + self.post_attention_layernorm = source.post_attention_layernorm + # The bundled hyper-connections run unchanged; the recipe may replace them with the fused + # operators. Only the norm epsilon is the training recipe's, not the inference default. + self.attn_hc, self.ffn_hc = source.attn_hc, source.ffn_hc + self.attn_hc.input_norm.eps = config.mhc_layernorm_epsilon + self.ffn_hc.input_norm.eps = config.mhc_layernorm_epsilon + # The training recipe applies its norm epsilon to both MLA latent projections. + self.self_attn.q_a_layernorm.variance_epsilon = config.rms_norm_eps + self.self_attn.kv_a_layernorm.variance_epsilon = config.rms_norm_eps + if config.attention_softmax_scale is not None: + self.self_attn.scaling = config.attention_softmax_scale + + def forward(self, hidden_states: torch.Tensor, attention_mask: torch.Tensor | None = None, + position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None, **kwargs: Any) -> torch.Tensor: + """Call the official blocks through replaceable pre/post mHC operations.""" + post, mix, collapsed, residual = self._pre(self.attn_hc, hidden_states) + output = self.self_attn(hidden_states=self.input_layernorm(collapsed), + position_embeddings=position_embeddings, attention_mask=attention_mask, **kwargs)[0] + hidden_states = self._post(output, residual, post, mix) + post, mix, collapsed, residual = self._pre(self.ffn_hc, hidden_states) + output = self.mlp(self.post_attention_layernorm(collapsed)) + return self._post(output, residual, post, mix) + + @staticmethod + def _pre(hyper_connection: nn.Module, streams: torch.Tensor) -> tuple[torch.Tensor, ...]: + """Return the mHC coefficients plus the streams the matching post operation consumes. + + The bundled module returns three values and the post operation can take the layer input. + The fused replacement returns a fourth instead: its own output, whose backward consumes + the post gradient through ``grad_x_post``, so the input cannot stand in for it. + + Args: + hyper_connection: The layer's ``attn_hc`` or ``ffn_hc``. + streams: Residual streams entering the sublayer. + """ + post, mix, collapsed, *fused = hyper_connection(streams) + return post, mix, collapsed, fused[0] if fused else streams + + @staticmethod + def _post(output: torch.Tensor, residual: torch.Tensor, + post: torch.Tensor, mix: torch.Tensor) -> torch.Tensor: + """Convert destination-by-source mixing to the shared post layout.""" + streams = residual.shape[2] + result = mhc_post(output, residual.flatten(2), post, mix.transpose(-1, -2).contiguous(), streams) + return result.unflatten(-1, (streams, output.shape[-1])) + + +class _Xing4Initialization: + """Initialize training state and repair the bundled HC initializer's field lookup. + + Mixed in by both the backbone and the causal LM: Transformers dispatches a nested + ``PreTrainedModel`` to its own ``_init_weights``. + """ + + @torch.no_grad() + def _init_weights(self, module: nn.Module) -> None: + """Initialize one module, delegating everything this model does not own. + + Args: + module: Module to initialize. + """ + if isinstance(module, Xing4_0HyperConnection): + nn.init.normal_(module.hc_fn, mean=0.0, std=_MHC_PROJECTION_INIT_STD) + module.hc_scale.fill_(self.config.mhc_init_gating_factor) + module.hc_base.copy_(_mhc_bias(module.hc_mult, module.hc_base)) + return + if isinstance(module, Xing4Router): + nn.init.normal_(module.weight, mean=0.0, std=self.config.initializer_range) + module.tokens_per_expert.zero_() + module.e_score_correction_bias.zero_() + return + super()._init_weights(module) + + +class Xing4Model(_Xing4Initialization, Xing4_0Model): + """Use the unchanged HF backbone forward with training-aware decoder blocks.""" + + config_class = Xing4_0Config + _supports_attention_backend = False + + def __init__(self, config: Any) -> None: + super().__init__(config) + self.layers = nn.ModuleList( + Xing4DecoderLayer(config, index, source=layer) for index, layer in enumerate(self.layers)) + rotary = self.rotary_emb + rope_init_fn = (rotary.compute_default_rope_parameters if rotary.rope_type == "default" + else ROPE_INIT_FUNCTIONS[rotary.rope_type]) + with torch.device("cpu"): + frequencies, rotary.attention_scaling = rope_init_fn(config, device="cpu") + for name in ("inv_freq", "original_inv_freq"): + register_rebuildable_buffer(rotary, name, value=frequencies) + self.post_init() + + @staticmethod + def shift_tokens(tokens: torch.Tensor, pad_value: int) -> torch.Tensor: + """Shift a full training sequence; CP recipes replace its boundary exchange.""" + return F.pad(tokens[:, 1:], (0, 1), value=pad_value) + + @staticmethod + def mean_loss(loss_sum: torch.Tensor, count: torch.Tensor) -> torch.Tensor: + """Average one sequence objective; CP recipes reduce its numerator and count.""" + return loss_sum / count.clamp_min(1) + + +class Xing4MTPBlock(Xing4DecoderLayer): + """Adapt the shared MTP block's 3-D input to official Xing4 residual streams.""" + + def __init__(self, config: Any, layer_idx: int) -> None: + super().__init__(config, layer_idx) + if not isinstance(self.mlp, Xing4MoE): + raise ValueError("Xing4 MTP requires an MoE decoder at its native layer index") + self.hc_mult = config.hc_mult + + def forward(self, hidden_states: torch.Tensor, **kwargs: Any) -> torch.Tensor: + """Expand and collapse streams, leaving fusion and norms to MTPLayer.""" + streams = hidden_states.unsqueeze(2).expand(-1, -1, self.hc_mult, -1).contiguous() + return super().forward(streams, **kwargs).mean(dim=2) + + +class Xing4ForCausalLM(_Xing4Initialization, Xing4_0ForCausalLM): + """Add teacher-forced LM/MTP losses to the official causal language model.""" + + config_class = Xing4_0Config + _no_split_modules = ["Xing4DecoderLayer", "MTPLayer"] + _keys_to_ignore_on_load_unexpected = None + _can_record_outputs = None + _supports_flash_attn = False + _supports_flex_attn = False + _supports_attention_backend = False + + def __init__(self, config: Any) -> None: + Xing4_0PreTrainedModel.__init__(self, config) + if config.hidden_act != "silu" or config.q_lora_rank is None: + raise ValueError("Xing4 training requires SiLU and low-rank query projection") + if config.rope_parameters["rope_type"] not in ("default", "yarn") or not config.rope_interleave: + raise ValueError("Xing4 training requires default or YaRN interleaved RoPE") + if getattr(config, "enable_cmhc", False) or getattr(config, "enable_hc_head", False): + raise ValueError("This Xing4 backbone uses the official mHC streams and mean collapse") + if not getattr(config, "mtp_enable_hyper_connections", True): + raise ValueError("Xing4 MTP uses the same mHC decoder as the backbone") + if config.attention_dropout: + raise ValueError("Xing4 training requires attention_dropout=0") + compute_dtype = getattr(config, "compute_dtype", None) + self.embedding_compute_dtype = (getattr(torch, compute_dtype, compute_dtype) + if isinstance(compute_dtype, str) else compute_dtype) + if self.embedding_compute_dtype not in (None, torch.float16, torch.bfloat16, torch.float32): + raise ValueError(f"Unsupported Xing4 compute_dtype: {compute_dtype!r}") + self.model = Xing4Model(config) + self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) + self.mtp = build_mtp(config.num_nextn_predict_layers, layer_factory=lambda depth: MTPLayer( + config.hidden_size, Xing4MTPBlock(config, config.num_hidden_layers + depth), + norm_factory=partial(Xing4_0RMSNorm, eps=config.rms_norm_eps))) + if self.mtp is not None: + self.mtp.gradient_checkpointing = False + self.post_init() + + @classmethod + def from_config(cls, config: Any, **kwargs: Any) -> "Xing4ForCausalLM": + """Construct through the shared custom-model builder contract.""" + del kwargs + return cls(config) + + def forward(self, input_ids: torch.Tensor, labels: torch.Tensor | None = None, + shift_labels: torch.Tensor | None = None, position_ids: torch.Tensor | None = None, + attention_mask: torch.Tensor | None = None, use_cache: bool = False) -> ModelOutput: + """Return LM and weighted MTP losses for aligned causal training sequences.""" + del labels + if attention_mask is not None or use_cache: + raise ValueError("Xing4 trains causal sequences without attention masks or KV cache") + if shift_labels is None or input_ids.ndim != 2 or min(input_ids.shape) < 1 \ + or shift_labels.shape != input_ids.shape: + raise ValueError("Xing4 requires nonempty [batch, sequence] input_ids with matching shift_labels") + if position_ids is None: + position_ids = torch.arange(input_ids.shape[1], device=input_ids.device).unsqueeze(0) + embeddings = self.model.embed_tokens(input_ids).to(dtype=self.embedding_compute_dtype) + hidden = self.model(inputs_embeds=embeddings, position_ids=position_ids, use_cache=False).last_hidden_state + targets = shift_labels.masked_fill(shift_labels < 0, IGNORE_INDEX) + losses = {"foundation_loss": self._cross_entropy(hidden, targets)} + if self.mtp is not None: + position_embeddings = self.model.rotary_emb(hidden, position_ids) + losses["foundation_loss/mtp"] = self._mtp_loss( + hidden, input_ids, targets, position_embeddings, position_ids) + return ModelOutput(loss=losses) + + def _mtp_loss(self, hidden: torch.Tensor, input_ids: torch.Tensor, targets: torch.Tensor, + position_embeddings: tuple[torch.Tensor, torch.Tensor], + position_ids: torch.Tensor) -> torch.Tensor: + """Return ``mtp_loss_factor / D * sum_k CE_k``, where depth ``k`` predicts ``k`` tokens further. + + Inputs and targets shift left by one token per depth without wrapping. + """ + total = torch.zeros((), device=hidden.device, dtype=torch.float32) + for layer in self.mtp.layers: + input_ids = self.model.shift_tokens(input_ids, 0) + targets = self.model.shift_tokens(targets, IGNORE_INDEX) + embeddings = self.model.embed_tokens(input_ids).to(dtype=self.embedding_compute_dtype) + attention_mask = create_causal_mask( + config=self.config, inputs_embeds=embeddings, attention_mask=None, + past_key_values=None, position_ids=position_ids) + hidden = layer(hidden, embeddings, position_embeddings=position_embeddings, + attention_mask=attention_mask) + total = total + self._cross_entropy(hidden, targets) + return total * (self.config.mtp_loss_factor / len(self.mtp.layers)) + + def _cross_entropy(self, hidden: torch.Tensor, targets: torch.Tensor) -> torch.Tensor: + """Return the LM-head cross entropy averaged over the non-ignored targets. + + A head holding the whole vocabulary uses the chunked cross entropy, which never + materializes the sequence's logits. A tensor-parallel head runs as a module, so its + sharding plan gathers the logits or, under loss parallelism, keeps them + vocabulary-sharded for the ``loss_function`` the Trainer installs. + """ + count = targets.ne(IGNORE_INDEX).sum() + weight = self.lm_head.weight + if getattr(weight, "placements", None) is None and weight.shape[0] == self.config.vocab_size: + chunk_size = getattr(self.config, "chunk_loss_size", None) + if isinstance(chunk_size, bool) or not isinstance(chunk_size, int) or chunk_size <= 0: + raise ValueError("Full-vocabulary Xing4 cross entropy requires a positive integer chunk_loss_size") + loss_sum = chunked_cross_entropy(hidden, targets, weight, + chunk_size=chunk_size, ignore_index=IGNORE_INDEX) + else: + loss_sum = self.loss_function(self.lm_head(hidden), None, self.config.vocab_size, num_items_in_batch=1, + ignore_index=IGNORE_INDEX, shift_labels=targets) + return self.model.mean_loss(loss_sum, count) diff --git a/hyper_parallel/models/xing_4/transformer/__init__.py b/hyper_parallel/models/xing_4/transformer/__init__.py new file mode 100644 index 0000000000..3cd26d2860 --- /dev/null +++ b/hyper_parallel/models/xing_4/transformer/__init__.py @@ -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. +# ============================================================================ +"""Bundled, unmodified Hugging Face Xing4 model sources.""" diff --git a/hyper_parallel/models/xing_4/transformer/configuration_xing4_0.py b/hyper_parallel/models/xing_4/transformer/configuration_xing4_0.py new file mode 100644 index 0000000000..6b3d6efcd5 --- /dev/null +++ b/hyper_parallel/models/xing_4/transformer/configuration_xing4_0.py @@ -0,0 +1,142 @@ +from transformers.configuration_utils import PretrainedConfig +from transformers.utils import logging + +logger = logging.get_logger(__name__) + +DEEPSEEK_PRETRAINED_CONFIG_ARCHIVE_MAP = {} + + +class Xing4_0Config(PretrainedConfig): + model_type = "xing4_0" + keys_to_ignore_at_inference = ["past_key_values"] + base_model_tp_plan = { + "layers.*.mlp.experts.gate_up_proj": "packed_colwise", + "layers.*.mlp.experts.down_proj": "rowwise", + "layers.*.mlp.experts": "moe_tp_experts", + "layers.*.mlp.shared_experts.gate_proj": "colwise", + "layers.*.mlp.shared_experts.up_proj": "colwise", + "layers.*.mlp.shared_experts.down_proj": "rowwise", + "layers.*.mlp.gate_proj": "colwise", + "layers.*.mlp.up_proj": "colwise", + "layers.*.mlp.down_proj": "rowwise", + } + base_model_pp_plan = { + "embed_tokens": (["input_ids"], ["inputs_embeds"]), + "layers": (["hidden_states", "attention_mask"], ["hidden_states"]), + "norm": (["hidden_states"], ["hidden_states"]), + } + base_model_ep_plan = { + "layers.*.mlp.gate": "ep_router", + "layers.*.mlp.experts.gate_up_proj": "grouped_gemm", + "layers.*.mlp.experts.down_proj": "grouped_gemm", + "layers.*.mlp.experts": "moe_tp_experts", + } + + attribute_map = { + "num_local_experts": "n_routed_experts", + "num_mtp_layers": "num_nextn_predict_layers", + } + + def __init__( + self, + vocab_size=131072, + hidden_size=3584, + intermediate_size=9216, + moe_intermediate_size=1024, + num_hidden_layers=40, + num_nextn_predict_layers=1, + num_attention_heads=32, + num_key_value_heads=32, + n_shared_experts=1, + n_routed_experts=64, + ep_size=1, + routed_scaling_factor=2.0, + kv_lora_rank=512, + q_lora_rank=1536, + qk_rope_head_dim=64, + v_head_dim=128, + qk_nope_head_dim=128, + topk_method='noaux_tc', + n_group=8, + topk_group=4, + num_experts_per_tok=4, + moe_layer_freq=1, + first_k_dense_replace=2, + norm_topk_prob=True, + scoring_func='sigmoid', + hidden_act="silu", + max_position_embeddings=4096, + initializer_range=0.02, + rms_norm_eps=1e-6, + use_cache=True, + pad_token_id=None, + bos_token_id=1, + eos_token_id=2, + tie_word_embeddings=False, + rope_theta=10000.0, + rope_scaling=None, + rope_interleave=True, + attention_bias=False, + attention_dropout=0.0, + hc_mult: int = 4, + hc_sinkhorn_iters: int = 20, + hc_eps: float = 1.0e-6, + mhc_h_res_clamp_min=-30, + mhc_h_res_clamp_max=30, + **kwargs, + ): + self.vocab_size = vocab_size + self.max_position_embeddings = max_position_embeddings + self.hidden_size = hidden_size + self.intermediate_size = intermediate_size + self.moe_intermediate_size = moe_intermediate_size + self.num_hidden_layers = num_hidden_layers + self.num_nextn_predict_layers = num_nextn_predict_layers + self.num_attention_heads = num_attention_heads + self.n_shared_experts = n_shared_experts + self.n_routed_experts = n_routed_experts + self.ep_size = ep_size + self.routed_scaling_factor = routed_scaling_factor + self.kv_lora_rank = kv_lora_rank + self.q_lora_rank = q_lora_rank + self.qk_rope_head_dim = qk_rope_head_dim + self.v_head_dim = v_head_dim + self.qk_nope_head_dim = qk_nope_head_dim + self.qk_head_dim = self.qk_nope_head_dim + self.qk_rope_head_dim + self.head_dim = self.qk_rope_head_dim + self.topk_method = topk_method + self.n_group = n_group + self.topk_group = topk_group + self.num_experts_per_tok = num_experts_per_tok + self.moe_layer_freq = moe_layer_freq + self.first_k_dense_replace = first_k_dense_replace + self.norm_topk_prob = norm_topk_prob + self.scoring_func = scoring_func + # for backward compatibility + if num_key_value_heads is None: + num_key_value_heads = num_attention_heads + + self.num_key_value_heads = num_key_value_heads + self.hidden_act = hidden_act + self.initializer_range = initializer_range + self.rms_norm_eps = rms_norm_eps + self.use_cache = use_cache + self.rope_theta = rope_theta + self.rope_scaling = rope_scaling + self.attention_bias = attention_bias + self.attention_dropout = attention_dropout + self.hc_mult = hc_mult + self.hc_sinkhorn_iters = hc_sinkhorn_iters + self.hc_eps = hc_eps + self.mhc_h_res_clamp_min = mhc_h_res_clamp_min + self.mhc_h_res_clamp_max = mhc_h_res_clamp_max + self.rope_interleave = rope_interleave + super().__init__( + pad_token_id=pad_token_id, + bos_token_id=bos_token_id, + eos_token_id=eos_token_id, + tie_word_embeddings=tie_word_embeddings, + **kwargs, + ) + + diff --git a/hyper_parallel/models/xing_4/transformer/modeling_xing4_0.py b/hyper_parallel/models/xing_4/transformer/modeling_xing4_0.py new file mode 100644 index 0000000000..0717980f04 --- /dev/null +++ b/hyper_parallel/models/xing_4/transformer/modeling_xing4_0.py @@ -0,0 +1,701 @@ +import math +from collections.abc import Callable +from typing import Optional + +import torch +import torch.nn.functional as F +from torch import nn + +from transformers import initialization as init +from transformers.activations import ACT2FN +from transformers.cache_utils import Cache, DynamicCache +from transformers.generation import GenerationMixin +from transformers.integrations import use_experts_implementation, use_kernel_forward_from_hub +from transformers.masking_utils import create_causal_mask +from transformers.modeling_flash_attention_utils import FlashAttentionKwargs +from transformers.modeling_layers import ( + GenericForSequenceClassification, + GenericForTokenClassification, + GradientCheckpointingLayer, +) +from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast +from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update +from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel +from transformers.processing_utils import Unpack +from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple +from transformers.utils.generic import is_flash_attention_requested, maybe_autocast, merge_with_config_defaults +from transformers.utils.output_capturing import capture_outputs +from .configuration_xing4_0 import Xing4_0Config + + +class Xing4_0RMSNorm(nn.Module): + def __init__(self, hidden_size, eps: float = 1e-6) -> None: + """ + Xing4_0RMSNorm is equivalent to T5LayerNorm + """ + super().__init__() + self.weight = nn.Parameter(torch.ones(hidden_size)) + self.variance_epsilon = eps + + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + input_dtype = hidden_states.dtype + hidden_states = hidden_states.to(torch.float32) + variance = hidden_states.pow(2).mean(-1, keepdim=True) + hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) + return (self.weight * hidden_states).to(input_dtype) + + def extra_repr(self): + return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}" + + +class Xing4_0UnweightedRMSNorm(nn.Module): + def __init__(self, eps: float = 1.0e-6): + super().__init__() + self.eps = eps + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return (x.float() * torch.rsqrt(x.float().square().mean(-1, keepdim=True) + self.eps)).to(x.dtype) + + +class Xing4_0RotaryEmbedding(nn.Module): + inv_freq: torch.Tensor # fix linting for `register_buffer` + + def __init__(self, config: Xing4_0Config, device=None): + super().__init__() + self.max_seq_len_cached = config.max_position_embeddings + self.original_max_seq_len = config.max_position_embeddings + + self.config = config + + self.rope_type = self.config.rope_parameters["rope_type"] + rope_init_fn: Callable = self.compute_default_rope_parameters + if self.rope_type != "default": + rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type] + inv_freq, self.attention_scaling = rope_init_fn(self.config, device) + self.register_buffer("inv_freq", inv_freq, persistent=False) + self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False) + + @staticmethod + def compute_default_rope_parameters( + config: Xing4_0Config | None = None, + device: Optional["torch.device"] = None, + seq_len: int | None = None, + ) -> tuple["torch.Tensor", float]: + """ + Computes the inverse frequencies according to the original RoPE implementation + Args: + config ([`~transformers.PreTrainedConfig`]): + The model configuration. + device (`torch.device`): + The device to use for initialization of the inverse frequencies. + seq_len (`int`, *optional*): + The current sequence length. Unused for this type of RoPE. + Returns: + Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the + post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). + """ + base = config.rope_parameters["rope_theta"] + dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads + + attention_factor = 1.0 # Unused in this type of RoPE + + # Compute the inverse frequencies + inv_freq = 1.0 / ( + base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim) + ) + return inv_freq, attention_factor + + @torch.no_grad() + @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope) + def forward(self, x, position_ids): + inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device) + position_ids_expanded = position_ids[:, None, :].float() + + device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" + with maybe_autocast(device_type=device_type, enabled=False): # Force float32 + freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2) + emb = torch.cat((freqs, freqs), dim=-1) + cos = emb.cos() * self.attention_scaling + sin = emb.sin() * self.attention_scaling + return cos.float(), sin.float() + + +class Xing4_0MLP(nn.Module): + def __init__(self, config, intermediate_size=None): + super().__init__() + self.config = config + self.hidden_size = config.hidden_size + self.intermediate_size = config.intermediate_size if intermediate_size is None else intermediate_size + self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False) + self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False) + self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False) + self.act_fn = ACT2FN[config.hidden_act] + + def forward(self, x): + down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x)) + return down_proj + + +class Xing4_0TopkRouter(nn.Module): + def __init__(self, config): + super().__init__() + self.top_k = config.num_experts_per_tok + self.num_experts = config.num_local_experts + self.hidden_dim = config.hidden_size + self.weight = nn.Parameter(torch.zeros(self.num_experts, self.hidden_dim)) + self.routed_scaling_factor = config.routed_scaling_factor + self.num_group = config.n_group + self.topk_group = config.topk_group + self.norm_topk_prob = config.norm_topk_prob + self.register_buffer("e_score_correction_bias", torch.zeros(self.num_experts)) + + def forward(self, hidden_states): + hidden_states = hidden_states.view(-1, self.hidden_dim) + router_logits = F.linear(hidden_states.type(torch.float32), self.weight.type(torch.float32)) + scores = router_logits.sigmoid() + topk_indices = torch.topk(scores + self.e_score_correction_bias, self.top_k, dim=-1, sorted=False).indices + topk_weights = scores.gather(1, topk_indices) + if self.norm_topk_prob: + denominator = topk_weights.sum(dim=-1, keepdim=True) + 1e-20 + topk_weights /= denominator + topk_weights = topk_weights * self.routed_scaling_factor + return router_logits, topk_weights, topk_indices + + +class Xing4_0MoE(nn.Module): + """ + A mixed expert module containing shared experts. + """ + + def __init__(self, config: Xing4_0Config): + super().__init__() + self.config = config + self.experts = nn.ModuleList( + [ + Xing4_0MLP( + config, intermediate_size=config.moe_intermediate_size + ) + for i in range(config.n_routed_experts) + ] + ) + self.gate = Xing4_0TopkRouter(config) + self.shared_experts = Xing4_0MLP( + config=config, intermediate_size=config.moe_intermediate_size * config.n_shared_experts + ) + + def moe(self, hidden_states: torch.Tensor, topk_indices: torch.Tensor, topk_weights: torch.Tensor): + final_hidden_states = torch.zeros_like(hidden_states, dtype=topk_weights.dtype) + expert_mask = torch.nn.functional.one_hot(topk_indices, num_classes=len(self.experts)) + expert_mask = expert_mask.permute(2, 0, 1) + + for expert_idx in range(len(self.experts)): + expert = self.experts[expert_idx] + mask = expert_mask[expert_idx] + token_indices, weight_indices = torch.where(mask) + + if token_indices.numel() > 0: + expert_weights = topk_weights[token_indices, weight_indices] + expert_input = hidden_states[token_indices] + expert_output = expert(expert_input) + weighted_output = expert_output * expert_weights.unsqueeze(-1) + final_hidden_states.index_add_(0, token_indices, weighted_output) + return final_hidden_states.type(hidden_states.dtype) + + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + residuals = hidden_states + orig_shape = hidden_states.shape + _, topk_weights, topk_indices = self.gate(hidden_states) + hidden_states = hidden_states.view(-1, hidden_states.shape[-1]) + hidden_states = self.moe(hidden_states, topk_indices, topk_weights).view(*orig_shape) + hidden_states = hidden_states + self.shared_experts(residuals) + return hidden_states + + +def rotate_half(x): + """Rotates half the hidden dims of the input.""" + x1 = x[..., : x.shape[-1] // 2] + x2 = x[..., x.shape[-1] // 2:] + return torch.cat((-x2, x1), dim=-1) + + +def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1): + """Applies Rotary Position Embedding to the query and key tensors. + + Args: + q (`torch.Tensor`): The query tensor. + k (`torch.Tensor`): The key tensor. + cos (`torch.Tensor`): The cosine part of the rotary embedding. + sin (`torch.Tensor`): The sine part of the rotary embedding. + unsqueeze_dim (`int`, *optional*, defaults to 1): + The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and + sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note + that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and + k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes + cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have + the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2. + Returns: + `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding. + """ + ori_dtype = q.dtype + q = q.float() + k = k.float() + cos = cos.unsqueeze(unsqueeze_dim) + sin = sin.unsqueeze(unsqueeze_dim) + q_embed = (q * cos) + (rotate_half(q) * sin) + k_embed = (k * cos) + (rotate_half(k) * sin) + return q_embed.to(ori_dtype), k_embed.to(ori_dtype) + + +def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: + """ + This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, + num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) + """ + batch, num_key_value_heads, slen, head_dim = hidden_states.shape + if n_rep == 1: + return hidden_states + hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim) + return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim) + + +def eager_attention_forward( + module: nn.Module, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + attention_mask: torch.Tensor | None, + scaling: float, + dropout: float = 0.0, + **kwargs: Unpack[TransformersKwargs], +): + key_states = repeat_kv(key, module.num_key_value_groups) + value_states = repeat_kv(value, module.num_key_value_groups) + + attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling + if attention_mask is not None: + attn_weights = attn_weights + attention_mask + + attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype) + attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training) + attn_output = torch.matmul(attn_weights, value_states) + attn_output = attn_output.transpose(1, 2).contiguous() + + return attn_output, attn_weights + + +def apply_rotary_pos_emb_interleave(q, k, cos, sin, position_ids=None, unsqueeze_dim=1): + r""" + Applies interleaved Rotary Position Embedding to the query and key tensors. + + Xing4_0 lays the rotary dimensions out in interleaved pairs `(x0, x1), (x2, x3), ...`, each rotated by a + single frequency. We compute that rotation directly on the even/odd slices instead of de-interleaving with a + `view`/`transpose`/`reshape`; the output is bit-identical to the de-interleaved `rotate_half` formulation while + avoiding the extra contiguous copy. + + Args: + q (`torch.Tensor`): The query tensor. + k (`torch.Tensor`): The key tensor. + cos (`torch.Tensor`): The cosine part of the rotary embedding. + sin (`torch.Tensor`): The sine part of the rotary embedding. + position_ids (`torch.Tensor`): + The position indices of the tokens corresponding to the query and key tensors. For example, this can be + used to pass offsetted position ids when working with a KV-cache. + unsqueeze_dim (`int`, *optional*, defaults to 1): + The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and + sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note + that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and + k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes + cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have + the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2. + Returns: + `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding. + """ + # `cos`/`sin` are `cat(freqs, freqs)`; the first half holds the per-pair angle. + ori_dtype = q.dtype + q = q.float() + k = k.float() + cos = cos[..., : cos.shape[-1] // 2].unsqueeze(unsqueeze_dim) + sin = sin[..., : sin.shape[-1] // 2].unsqueeze(unsqueeze_dim) + + q1, q2 = q[..., 0::2], q[..., 1::2] + k1, k2 = k[..., 0::2], k[..., 1::2] + q_embed = torch.cat([q1 * cos - q2 * sin, q2 * cos + q1 * sin], dim=-1) + k_embed = torch.cat([k1 * cos - k2 * sin, k2 * cos + k1 * sin], dim=-1) + return q_embed.to(ori_dtype), k_embed.to(ori_dtype) + + +def yarn_get_mscale(scale=1, mscale=1): + if scale <= 1: + return 1.0 + return 0.1 * mscale * math.log(scale) + 1.0 + + +class Xing4_0Attention(nn.Module): + """Multi-headed attention from 'Attention Is All You Need' paper""" + + def __init__(self, config: Xing4_0Config, layer_idx: int): + super().__init__() + self.config = config + self.layer_idx = layer_idx + self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads + self.attention_dropout = config.attention_dropout + self.num_heads = config.num_attention_heads + + self.q_lora_rank = config.q_lora_rank + self.qk_rope_head_dim = config.qk_rope_head_dim + self.kv_lora_rank = config.kv_lora_rank + self.v_head_dim = config.v_head_dim + self.qk_nope_head_dim = config.qk_nope_head_dim + self.qk_head_dim = config.qk_head_dim + + self.is_causal = True + if self.q_lora_rank is None: + self.q_proj = nn.Linear(config.hidden_size, self.num_heads * self.qk_head_dim, bias=False) + else: + self.q_a_proj = nn.Linear(config.hidden_size, config.q_lora_rank, bias=config.attention_bias) + self.q_a_layernorm = Xing4_0RMSNorm(config.q_lora_rank) + self.q_b_proj = nn.Linear(config.q_lora_rank, self.num_heads * self.qk_head_dim, bias=False) + + self.kv_a_proj_with_mqa = nn.Linear( + config.hidden_size, + self.kv_lora_rank + self.qk_rope_head_dim, + bias=config.attention_bias, + ) + self.kv_a_layernorm = Xing4_0RMSNorm(self.kv_lora_rank) + self.kv_b_proj = nn.Linear( + self.kv_lora_rank, + self.num_heads * (self.qk_nope_head_dim + self.v_head_dim), + bias=False, + ) + + self.o_proj = nn.Linear( + self.num_heads * self.v_head_dim, + config.hidden_size, + bias=config.attention_bias, + ) + + self.scaling = self.qk_head_dim ** (-0.5) + if self.config.rope_parameters.get("rope_type", "default") != "default": + mscale_all_dim = self.config.rope_parameters.get("mscale_all_dim", 0) + scaling_factor = self.config.rope_parameters["factor"] + if mscale_all_dim: + mscale = yarn_get_mscale(scaling_factor, mscale_all_dim) + self.scaling = self.scaling * mscale * mscale + + def forward( + self, + hidden_states: torch.Tensor, + position_embeddings: tuple[torch.Tensor, torch.Tensor], + attention_mask: torch.Tensor | None, + past_key_values: Cache | None = None, + **kwargs: Unpack[FlashAttentionKwargs], + ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]: + batch_size, seq_length = hidden_states.shape[:-1] + query_shape = (batch_size, seq_length, -1, self.qk_head_dim) + key_shape = (batch_size, seq_length, -1, self.qk_nope_head_dim + self.v_head_dim) + + if self.q_lora_rank is None: + q_states = self.q_proj(hidden_states) + else: + q_states = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states))) + q_states = q_states.view(query_shape).transpose(1, 2) + q_pass, q_rot = torch.split(q_states, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1) + + compressed_kv = self.kv_a_proj_with_mqa(hidden_states) + k_pass, k_rot = torch.split(compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1) + + k_pass = self.kv_b_proj(self.kv_a_layernorm(k_pass)).view(key_shape).transpose(1, 2) + k_pass, value_states = torch.split(k_pass, [self.qk_nope_head_dim, self.v_head_dim], dim=-1) + + k_rot = k_rot.view(batch_size, 1, seq_length, self.qk_rope_head_dim) + + cos, sin = position_embeddings + if self.config.rope_interleave: # support using interleaved weights for efficiency + q_rot, k_rot = apply_rotary_pos_emb_interleave(q_rot, k_rot, cos, sin) + else: + q_rot, k_rot = apply_rotary_pos_emb(q_rot, k_rot, cos, sin) + k_rot = k_rot.expand(*k_pass.shape[:-1], -1) + + query_states = torch.cat((q_pass, q_rot), dim=-1) + key_states = torch.cat((k_pass, k_rot), dim=-1) + + if past_key_values is not None: + key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx) + + if is_flash_attention_requested(self.config) and self.qk_head_dim != self.v_head_dim: + value_states = F.pad(value_states, [0, self.qk_head_dim - self.v_head_dim]) + + attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface( + self.config._attn_implementation, eager_attention_forward + ) + + attn_output, attn_weights = attention_interface( + self, + query_states, + key_states, + value_states, + attention_mask, + dropout=0.0 if not self.training else self.attention_dropout, + scaling=self.scaling, + **kwargs, + ) + + if is_flash_attention_requested(self.config) and self.qk_head_dim != self.v_head_dim: + attn_output = attn_output[:, :, :, : self.v_head_dim] + + attn_output = attn_output.reshape(batch_size, seq_length, -1).contiguous() + attn_output = self.o_proj(attn_output) + return attn_output, attn_weights + + +class Xing4_0HyperConnection(nn.Module): + + def __init__(self, config: Xing4_0Config): + super().__init__() + self.hc_mult = config.hc_mult + self.hc_sinkhorn_iters = config.hc_sinkhorn_iters + self.hc_eps = config.hc_eps + self.input_norm = Xing4_0UnweightedRMSNorm(eps=config.rms_norm_eps) + mix = (2 + self.hc_mult) * self.hc_mult + self.hc_fn = nn.Parameter(torch.empty(mix, self.hc_mult * config.hidden_size)) + self.hc_base = nn.Parameter(torch.empty(mix)) + self.hc_scale = nn.Parameter(torch.empty(3)) + self.mhc_h_res_clamp_max = config.mhc_h_res_clamp_max + self.mhc_h_res_clamp_min = config.mhc_h_res_clamp_min + + def forward(self, hidden_streams: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + ori_dtype = hidden_streams.dtype + hc = self.hc_mult + flat = self.input_norm(hidden_streams.flatten(start_dim=2).float()) + pre_w, post_w, comb_w = F.linear(flat.to(ori_dtype), self.hc_fn.to(ori_dtype)).float().split([hc, hc, hc * hc], dim=-1) + pre_b, post_b, comb_b = self.hc_base.split([hc, hc, hc * hc]) + pre_scale, post_scale, comb_scale = self.hc_scale.unbind(0) + pre = torch.sigmoid(pre_w * pre_scale + pre_b) + post = 2 * torch.sigmoid(post_w * post_scale + post_b) + comb_logits = comb_w.view(*comb_w.shape[:-1], hc, hc) * comb_scale + comb_b.view(hc, hc) + comb_logits = torch.clamp(comb_logits, min=self.mhc_h_res_clamp_min, max=self.mhc_h_res_clamp_max) + comb_max = comb_logits.amax(dim=-1, keepdim=True) + comb = torch.exp(comb_logits - comb_max) + for _ in range(self.hc_sinkhorn_iters): + comb = comb / (comb.sum(dim=-1, keepdim=True) + self.hc_eps) + comb = comb / (comb.sum(dim=-2, keepdim=True) + self.hc_eps) + collapsed = (pre.unsqueeze(-1).to(ori_dtype) * hidden_streams).sum(dim=2) + return post.to(ori_dtype), comb.to(ori_dtype), collapsed.to(ori_dtype) + + +class Xing4_0DecoderLayer(GradientCheckpointingLayer): + def __init__(self, config: Xing4_0Config, layer_idx: int): + super().__init__() + self.hidden_size = config.hidden_size + + self.self_attn = Xing4_0Attention(config=config, layer_idx=layer_idx) + + if layer_idx >= config.first_k_dense_replace: + self.mlp = Xing4_0MoE(config) + else: + self.mlp = Xing4_0MLP(config) + + self.input_layernorm = Xing4_0RMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.post_attention_layernorm = Xing4_0RMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.attn_hc = Xing4_0HyperConnection(config) + self.ffn_hc = Xing4_0HyperConnection(config) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: torch.Tensor | None = None, + position_ids: torch.LongTensor | None = None, + past_key_values: Cache | None = None, + use_cache: bool | None = False, + position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> torch.Tensor: + post, comb, collapsed = self.attn_hc(hidden_states) + # Self Attention + collapsed = self.input_layernorm(collapsed) + attn_output, _ = self.self_attn( + hidden_states=collapsed, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_values=past_key_values, + use_cache=use_cache, + position_embeddings=position_embeddings, + **kwargs, + ) + hidden_states = post.unsqueeze(-1) * attn_output.unsqueeze(-2) + torch.matmul( + comb, hidden_states + ) + # Fully Connected + post, comb, collapsed = self.ffn_hc(hidden_states) + collapsed = self.post_attention_layernorm(collapsed) + mlp_output = self.mlp(collapsed) + return post.unsqueeze(-1) * mlp_output.unsqueeze(-2) + torch.matmul( + comb, hidden_states + ) + + +@auto_docstring +class Xing4_0PreTrainedModel(PreTrainedModel): + config: Xing4_0Config + base_model_prefix = "model" + supports_gradient_checkpointing = True + _no_split_modules = ["Xing4_0DecoderLayer"] + _skip_keys_device_placement = ["past_key_values"] + _supports_flash_attn = True + _supports_sdpa = True + _supports_flex_attn = True + + _can_compile_fullgraph = True + _supports_attention_backend = True + _can_record_outputs = { + "hidden_states": Xing4_0DecoderLayer, + "attentions": Xing4_0Attention, + } + _keep_in_fp32_modules_strict = [ + "e_score_correction_bias", + ] + _keys_to_ignore_on_load_unexpected = [r"model\.layers\.40.*"] + + @torch.no_grad() + def _init_weights(self, module): + super()._init_weights(module) + if isinstance(module, Xing4_0TopkRouter): + init.normal_(module.weight, mean=0.0, std=self.config.initializer_range) + init.zeros_(module.e_score_correction_bias) + elif isinstance(module, Xing4_0HyperConnection): + init.normal_(module.fn, mean=0.0, std=self.config.initializer_range) + init.zeros_(module.base) + init.ones_(module.scale) + + +@auto_docstring +class Xing4_0Model(Xing4_0PreTrainedModel): + def __init__(self, config: Xing4_0Config): + super().__init__(config) + self.padding_idx = config.pad_token_id + self.vocab_size = config.vocab_size + + self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) + self.layers = nn.ModuleList( + [Xing4_0DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] + ) + self.norm = Xing4_0RMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.rotary_emb = Xing4_0RotaryEmbedding(config=config) + self.gradient_checkpointing = False + self.post_init() + + @merge_with_config_defaults + @capture_outputs + @auto_docstring + def forward( + self, + input_ids: torch.LongTensor | None = None, + attention_mask: torch.Tensor | None = None, + position_ids: torch.LongTensor | None = None, + past_key_values: Cache | None = None, + inputs_embeds: torch.FloatTensor | None = None, + use_cache: bool | None = None, + **kwargs: Unpack[TransformersKwargs], + ) -> BaseModelOutputWithPast: + if (input_ids is None) ^ (inputs_embeds is not None): + raise ValueError("You must specify exactly one of input_ids or inputs_embeds") + + if inputs_embeds is None: + inputs_embeds: torch.Tensor = self.embed_tokens(input_ids) + if use_cache and past_key_values is None: + past_key_values = DynamicCache(config=self.config) + + if position_ids is None: + past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0 + position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens + position_ids = position_ids.unsqueeze(0) + + causal_mask = create_causal_mask( + config=self.config, + inputs_embeds=inputs_embeds, + attention_mask=attention_mask, + past_key_values=past_key_values, + position_ids=position_ids, + ) + + hidden_states = inputs_embeds.unsqueeze(2).expand(-1, -1, self.config.hc_mult, -1).contiguous() + position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids) + for decoder_layer in self.layers[: self.config.num_hidden_layers]: + hidden_states = decoder_layer( + hidden_states, + attention_mask=causal_mask, + position_embeddings=position_embeddings, + position_ids=position_ids, + past_key_values=past_key_values, + use_cache=use_cache, + **kwargs, + ) + hidden_states = hidden_states.mean(dim=2) + hidden_states = self.norm(hidden_states) + return BaseModelOutputWithPast( + last_hidden_state=hidden_states, + past_key_values=past_key_values, + ) + + +class Xing4_0ForCausalLM(Xing4_0PreTrainedModel, GenerationMixin): + _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"} + _tp_plan = {"lm_head": "colwise_gather_output"} + _pp_plan = {"lm_head": (["hidden_states"], ["logits"])} + _fsdp_plan = {"lm_head": "keep_full_weight"} + + def __init__(self, config): + super().__init__(config) + self.model = Xing4_0Model(config) + self.vocab_size = config.vocab_size + self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) + + # Initialize weights and apply final processing + self.post_init() + + def forward( + self, + input_ids: torch.LongTensor | None = None, + attention_mask: torch.Tensor | None = None, + position_ids: torch.LongTensor | None = None, + past_key_values: Cache | None = None, + inputs_embeds: torch.FloatTensor | None = None, + labels: torch.LongTensor | None = None, + use_cache: bool | None = None, + logits_to_keep: int | torch.Tensor = 0, + **kwargs: Unpack[TransformersKwargs], + ) -> CausalLMOutputWithPast: + outputs: BaseModelOutputWithPast = self.model( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + **kwargs, + ) + + hidden_states = outputs.last_hidden_state + # Only compute necessary logits, and do not upcast them to float if we are not computing the loss + slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep + logits = self.lm_head(hidden_states[:, slice_indices, :]) + loss = None + if labels is not None: + loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs) + + return CausalLMOutputWithPast( + loss=loss, + logits=logits, + past_key_values=outputs.past_key_values, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + +__all__ = [ + "Xing4_0PreTrainedModel", + "Xing4_0Model", + "Xing4_0ForCausalLM", +] + + diff --git a/hyper_parallel/models/xing_4/transformer/tokenization_xing4_0.py b/hyper_parallel/models/xing_4/transformer/tokenization_xing4_0.py new file mode 100644 index 0000000000..a4fce4e4da --- /dev/null +++ b/hyper_parallel/models/xing_4/transformer/tokenization_xing4_0.py @@ -0,0 +1,222 @@ +import os +from shutil import copyfile +from typing import Any, Dict, List, Optional, Tuple +import sentencepiece as spm +from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer +from transformers.utils import logging + +logger = logging.get_logger(__name__) + +VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"} + +# TODO: when we get download url from huggingface, refresh the map +PRETRAINED_VOCAB_FILES_MAP = { + "vocab_file": {}, + "tokenizer_file": {}, +} + + +class Xing4_0Tokenizer(PreTrainedTokenizer): + vocab_files_names = VOCAB_FILES_NAMES + pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP + model_input_names = ["input_ids", "attention_mask"] + + def __init__( + self, + vocab_file, + unk_token="", + bos_token="<_start>", + eos_token="<_end>", + pad_token="<_pad>", + sp_model_kwargs: Optional[Dict[str, Any]] = None, + add_bos_token=True, + add_eos_token=False, + clean_up_tokenization_spaces=False, + **kwargs, + ): + self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs + bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token + eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token + pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token + self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs) + self.sp_model.Load(vocab_file) + super().__init__( + bos_token=bos_token, + eos_token=eos_token, + pad_token=pad_token, + add_bos_token=add_bos_token, + add_eos_token=add_eos_token, + sp_model_kwargs=self.sp_model_kwargs, + clean_up_tokenization_spaces=clean_up_tokenization_spaces, + **kwargs, + ) + self.vocab_file = vocab_file + self.add_bos_token = add_bos_token + self.add_eos_token = add_eos_token + + def __getstate__(self): + state = self.__dict__.copy() + state["sp_model"] = None + return state + + def __setstate__(self, d): + self.__dict__ = d + self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs) + self.sp_model.Load(self.vocab_file) + + @property + def vocab_size(self): + """Returns vocab size""" + return self.sp_model.get_piece_size() + + def get_vocab(self): + """Returns vocab as a dict""" + vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)} + vocab.update(self.added_tokens_encoder) + return vocab + + @property + def vocab(self): + return self.get_vocab() + + def _tokenize(self, text): + """Returns a tokenized string.""" + return self.sp_model.encode(text, out_type=str) + + def _convert_token_to_id(self, token): + """Converts a token (str) in an id using the vocab.""" + return self.sp_model.piece_to_id(token) + + def _convert_id_to_token(self, index): + """Converts an index (integer) in a token (str) using the vocab.""" + token = self.sp_model.IdToPiece(index) + return token + + def convert_tokens_to_string(self, tokens): + """Converts a sequence of tokens (string) in a single string.""" + current_sub_tokens = [] + out_string = "" + # prev_is_special = False + for i, token in enumerate(tokens): + # make sure that special tokens are not decoded using sentencepiece model + if token in self.all_special_tokens: + # if not prev_is_special and i != 0: + # out_string += " " + out_string += self.sp_model.decode(current_sub_tokens) + token + # prev_is_special = True + current_sub_tokens = [] + else: + current_sub_tokens.append(token) + # prev_is_special = False + out_string += self.sp_model.decode(current_sub_tokens) + return out_string + + def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]: + """ + Save the vocabulary and special tokens file to a directory. + + Args: + save_directory (`str`): + The directory in which to save the vocabulary. + + Returns: + `Tuple(str)`: Paths to the files saved. + """ + if not os.path.isdir(save_directory): + logger.error(f"Vocabulary path ({save_directory}) should be a directory") + return + out_vocab_file = os.path.join( + save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] + ) + + if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file): + copyfile(self.vocab_file, out_vocab_file) + elif not os.path.isfile(self.vocab_file): + with open(out_vocab_file, "wb") as fi: + content_spiece_model = self.sp_model.serialized_model_proto() + fi.write(content_spiece_model) + + return (out_vocab_file,) + + def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None): + bos_token_id = [self.bos_token_id] if self.add_bos_token else [] + eos_token_id = [self.eos_token_id] if self.add_eos_token else [] + + output = bos_token_id + token_ids_0 + eos_token_id + + if token_ids_1 is not None: + output = output + bos_token_id + token_ids_1 + eos_token_id + + return output + + def get_special_tokens_mask( + self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, + already_has_special_tokens: bool = False + ) -> List[int]: + """ + Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding + special tokens using the tokenizer `prepare_for_model` method. + + Args: + token_ids_0 (`List[int]`): + List of IDs. + token_ids_1 (`List[int]`, *optional*): + Optional second list of IDs for sequence pairs. + already_has_special_tokens (`bool`, *optional*, defaults to `False`): + Whether or not the token list is already formatted with special tokens for the model. + + Returns: + `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token. + """ + if already_has_special_tokens: + return super().get_special_tokens_mask( + token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True + ) + + bos_token_id = [1] if self.add_bos_token else [] + eos_token_id = [1] if self.add_eos_token else [] + + if token_ids_1 is None: + return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id + return ( + bos_token_id + + ([0] * len(token_ids_0)) + + eos_token_id + + bos_token_id + + ([0] * len(token_ids_1)) + + eos_token_id + ) + + def create_token_type_ids_from_sequences( + self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None + ) -> List[int]: + """ + Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT + sequence pair mask has the following format: + + ``` + 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 + | first sequence | second sequence | + ``` + + if token_ids_1 is None, only returns the first portion of the mask (0s). + + Args: + token_ids_0 (`List[int]`): + List of ids. + token_ids_1 (`List[int]`, *optional*): + Optional second list of IDs for sequence pairs. + + Returns: + `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s). + """ + bos_token_id = [self.bos_token_id] if self.add_bos_token else [] + eos_token_id = [self.eos_token_id] if self.add_eos_token else [] + + output = [0] * len(bos_token_id + token_ids_0 + eos_token_id) + + if token_ids_1 is not None: + output += [1] * len(bos_token_id + token_ids_1 + eos_token_id) + + return output +