From a6595f140f0dd9ed4c2c30d541f00480965956c6 Mon Sep 17 00:00:00 2001 From: Pangxz Date: Sun, 22 Nov 2026 16:12:45 +0800 Subject: [PATCH] feat(xing4): integrate Engram with staged grouped experts --- examples/training_demo/xing4/engram.md | 65 ++++++ .../components/modules/engram/assets.py | 91 +++++++++ .../modules/engram/parallel_engram.py | 2 + .../models/deepseek_v41/configuration.py | 76 +------ .../adapter/distributed/engram_parallel.py | 82 ++++++++ .../adapter/distributed/expert_parallel.py | 7 +- .../xing_4/adapter/optim/muon_layout.py | 12 +- .../models/xing_4/adapter/registration.py | 65 ++++-- hyper_parallel/models/xing_4/engram_config.py | 189 ++++++++++++++++++ .../models/xing_4/modeling_xing4_0.py | 55 ++++- tests/ut/models/xing_4/test_engram_config.py | 111 ++++++++++ tests/ut/trainer/test_aux_loss_scaling.py | 4 - tests/ut/trainer/test_text_trainer.py | 4 - 13 files changed, 654 insertions(+), 109 deletions(-) create mode 100644 examples/training_demo/xing4/engram.md create mode 100644 hyper_parallel/components/modules/engram/assets.py create mode 100644 hyper_parallel/models/xing_4/adapter/distributed/engram_parallel.py create mode 100644 hyper_parallel/models/xing_4/engram_config.py create mode 100644 tests/ut/models/xing_4/test_engram_config.py diff --git a/examples/training_demo/xing4/engram.md b/examples/training_demo/xing4/engram.md new file mode 100644 index 0000000000..cf8f05cfe9 --- /dev/null +++ b/examples/training_demo/xing4/engram.md @@ -0,0 +1,65 @@ +# Xing4 Engram 训练 + +在 [Xing4 训练配方](train_single.yaml) 的 `model.config` 中设置 `engram_config_path`,读取架构 JSON 中的 +八个 Engram 字段。也可以直接在 `model.config` 中填写这些字段。两处同时设置时,以配方中的字段为准。 +附件格式支持 UTF-16。主干、注意力和 mHC 仍按 Xing4 训练配方配置。 + +对于 `config_arch_demo_1130.json`,使用零基主干层 1 和 11,主干深度至少为 12。复现附件形状时使用 +40 层、`hidden_size: 3584`、`vocab_size: 131072` 和 4 路残差。现有训练主干采用 MLA 和可选融合 mHC。 + +| 字段 | 附件示例 | 用途 | +| --- | --- | --- | +| `engram_layer_ids` | `[1, 11]` | 启用查表的主干层,按列表顺序生成哈希桶 | +| `engram_max_ngram_size` | `3` | 从 bigram 开始计数,覆盖 2、3、4-gram | +| `engram_n_heads` | `8` | 每组 n-gram 的独立哈希头数 | +| `engram_head_dim` | `256` | 每行嵌入宽度,拼接后的投影输入宽度为 `24 × 256 = 6144` | +| `engram_vocab_size` | `16000000` | 每个哈希桶的素数搜索基数 | +| `engram_num_embeddings` | `[384006168, 384016682]` | 各层逻辑表行数,须等于该层桶大小之和 | +| `engram_pad_token_id` | `3` | n-gram 历史不足时使用的原始 token ID | +| `engram_compressed_vocab_size` | `131072` | 哈希输入的压缩词表大小 | + +Engram 桶基数可独立于模型词表调整。生成新表时要同步更新逻辑行数。默认可用 `engram_table_pad_multiple` +配置物理表行数向上对齐,默认值为 16。EP 要求物理行数可被 EP 度数整除。对齐不改变哈希结果或 checkpoint +的逻辑行数。 + +从头训练时,压缩词表等于模型词表可使用恒等 token map。使用压缩 tokenizer 或已有权重时,通过 +`model.config.engram_assets_path` 传入原始 JSON 资产,其中包含 token map、逐层倍数和素数桶。 +资产中的 `max_ngram_size` 使用最大 n-gram 阶数,附件中的 `engram_max_ngram_size` 使用组数。 +恢复训练时保留原始资产和层顺序。开启 Engram 的配方使用 PR1594 的 `GroupedExperts`,旧版 Xing4 Engram +checkpoint 的专家张量需要先转换布局。MindFormers 全量 checkpoint 条件见 [Xing4 训练指南](README.md)。 + +## 启动 + +先按 [Xing4 训练指南](README.md) 准备 CANN、隔离 Python 环境和预分词数据。复制训练配方到任务目录,设置 +数据与输出路径。从头训练时留空恢复路径。以下命令在 HyperParallel 源码根目录运行。 + +```bash +# 单卡,YAML 使用缩小的模型和 Engram 表。 +torchrun --standalone --nproc_per_node=1 -m examples.training_demo.train_text \ + /path/to/xing4-engram-smoke.yaml + +# 单机双卡,EP2 对 Engram 表做行分片,普通参数按 DP2 分片。 +torchrun --standalone --nproc_per_node=2 -m examples.training_demo.train_text \ + /path/to/xing4-engram-smoke.yaml \ + --accelerator.ep_size=2 --fsdp_config.dp_shard_size=2 --fsdp_config.edp_shard_size=1 \ + --training.global_batch_size=2 +``` + +Engram 的行分片和并行计算由 `build_model` 声明。缩小配方可以保留示例的两层主干,使用以下参数启用第 1 层。 + +```yaml +model: + config: + engram_layer_ids: [1] + engram_max_ngram_size: 3 + engram_n_heads: 2 + engram_head_dim: 16 + engram_vocab_size: 17 + engram_num_embeddings: [156] + engram_pad_token_id: 3 + engram_compressed_vocab_size: 131072 +``` + +附件的两张表合计约 366 GiB BF16 或 732 GiB FP32,另需预留主干参数、梯度和优化器状态。实际部署前根据 +设备容量选择拓扑与表规模。自定义训练输入可传入与 CP 本地 token 对齐的 `engram_segment_starts` 和 +`engram_token_mask`。前者重置哈希历史,后者选择参与查表的 token。注意力的 packed 边界由注意力入口管理。 diff --git a/hyper_parallel/components/modules/engram/assets.py b/hyper_parallel/components/modules/engram/assets.py new file mode 100644 index 0000000000..e0e583cd5f --- /dev/null +++ b/hyper_parallel/components/modules/engram/assets.py @@ -0,0 +1,91 @@ +# 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. +# ============================================================================ +"""Deterministic prime-bucket layouts for Engram.""" + +from __future__ import annotations + +import math +from typing import Iterable + + +def _is_prime(value: int) -> bool: + """Return whether ``value`` is prime.""" + if value < 2: + return False + if value % 2 == 0: + return value == 2 + limit = math.isqrt(value) + return all(value % divisor for divisor in range(3, limit + 1, 2)) + + +def _next_unused_prime(start: int, seen: set[int]) -> int: + """Return the first unused prime strictly greater than ``start``.""" + candidate = start + 1 + while not _is_prime(candidate) or candidate in seen: + candidate += 1 + return candidate + + +def build_scaled_engram_buckets( + layer_ids: Iterable[int], + *, + bucket_base: int, + max_ngram_size: int, + num_heads: int, +) -> tuple[list[list[list[int]]], list[int]]: + """Build synchronized prime buckets and table sizes for scaled Engram. + + Args: + layer_ids: Decoder layers that contain an Engram module. + bucket_base: Approximate rows assigned to each n-gram/head bucket. + max_ngram_size: Largest n-gram included in the hash. + num_heads: Independent Engram hash heads. + + Returns: + Nested prime moduli ``[layer][ngram][head]`` and the exact number of + embedding rows required by every layer. + + Raises: + ValueError: If a shape argument cannot describe a useful table. + """ + layer_ids = list(layer_ids) + if not layer_ids: + raise ValueError("scaled Engram requires at least one layer") + if bucket_base < 2: + raise ValueError("engram bucket_base must be at least 2") + if max_ngram_size < 2: + raise ValueError("engram max_ngram_size must be at least 2") + if num_heads <= 0: + raise ValueError("engram num_heads must be positive") + + seen: set[int] = set() + all_primes: list[list[list[int]]] = [] + table_sizes: list[int] = [] + for _ in layer_ids: + layer_primes: list[list[int]] = [] + for _ in range(max_ngram_size - 1): + head_primes: list[int] = [] + current = bucket_base - 1 + for _ in range(num_heads): + current = _next_unused_prime(current, seen) + seen.add(current) + head_primes.append(current) + layer_primes.append(head_primes) + all_primes.append(layer_primes) + table_sizes.append(sum(prime for row in layer_primes for prime in row)) + return all_primes, table_sizes + + +__all__ = ["build_scaled_engram_buckets"] diff --git a/hyper_parallel/components/modules/engram/parallel_engram.py b/hyper_parallel/components/modules/engram/parallel_engram.py index 29e3648166..856b7a21a1 100644 --- a/hyper_parallel/components/modules/engram/parallel_engram.py +++ b/hyper_parallel/components/modules/engram/parallel_engram.py @@ -303,6 +303,8 @@ def _sparse_lookup( padded_num_embeddings: int, ) -> torch.Tensor: """Route requested global rows to their EP owners and restore order.""" + if ep_size == 1: + return embedding(hash_ids) if padded_num_embeddings % ep_size: raise ValueError( f"Engram padded rows {padded_num_embeddings} are not divisible by ep_size={ep_size}" diff --git a/hyper_parallel/models/deepseek_v41/configuration.py b/hyper_parallel/models/deepseek_v41/configuration.py index 8aae2f47d7..2045ad8a8f 100644 --- a/hyper_parallel/models/deepseek_v41/configuration.py +++ b/hyper_parallel/models/deepseek_v41/configuration.py @@ -12,80 +12,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ -"""Pure-Python configuration helpers for the DeepSeek-V4.1 validation crop.""" - -from __future__ import annotations - -import math -from typing import Iterable - - -def _is_prime(value: int) -> bool: - """Return whether ``value`` is prime.""" - if value < 2: - return False - if value % 2 == 0: - return value == 2 - limit = math.isqrt(value) - return all(value % divisor for divisor in range(3, limit + 1, 2)) - - -def _next_unused_prime(start: int, seen: set[int]) -> int: - """Return the first unused prime strictly greater than ``start``.""" - candidate = start + 1 - while not _is_prime(candidate) or candidate in seen: - candidate += 1 - return candidate - - -def build_scaled_engram_buckets( - layer_ids: Iterable[int], - *, - bucket_base: int, - max_ngram_size: int, - num_heads: int, -) -> tuple[list[list[list[int]]], list[int]]: - """Build synchronized prime buckets and table sizes for scaled Engram. - - Args: - layer_ids: Decoder layers that contain an Engram module. - bucket_base: Approximate rows assigned to each n-gram/head bucket. - max_ngram_size: Largest n-gram included in the hash. - num_heads: Independent Engram hash heads. - - Returns: - Nested prime moduli ``[layer][ngram][head]`` and the exact number of - embedding rows required by every layer. - - Raises: - ValueError: If a shape argument cannot describe a useful table. - """ - layer_ids = list(layer_ids) - if not layer_ids: - raise ValueError("scaled Engram requires at least one layer") - if bucket_base < 2: - raise ValueError("engram bucket_base must be at least 2") - if max_ngram_size < 2: - raise ValueError("engram max_ngram_size must be at least 2") - if num_heads <= 0: - raise ValueError("engram num_heads must be positive") - - seen: set[int] = set() - all_primes: list[list[list[int]]] = [] - table_sizes: list[int] = [] - for _ in layer_ids: - layer_primes: list[list[int]] = [] - for _ in range(max_ngram_size - 1): - head_primes: list[int] = [] - current = bucket_base - 1 - for _ in range(num_heads): - current = _next_unused_prime(current, seen) - seen.add(current) - head_primes.append(current) - layer_primes.append(head_primes) - all_primes.append(layer_primes) - table_sizes.append(sum(prime for row in layer_primes for prime in row)) - return all_primes, table_sizes +"""Configuration helpers for the DeepSeek-V4.1 validation crop.""" +from hyper_parallel.components.modules.engram.assets import build_scaled_engram_buckets __all__ = ["build_scaled_engram_buckets"] diff --git a/hyper_parallel/models/xing_4/adapter/distributed/engram_parallel.py b/hyper_parallel/models/xing_4/adapter/distributed/engram_parallel.py new file mode 100644 index 0000000000..c26a8a1495 --- /dev/null +++ b/hyper_parallel/models/xing_4/adapter/distributed/engram_parallel.py @@ -0,0 +1,82 @@ +# 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. +# ============================================================================ +"""Bind Xing4 Engram to the sequence and table meshes selected by the recipe.""" + +from __future__ import annotations + +from collections.abc import Callable +from dataclasses import replace +from typing import Any + +import torch + +from hyper_parallel.components.modules.engram import EngramModule +from hyper_parallel.core.dtensor.placement_types import Replicate, Shard +from hyper_parallel.distributed.mesh import DistributedSetup +from hyper_parallel.distributed.recipe_spec import ModuleShardingSpec, local_compute + + +@local_compute +def xing4_engram_compute_fn( + *, module: EngramModule, mesh: Any, tp_mesh: Any, cp_mesh: Any, ep_mesh: Any, +) -> Callable: + """Bind the shared Engram sequence alignment and EP row lookup.""" + del mesh + if not isinstance(module, EngramModule): + raise TypeError("Xing4 parallel Engram requires the EngramModule replacement") + ep_rank = 0 if ep_mesh is None else ep_mesh.get_local_rank("ep") + ep_size = 1 if ep_mesh is None else ep_mesh["ep"].size() + if module.padded_num_embeddings % ep_size: + raise ValueError("Xing4 Engram padded table rows must be divisible by the EP degree") + coordinates = { + "ep_rank": ep_rank, + "ep_size": ep_size, + "ep_group": None if ep_mesh is None else ep_mesh.get_group("ep"), + "cp_rank": 0 if cp_mesh is None else cp_mesh.get_local_rank(), + "cp_size": 1 if cp_mesh is None else cp_mesh.size(), + "cp_group": None if cp_mesh is None else cp_mesh.get_group(), + "tp_rank": 0 if tp_mesh is None else tp_mesh.get_local_rank(), + "tp_size": 1 if tp_mesh is None else tp_mesh.size(), + } + + def forward( + module: EngramModule, hidden_states: torch.Tensor, input_ids: torch.Tensor, + segment_starts: torch.Tensor | None = None, token_mask: torch.Tensor | None = None, + ) -> torch.Tensor: + """Run Engram with the local token IDs and residual streams.""" + return module.parallel_forward(hidden_states, input_ids, segment_starts, token_mask, **coordinates) + + return forward + + +def with_engram_parallelism(setup: DistributedSetup) -> DistributedSetup: + """Declare Engram placement and communication for a parallel Xing4 build.""" + mesh = setup.mesh_context + overrides = dict(setup.plan_overrides or {}) + key = "model.layers.*.engram" + spec = overrides.get(key, ModuleShardingSpec()) + replicas = {"tp": Replicate()} + params = { + "embed.weight": {"ep": Shard(0)} if mesh.ep_size > 1 else replicas, + "wkv.weight": replicas, + "q_weight": replicas, + "k_weight": replicas, + } + overrides[key] = replace( + spec, params={**params, **(spec.params or {})}, + region_dispatch=False if spec.region_dispatch is None else spec.region_dispatch, + local_compute_fn=spec.local_compute_fn or xing4_engram_compute_fn, + ) + return replace(setup, plan_overrides=overrides) diff --git a/hyper_parallel/models/xing_4/adapter/distributed/expert_parallel.py b/hyper_parallel/models/xing_4/adapter/distributed/expert_parallel.py index 44ad0145a8..396ed123d5 100644 --- a/hyper_parallel/models/xing_4/adapter/distributed/expert_parallel.py +++ b/hyper_parallel/models/xing_4/adapter/distributed/expert_parallel.py @@ -19,6 +19,7 @@ import torch +from hyper_parallel.components.modules.moe.grouped_experts.grouped_experts import GroupedExpertsModule 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.expert_parallel.routing import resolve_moe_router @@ -49,11 +50,13 @@ def xing4_ep_compute_fn(*, module: Any, mesh: Any, tp_mesh: Any, cp_mesh: Any, """ del mesh, tp_mesh, cp_mesh route = type(module).route - executor = None if ep_mesh is None else build_ep_compute( + # PR1594 expert members own routing transport; keep the recipe's optional test router. + staged = isinstance(module.experts, GroupedExpertsModule) + executor = None if ep_mesh is None or staged else build_ep_compute( module, ep_mesh, router_fn=route, archetype_key="xing4", expected_attrs=["gate", "experts", "shared_experts"], combine=SHARED_MERGE_MODES["none"], use_grouped_gemm=True, fix_router=fix_router) - if ep_mesh is None: + if executor is None: route = resolve_moe_router(route, fix_router) def forward(module: Any, hidden_states: torch.Tensor) -> torch.Tensor: diff --git a/hyper_parallel/models/xing_4/adapter/optim/muon_layout.py b/hyper_parallel/models/xing_4/adapter/optim/muon_layout.py index a795855a80..0a26ac16f7 100644 --- a/hyper_parallel/models/xing_4/adapter/optim/muon_layout.py +++ b/hyper_parallel/models/xing_4/adapter/optim/muon_layout.py @@ -23,6 +23,7 @@ import torch # pylint: disable=forbidden-backend-import from hyper_parallel.core.optimizer.muon import NSInputTransform +from hyper_parallel.models.xing_4.engram_config import engram_enabled @dataclass(frozen=True) @@ -43,6 +44,7 @@ class Xing4MuonLayout: intermediate_size: int moe_intermediate_size: int n_shared_experts: int = 0 + staged_experts: bool = False @classmethod def from_config(cls, config: Any) -> "Xing4MuonLayout": @@ -54,7 +56,9 @@ def from_config(cls, config: Any) -> "Xing4MuonLayout": Returns: The logical matrix layout. """ - return cls(**{item.name: getattr(config, item.name) for item in fields(cls) if hasattr(config, item.name)}) + values = {item.name: getattr(config, item.name) for item in fields(cls) if hasattr(config, item.name)} + values["staged_experts"] = engram_enabled(config) + return cls(**values) @staticmethod def _check_shape(name: str, tensor: torch.Tensor, shape: tuple[int, ...]) -> None: @@ -83,6 +87,9 @@ def reshape_fn(self, name: str, tensor: torch.Tensor) -> list[torch.Tensor]: Matrix views for independent Muon updates. """ if name.endswith(".mlp.experts.gate_up_proj"): + if self.staged_experts: + self._check_shape(name, tensor, (tensor.shape[0], 2 * self.moe_intermediate_size, self.hidden_size)) + return list(tensor.split(self.moe_intermediate_size, dim=-2)) 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:])) @@ -94,8 +101,7 @@ def reshape_fn(self, name: str, tensor: torch.Tensor) -> list[torch.Tensor]: 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. + Q splits no-RoPE/RoPE and KV splits key/value. Expert gate/up use reshape_fn. Args: name: Full model parameter name. diff --git a/hyper_parallel/models/xing_4/adapter/registration.py b/hyper_parallel/models/xing_4/adapter/registration.py index 2591ef0209..a1be63e9f7 100644 --- a/hyper_parallel/models/xing_4/adapter/registration.py +++ b/hyper_parallel/models/xing_4/adapter/registration.py @@ -30,23 +30,33 @@ from importlib import import_module from typing import Any +from hyper_parallel.components.modules import GroupedExperts +from hyper_parallel.components.modules.moe.grouped_experts.grouped_experts import GroupedExpertsModule from hyper_parallel.distributed.tensor_parallel.param_role import ParamRole from hyper_parallel.models.adapter_spec import ModelAdapterSpec, RecomputePolicy from hyper_parallel.models.registry import register_custom_model, register_model_adapter from hyper_parallel.models.replacement import ModuleReplacementRequest +from hyper_parallel.models.xing_4.engram_config import engram_enabled def _replacements(model: Any, context: Mapping[str, Any]) -> tuple[ModuleReplacementRequest, ...]: - """Apply the shared CP implementation to MLA in both the backbone and MTP.""" - del model - if context["cp_size"] == 1: - return () - # Model registration precedes construction of the NPU training classes. - from hyper_parallel.models.xing_4.adapter.distributed.context_parallel import build_xing4_mla_cp - from hyper_parallel.models.xing_4.modeling_xing4_0 import Xing4MLAAttention - - return (ModuleReplacementRequest(match=("*.self_attn",), target=build_xing4_mla_cp, - module_type=Xing4MLAAttention),) + """Select mesh-aware MLA and routed-expert members at their module boundaries.""" + requests = [] + if context["cp_size"] > 1: + # The training classes are loaded only after model construction. + from hyper_parallel.models.xing_4.adapter.distributed.context_parallel import ( # pylint: disable=C0415 + build_xing4_mla_cp, + ) + from hyper_parallel.models.xing_4.modeling_xing4_0 import Xing4MLAAttention # pylint: disable=C0415 + + requests.append(ModuleReplacementRequest( + match=("*.self_attn",), target=build_xing4_mla_cp, module_type=Xing4MLAAttention, + )) + if engram_enabled(model.config) and any(isinstance(module, GroupedExpertsModule) for module in model.modules()): + requests.append(ModuleReplacementRequest( + match=("*.mlp.experts",), target=GroupedExperts, module_type=GroupedExpertsModule, + )) + return tuple(requests) def build_recompute_policy() -> RecomputePolicy: @@ -60,9 +70,35 @@ def get_fsdp_excluded_subtrees(model: Any) -> tuple[str, ...]: 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())) + """Wrap each MTP depth and separate EP-owned Engram tables from dense projections.""" + mtp_units = (() if model.mtp is None else + tuple(f"mtp.layers.{name}" for name, _ in model.mtp.layers.named_children())) + engram_units = tuple( + fqn for fqn, _ in model.named_modules() if fqn.endswith((".engram.embed", ".engram.wkv")) + ) + return engram_units + mtp_units + + +def get_fsdp_execution_order(model: Any, module_fqns: tuple[str, ...]) -> tuple[str, ...]: + """Place Engram children next to the backbone layer that executes them.""" + del model + selected = set(module_fqns) + child_suffixes = ("engram.embed", "engram.wkv", "mlp.experts", "mtp_block.mlp.experts") + child_units = { + f"{parent}.{suffix}" + for parent in module_fqns for suffix in child_suffixes + } & selected + order = [] + for fqn in module_fqns: + if fqn in child_units: + continue + order.append(fqn) + for suffix in child_suffixes: + child = f"{fqn}.{suffix}" + if child in selected: + order.append(child) + order.extend(fqn for fqn in module_fqns if fqn not in order) + return tuple(order) def build_parameter_sharding_rules() -> list[tuple[list[str], Any]]: @@ -75,7 +111,7 @@ def build_parameter_sharding_rules() -> list[tuple[list[str], Any]]: Name patterns and their parameter roles. """ return [ - (["linear_qkv"], ParamRole.REPLICATED), + (["linear_qkv", "engram"], ParamRole.REPLICATED), (["q_b_proj", "kv_b_proj"], ParamRole.COLWISE), ] @@ -94,6 +130,7 @@ def build_parameter_sharding_rules() -> list[tuple[list[str], Any]]: recompute=build_recompute_policy, sharding_rules=build_parameter_sharding_rules, fsdp_wrap_modules=get_fsdp_wrap_modules, + fsdp_execution_order=get_fsdp_execution_order, fsdp_excluded_subtrees=get_fsdp_excluded_subtrees, ) register_model_adapter(XING4_ADAPTER_SPEC) diff --git a/hyper_parallel/models/xing_4/engram_config.py b/hyper_parallel/models/xing_4/engram_config.py new file mode 100644 index 0000000000..5d50cb8344 --- /dev/null +++ b/hyper_parallel/models/xing_4/engram_config.py @@ -0,0 +1,189 @@ +# 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. +# ============================================================================ +"""Translate Xing4 architecture fields into a device Engram layout.""" + +from __future__ import annotations + +from dataclasses import dataclass +import json +from pathlib import Path +from typing import Any + +import numpy as np + +from hyper_parallel.components.modules.engram.assets import build_scaled_engram_buckets + + +_ARCH_FIELDS = ( + "engram_layer_ids", "engram_num_embeddings", "engram_max_ngram_size", + "engram_vocab_size", "engram_n_heads", "engram_head_dim", + "engram_pad_token_id", "engram_compressed_vocab_size", +) + + +def merge_engram_config(values: dict[str, Any]) -> None: + """Import only Engram fields from an architecture JSON into recipe values.""" + path = values.pop("engram_config_path", None) + if path is None: + return + source = _read_json(path) + if "vocab_size" in source and source["vocab_size"] != values.get("vocab_size", 131072): + raise ValueError("Xing4 and Engram architecture JSON must use the same vocab_size") + missing = [name for name in _ARCH_FIELDS if name not in source] + if missing: + raise ValueError(f"Missing Engram architecture fields: {missing}") + for name in _ARCH_FIELDS: + values.setdefault(name, source[name]) + + +def engram_enabled(config: Any) -> bool: + """Return whether the Xing4 config selects any Engram tables.""" + return bool(getattr(config, "engram_layer_ids", None) or getattr(config, "engram_assets_path", None)) + + +def _read_json(path: str) -> dict[str, Any]: + value = json.loads(Path(path).expanduser().read_bytes()) + if not isinstance(value, dict): + raise ValueError(f"Engram JSON must be an object: {path}") + return value + + +def _int(value: Any, name: str, minimum: int = 1) -> int: + if isinstance(value, bool) or not isinstance(value, int) or value < minimum: + raise ValueError(f"{name} must be an integer >= {minimum}") + return value + + +def _validate_token_map(mapping: list[int], vocab_size: int, compressed_size: int) -> None: + if (len(mapping) != vocab_size or any(isinstance(value, bool) or not isinstance(value, int) for value in mapping) + or min(mapping) < 0 or max(mapping) != compressed_size - 1 + or len(set(mapping)) != compressed_size): + raise ValueError("Engram token_map must map every LM token into the declared compressed vocabulary") + + +def _hash_multipliers(layer_ids: list[int], order: int, compressed_size: int) -> list[list[int]]: + upper = np.iinfo(np.int64).max // compressed_size // 2 + return [ + (np.random.default_rng(10007 * layer).integers(0, upper, size=order, dtype=np.int64) * 2 + 1).tolist() + for layer in layer_ids + ] + + +def _generated_assets(config: Any) -> dict[str, Any]: + missing = [name for name in _ARCH_FIELDS if getattr(config, name, None) is None] + if missing: + raise ValueError(f"Missing Xing4 Engram fields: {missing}") + compressed_size = _int(config.engram_compressed_vocab_size, "engram_compressed_vocab_size") + if compressed_size != config.vocab_size: + raise ValueError("Compressed Xing4 Engram requires engram_assets_path with an explicit token_map") + # Xing4 counts hash groups from the bigram. The shared mapper takes the largest order. + order = _int(config.engram_max_ngram_size, "engram_max_ngram_size") + 1 + layer_ids = config.engram_layer_ids + _validate_layers(layer_ids, config.num_hidden_layers) + heads = _int(config.engram_n_heads, "engram_n_heads") + base = _int(config.engram_vocab_size, "engram_vocab_size", 2) + primes, _ = build_scaled_engram_buckets(layer_ids, bucket_base=base, max_ngram_size=order, num_heads=heads) + return { + "layer_ids": layer_ids, "num_embeddings": config.engram_num_embeddings, + "max_ngram_size": order, "bucket_base": base, "num_heads": heads, + "head_dim": config.engram_head_dim, "pad_token_id": config.engram_pad_token_id, + "token_map": list(range(config.vocab_size)), + "multipliers": _hash_multipliers(layer_ids, order, compressed_size), + "primes": primes, + } + + +def _validate_layers(layer_ids: list[int], depth: int) -> None: + if (not isinstance(layer_ids, (list, tuple)) or not layer_ids + or any(isinstance(layer, bool) or not isinstance(layer, int) or not 0 <= layer < depth + for layer in layer_ids) + or len(set(layer_ids)) != len(layer_ids)): + raise ValueError("engram_layer_ids must identify distinct Xing4 backbone layers") + + +@dataclass(frozen=True) +class Xing4EngramConfig: + """Construction facts for a shared Engram member on one Xing4 layer.""" + + assets: dict[str, Any] + layer_id: int + hidden_size: int + hc_mult: int + embedding_dim: int + eps: float + logical_num_embeddings: int + padded_num_embeddings: int + clamp_value: float = 1e-6 + + +def _validate_architecture_fields(config: Any, assets: dict[str, Any], compressed_size: int) -> None: + asset_fields = ("layer_ids", "num_embeddings", "max_ngram_size", "bucket_base", + "num_heads", "head_dim", "pad_token_id", "compressed_vocab_size") + metadata = { + **assets, "compressed_vocab_size": compressed_size, "max_ngram_size": assets["max_ngram_size"] - 1, + } + for field, key in zip(_ARCH_FIELDS, asset_fields, strict=True): + configured = getattr(config, field, None) + if configured is not None and configured != metadata.get(key): + raise ValueError(f"{field} does not match Xing4 Engram assets") + + +def resolve_engram_layers(config: Any) -> tuple[Xing4EngramConfig, ...]: + """Validate the hash and table layouts before constructing device parameters.""" + path = getattr(config, "engram_assets_path", None) + if not path and not engram_enabled(config): + if any(getattr(config, name, None) is not None for name in _ARCH_FIELDS[1:]): + raise ValueError("engram_layer_ids is required with Xing4 Engram settings") + return () + assets = _read_json(path) if path else _generated_assets(config) + if assets.get("source_model_type", "xing4_0") != "xing4_0": + raise ValueError("Engram assets must use source_model_type xing4_0") + layers = assets["layer_ids"] + _validate_layers(layers, config.num_hidden_layers) + mapping = assets["token_map"] + compressed_size = getattr(config, "engram_compressed_vocab_size", None) + if compressed_size is None: + compressed_size = len(set(mapping)) + compressed_size = _int(compressed_size, "engram_compressed_vocab_size") + _validate_token_map(mapping, config.vocab_size, compressed_size) + if _int(assets["pad_token_id"], "engram_pad_token_id", 0) >= config.vocab_size: + raise ValueError("engram_pad_token_id is outside the LM vocabulary") + embedding_dim = _int(assets["head_dim"], "engram_head_dim") + order = _int(assets["max_ngram_size"], "Engram asset max_ngram_size", 2) + heads = _int(assets["num_heads"], "engram_n_heads") + _validate_architecture_fields(config, assets, compressed_size) + pad_multiple = _int(getattr(config, "engram_table_pad_multiple", 16), "engram_table_pad_multiple") + logical = assets["num_embeddings"] + padded = assets.get("padded_num_embeddings", logical) + primes = assets["primes"] + multipliers = assets["multipliers"] + if any(len(rows) != len(layers) for rows in (primes, multipliers, logical, padded)): + raise ValueError("Engram buckets, multipliers and table sizes must have one entry per layer") + + result = [] + for layer, buckets, factors, size, storage in zip(layers, primes, multipliers, logical, padded, strict=True): + if len(buckets) != order - 1 or any(len(row) != heads for row in buckets) or len(factors) != order: + raise ValueError(f"Invalid Xing4 Engram hash layout for layer {layer}") + hash_rows = sum(_int(modulus, "Engram bucket modulus", 2) for row in buckets for modulus in row) + if _int(size, "engram_num_embeddings") != hash_rows: + raise ValueError(f"Xing4 layer {layer} declares {size} Engram rows but its hash buckets need {hash_rows}") + storage = _int(storage, "padded_num_embeddings", size) + if "padded_num_embeddings" not in assets or hasattr(config, "engram_table_pad_multiple"): + storage = (storage + pad_multiple - 1) // pad_multiple * pad_multiple + result.append(Xing4EngramConfig( + assets, layer, config.hidden_size, config.hc_mult if config.enable_hyper_connections else 1, + embedding_dim, config.rms_norm_eps, size, storage, + )) + return tuple(result) diff --git a/hyper_parallel/models/xing_4/modeling_xing4_0.py b/hyper_parallel/models/xing_4/modeling_xing4_0.py index 6a445bfa77..1b575afa2d 100644 --- a/hyper_parallel/models/xing_4/modeling_xing4_0.py +++ b/hyper_parallel/models/xing_4/modeling_xing4_0.py @@ -31,7 +31,7 @@ from __future__ import annotations -from collections.abc import Callable, Mapping +from collections.abc import Callable from dataclasses import replace from functools import partial from typing import Any @@ -56,7 +56,11 @@ from hyper_parallel.components.losses.chunked_cross_entropy import chunked_cross_entropy from hyper_parallel.components.modules.attention.multi_latent_attention import MultiLatentAttentionModule from hyper_parallel.components.modules.attention.multi_latent_attention.multi_latent_attention import apply_mla_rope +from hyper_parallel.components.modules import GroupedExperts as StagedGroupedExperts +from hyper_parallel.components.modules.engram import Engram, EngramModule from hyper_parallel.components.modules.grouped_experts import GroupedExperts +from hyper_parallel.components.modules.moe.grouped_experts import GroupedExpertsConfig +from hyper_parallel.components.modules.moe.grouped_experts.grouped_experts import GroupedExpertsModule from hyper_parallel.components.modules.mtp import MTPLayer, build_mtp from hyper_parallel.components.modules.rms_norm import RMSNorm, RMSNormModule from hyper_parallel.core.activation_memory.recompute_state import is_recomputing @@ -64,6 +68,8 @@ from hyper_parallel.data.constants import IGNORE_INDEX from hyper_parallel.models import HyperAutoModelForCausalLM from hyper_parallel.models.materialization import register_rebuildable_buffer +from hyper_parallel.models.xing_4.adapter.distributed.engram_parallel import with_engram_parallelism +from hyper_parallel.models.xing_4.engram_config import engram_enabled, merge_engram_config, resolve_engram_layers 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, @@ -323,7 +329,14 @@ def __init__(self, config: Any, source: nn.Module, layer_idx: int) -> None: """Pack the official experts and add the training router and EP boundary.""" nn.Module.__init__(self) # pylint: disable=non-parent-init-called self.config = config - self.experts = build_grouped_experts(config, source.experts) + if engram_enabled(config): + self.experts = StagedGroupedExperts(config=GroupedExpertsConfig( + num_experts=config.n_routed_experts, hidden_size=config.hidden_size, + intermediate_size=config.moe_intermediate_size, routing_weight_mode="output", + init_method_std=config.initializer_range, num_layers=config.num_hidden_layers, + )) + else: + self.experts = build_grouped_experts(config, source.experts) self.gate = Xing4Router(config, source.gate, layer_idx) # The recipe replaces this dense MLP with the shared SwiGLUMLP. self.shared_experts = source.shared_experts @@ -403,10 +416,18 @@ def __init__(self, config: Any, layer_idx: int, *, enable_hyper_connections: boo self.ffn_hc = Xing4FusedHyperConnection(source.ffn_hc) 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: - """Run the shared blocks with ordinary residuals or fused mHC.""" + position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None, + engram_input_ids: torch.Tensor | None = None, engram_segment_starts: torch.Tensor | None = None, + engram_token_mask: torch.Tensor | None = None, **kwargs: Any) -> torch.Tensor: + """Apply Engram before attention and run the configured residual path.""" # The HF backbone supplies a shard-local causal mask. MLA builds its causal mask from global lengths. del attention_mask + if hasattr(self, "engram"): + if engram_input_ids is None: + raise ValueError("Xing4 Engram requires original input_ids for lookup") + streams = hidden_states if self.enable_hyper_connections else hidden_states.unsqueeze(2) + streams = self.engram(streams, engram_input_ids, engram_segment_starts, engram_token_mask) + hidden_states = streams if self.enable_hyper_connections else streams.squeeze(2) if not self.enable_hyper_connections: output = self.self_attn(hidden_states=self.input_layernorm(hidden_states), position_embeddings=position_embeddings, **kwargs)[0] @@ -445,7 +466,7 @@ def _init_training_weights(owner: Xing4_0PreTrainedModel, module: nn.Module) -> nn.init.zeros_(module.hc_base) elif isinstance(module, RMSNormModule): nn.init.ones_(module.weight) - elif isinstance(module, GroupedExperts): + elif isinstance(module, (GroupedExperts, GroupedExpertsModule, EngramModule)): module.reset_parameters() else: Xing4_0PreTrainedModel._init_weights(owner, module) @@ -467,12 +488,15 @@ class Xing4Model(Xing4_0Model): def __init__(self, config: Any) -> None: """Reuse the HF backbone and register RoPE tables for post-sharding materialization.""" + engram_layers = resolve_engram_layers(config) super().__init__(config) self.sequence_group = None self.layers = nn.ModuleList( Xing4DecoderLayer(config, index, enable_hyper_connections=config.enable_hyper_connections, source=layer) for index, layer in enumerate(self.layers) ) + for layer_config in engram_layers: + self.layers[layer_config.layer_id].engram = Engram(config=layer_config) rotary = self.rotary_emb rope_init_fn = (rotary.compute_default_rope_parameters if rotary.rope_type == "default" else ROPE_INIT_FUNCTIONS[rotary.rope_type]) @@ -485,12 +509,17 @@ def __init__(self, config: Any) -> None: def forward(self, input_ids: torch.Tensor | None = None, attention_mask: torch.Tensor | None = None, position_ids: torch.Tensor | None = None, past_key_values: Any = None, inputs_embeds: torch.Tensor | None = None, use_cache: bool | None = None, + engram_input_ids: torch.Tensor | None = None, **kwargs: Any) -> BaseModelOutputWithPast: """Run the backbone for training. The plain residual path keeps three-dimensional hidden states and requires causal attention without an explicit mask or KV cache. """ + if engram_enabled(self.config): + if use_cache or past_key_values is not None: + raise ValueError("Xing4 Engram training requires complete sequences without KV cache") + kwargs["engram_input_ids"] = input_ids if engram_input_ids is None else engram_input_ids if self.config.enable_hyper_connections: return super().forward(input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, @@ -590,7 +619,9 @@ def from_config(cls, config: Any, **kwargs: Any) -> "Xing4ForCausalLM": 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: + attention_mask: torch.Tensor | None = None, use_cache: bool = False, + engram_segment_starts: torch.Tensor | None = None, + engram_token_mask: torch.Tensor | None = None) -> ModelOutput: """Return LM and weighted MTP losses for aligned causal training sequences.""" del labels if attention_mask is not None or use_cache: @@ -602,7 +633,10 @@ def forward(self, input_ids: torch.Tensor, labels: torch.Tensor | None = None, for router in self._hash_routers: router.token_ids = input_ids 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 + hidden = self.model( + inputs_embeds=embeddings, position_ids=position_ids, use_cache=False, engram_input_ids=input_ids, + engram_segment_starts=engram_segment_starts, engram_token_mask=engram_token_mask, + ).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: @@ -657,6 +691,7 @@ def create_config(config: dict[str, Any]) -> Xing4_0Config: ValueError: If the recipe selects semantics the shared components do not implement. """ values = dict(config) + merge_engram_config(values) if "use_pad_tokens" in values: raise ValueError("Xing4 uses native empty-expert handling; remove use_pad_tokens from the model config") for alias, field in (("num_residual_streams", "hc_mult"), ("mhc_sinkhorn_iterations", "hc_sinkhorn_iters"), @@ -713,9 +748,13 @@ def build_model(*, config: dict[str, Any], **options: Any) -> PreTrainedModel: precision = strategy.mix_precision custom_params = {name: dtype for name, dtype in precision.custom_params.items() if name not in ("*.attn_hc.*", "*.ffn_hc.*")} - options["distributed_setup"] = replace( + setup = replace( setup, strategy_config=replace(strategy, mix_precision=replace(precision, custom_params=custom_params)) ) + if setup is not None and engram_enabled(model_config): + setup = with_engram_parallelism(setup) + if setup is not None: + options["distributed_setup"] = setup model = HyperAutoModelForCausalLM.from_config(model_config, **options) mesh = getattr(options.get("distributed_setup"), "mesh_context", None) if mesh is not None: diff --git a/tests/ut/models/xing_4/test_engram_config.py b/tests/ut/models/xing_4/test_engram_config.py new file mode 100644 index 0000000000..e40b5534a2 --- /dev/null +++ b/tests/ut/models/xing_4/test_engram_config.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. +# ============================================================================ +"""Verify how the Xing4 architecture describes the shared Engram layout.""" + +import json +import tempfile +import unittest +from pathlib import Path +from types import SimpleNamespace + +import torch + +from hyper_parallel.components.modules.engram import Engram +from hyper_parallel.core.dtensor.placement_types import Replicate, Shard +from hyper_parallel.distributed.mesh import DistributedSetup, MeshContext +from hyper_parallel.models.xing_4.adapter.distributed.engram_parallel import with_engram_parallelism +from hyper_parallel.models.xing_4.engram_config import merge_engram_config, resolve_engram_layers + + +class TestXing4EngramConfig(unittest.TestCase): + """Check attachment layout, logical rows, and scratch hashing.""" + + def setUp(self): + """Define the attachment and the matching backbone shape.""" + self.architecture = { + "vocab_size": 131072, "engram_layer_ids": [1, 11], "engram_num_embeddings": [384006168, 384016682], + "engram_max_ngram_size": 3, "engram_vocab_size": 16000000, "engram_n_heads": 8, "engram_head_dim": 256, + "engram_pad_token_id": 3, "engram_compressed_vocab_size": 131072, + "use_cache": True, "layer_types": ["kda", "dsa"], + } + self.model = { + "vocab_size": 131072, "num_hidden_layers": 40, "hidden_size": 3584, + "enable_hyper_connections": True, "rms_norm_eps": 1e-6, "hc_mult": 4, + } + + def test_utf16_architecture_and_meta_parameters(self): + """Import only Engram fields and preserve the attachment checkpoint rows.""" + with tempfile.TemporaryDirectory() as directory: + source = Path(directory) / "architecture.json" + source.write_text(json.dumps(self.architecture), encoding="utf-16") + values = dict(self.model, engram_config_path=str(source)) + merge_engram_config(values) + self.assertNotIn("layer_types", values) + self.assertNotIn("use_cache", values) + config = SimpleNamespace(**values) + layouts = resolve_engram_layers(config) + self.assertEqual([layout.layer_id for layout in layouts], [1, 11]) + for layout, rows, padded in zip( + layouts, (384006168, 384016682), (384006176, 384016688), strict=True, + ): + with torch.device("meta"): + engram = Engram(config=layout) + self.assertEqual(engram.embed.weight.shape, (padded, 256)) + self.assertEqual(engram.wkv.weight.shape, (17920, 6144)) + self.assertEqual(engram.q_weight.shape, (4, 3584)) + self.assertEqual(engram.checkpoint_logical_shapes(), {"embed.weight": (rows, 256)}) + self.assertEqual(engram.hash_mapping.max_ngram_size, 4) + + def test_tiny_scratch_table_and_masks(self): + """Generate the same hashes twice and keep masked-out residual rows intact.""" + config = SimpleNamespace(**dict( + self.model, vocab_size=32, hidden_size=4, enable_hyper_connections=False, + engram_layer_ids=[1], engram_num_embeddings=[156], engram_max_ngram_size=3, + engram_vocab_size=17, engram_n_heads=2, engram_head_dim=2, + engram_pad_token_id=3, engram_compressed_vocab_size=32, + )) + layout = resolve_engram_layers(config)[0] + self.assertEqual(layout.assets, resolve_engram_layers(config)[0].assets) + engram = Engram(config=layout) + ids = torch.tensor([[1, 2, 4, 8, 9]]) + starts = torch.tensor([[True, False, True, False, False]]) + mask = torch.tensor([[True, True, True, False, True]]) + hidden = torch.randn(1, 5, 1, 4) + actual = engram(hidden, ids, starts, mask) + torch.testing.assert_close(actual[:, 3], hidden[:, 3]) + actual.square().mean().backward() + self.assertGreater(engram.embed.weight.grad.norm().item(), 0.0) + + config.engram_num_embeddings = [157] + with self.assertRaisesRegex(ValueError, "hash buckets need 156"): + resolve_engram_layers(config) + config.engram_compressed_vocab_size = 31 + with self.assertRaisesRegex(ValueError, "explicit token_map"): + resolve_engram_layers(config) + + + def test_explicit_placements_for_single_rank_and_ep(self): + """Keep every trainable Engram parameter covered at EP1 and shard only the table at EP2.""" + for ep_size, expected in ((1, {"tp": Replicate()}), (2, {"ep": Shard(0)})): + with self.subTest(ep_size=ep_size): + setup = DistributedSetup(mesh_context=MeshContext(ep_size=ep_size)) + result = with_engram_parallelism(setup) + spec = result.plan_overrides["model.layers.*.engram"] + self.assertIsNone(setup.plan_overrides) + self.assertEqual(spec.params["embed.weight"], expected) + for name in ("wkv.weight", "q_weight", "k_weight"): + self.assertEqual(spec.params[name], {"tp": Replicate()}) + self.assertFalse(spec.region_dispatch) + self.assertTrue(callable(spec.local_compute_fn)) diff --git a/tests/ut/trainer/test_aux_loss_scaling.py b/tests/ut/trainer/test_aux_loss_scaling.py index eda4c258db..084bcfca72 100644 --- a/tests/ut/trainer/test_aux_loss_scaling.py +++ b/tests/ut/trainer/test_aux_loss_scaling.py @@ -58,8 +58,6 @@ def forward( class TestTrainerAuxLossScaling(unittest.TestCase): """Exercise the actual BaseTrainer microstep and loss aggregation.""" - @arg_mark(plat_marks=["cpu_linux", "cpu_macos"], level_mark="level0", - card_mark="onecard", essential_mark="essential") def test_rank_average_matches_equal_microbatch_objective(self) -> None: """Match equal microbatch weights for independent main, MTP and auxiliary branches. @@ -100,8 +98,6 @@ def test_rank_average_matches_equal_microbatch_objective(self) -> None: self.assertEqual(trainer.step_micro_batches, 0) - @arg_mark(plat_marks=["cpu_linux", "cpu_macos"], level_mark="level0", - card_mark="onecard", essential_mark="essential") def test_unequal_microbatches_match_weighted_explicit_objective(self) -> None: """ Feature: Auxiliary-loss training lifecycle. diff --git a/tests/ut/trainer/test_text_trainer.py b/tests/ut/trainer/test_text_trainer.py index c9ec2daa27..7bbdee7131 100644 --- a/tests/ut/trainer/test_text_trainer.py +++ b/tests/ut/trainer/test_text_trainer.py @@ -79,8 +79,6 @@ def test_default_loss_uses_aligned_trainer_token_count(self) -> None: torch.testing.assert_close(loss, torch.zeros_like(loss)) torch.testing.assert_close(logits.grad, torch.zeros_like(logits.grad)) - @arg_mark(plat_marks=["cpu_linux", "cpu_macos"], level_mark="level0", - card_mark="onecard", essential_mark="essential") def test_construction_initializes_configured_loss_aggregation(self) -> None: """Feature: Text Trainer shared setup. @@ -101,8 +99,6 @@ def test_construction_initializes_configured_loss_aggregation(self) -> None: f"expected aggregation={mode}, got={trainer.base.loss_aggregation}") - @arg_mark(plat_marks=["cpu_linux", "cpu_macos"], level_mark="level0", - card_mark="onecard", essential_mark="essential") def test_template_logging_is_independent_of_dataset_debug(self) -> None: """Feature: Independent template debug configuration.