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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions examples/training_demo/xing4/engram.md
Original file line number Diff line number Diff line change
@@ -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 边界由注意力入口管理。
91 changes: 91 additions & 0 deletions hyper_parallel/components/modules/engram/assets.py
Original file line number Diff line number Diff line change
@@ -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"]
2 changes: 2 additions & 0 deletions hyper_parallel/components/modules/engram/parallel_engram.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}"
Expand Down
76 changes: 2 additions & 74 deletions hyper_parallel/models/deepseek_v41/configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Original file line number Diff line number Diff line change
@@ -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)
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
Loading
Loading