Read code changes as Git diffs. Identifying strings are masked; binary files are listed by their full relative names.
mindspeed_llm · 5 changed files
Base commit: 72c49a6260c73669678b8f39b1ba41a4789bb555
diff --git a/mindspeed_llm/core/models/lfm2/__init__.py b/mindspeed_llm/core/models/lfm2/__init__.pynew file mode 100644index 0000000000000000000000000000000000000000..30ca4d40bc1338a8ad28821b8dc26d8b8ffd007a--- /dev/null+++ b/mindspeed_llm/core/models/lfm2/__init__.py@@ -0,0 +1,2 @@+# coding=utf-8+# Copyright (c) 2025, HUAWEI CORPORATION. All rights reserved.diff --git a/mindspeed_llm/core/models/lfm2/short_conv.py b/mindspeed_llm/core/models/lfm2/short_conv.pynew file mode 100644index 0000000000000000000000000000000000000000..f34b028b496461abccab2b57b2c432d888423a3b--- /dev/null+++ b/mindspeed_llm/core/models/lfm2/short_conv.py@@ -0,0 +1,164 @@+# coding=utf-8+# Copyright (c) 2025, HUAWEI CORPORATION. All rights reserved.+#+# 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.+"""LFM2 short convolution (gated causal depthwise conv) sequence mixer.++The LFM2 hybrid architecture replaces self-attention in most of its layers by a+short gated convolution. For an input ``x`` the block computes::++ B, C, x' = split(in_proj(x), 3)+ y = C * causal_depthwise_conv1d(B * x')+ out = out_proj(y)++This module is designed to be plugged into the ``self_attention`` slot of a+Megatron-Core ``TransformerLayer``, so it accepts (and ignores) the attention+specific keyword arguments and returns the ``(output, bias)`` pair expected by+the bias-dropout-add fusion that follows it.+"""++from dataclasses import dataclass+from typing import Union++import torch+import torch.nn.functional as F++from megatron.core.transformer.module import MegatronModule+from megatron.core.transformer.spec_utils import ModuleSpec, build_module+from megatron.core.transformer.transformer_config import TransformerConfig++# Number of gate/value projections produced by ``in_proj``: B, C and x.+LFM2_CONV_PROJECTIONS = 3+# Kernel width of the short convolution (``conv_L_cache`` in the HF config).+LFM2_DEFAULT_CONV_KERNEL = 3+++@dataclass+class Lfm2ShortConvSubmodules:+ """Submodules of the LFM2 short convolution mixer."""++ in_proj: Union[ModuleSpec, type] = None+ out_proj: Union[ModuleSpec, type] = None+++class Lfm2ShortConv(MegatronModule):+ """LFM2 gated short convolution mixer.++ Takes an input of shape ``[s, b, h]`` and returns an output of the same+ shape together with an optional bias (``None`` when biases are disabled).+ """++ def __init__(+ self,+ config: TransformerConfig,+ submodules: Lfm2ShortConvSubmodules,+ layer_number: int = 1,+ attn_mask_type=None,+ cp_comm_type: str = None,+ **kwargs,+ ):+ super().__init__(config=config)++ self.config = config+ self.layer_number = layer_number+ self.attn_mask_type = attn_mask_type+ self.hidden_size = config.hidden_size+ self.kernel_size = int(+ getattr(config, "lfm2_conv_kernel", LFM2_DEFAULT_CONV_KERNEL)+ or LFM2_DEFAULT_CONV_KERNEL+ )+ # The convolution is depthwise and therefore cannot be split across+ # tensor-parallel ranks together with the projections.+ if self.config.tensor_model_parallel_size != 1:+ raise AssertionError(+ "LFM2 short convolution currently requires "+ "--tensor-model-parallel-size 1"+ )++ self.in_proj = build_module(+ submodules.in_proj,+ self.hidden_size,+ LFM2_CONV_PROJECTIONS * self.hidden_size,+ config=self.config,+ init_method=self.config.init_method,+ gather_output=False,+ bias=self.config.add_bias_linear,+ skip_bias_add=True,+ is_expert=False,+ tp_comm_buffer_name="fc1",+ )++ # Depthwise causal convolution over the sequence dimension. Kept as a+ # plain ``nn.Conv1d`` so that its ``weight`` has the same [h, 1, k]+ # layout as the Hugging Face checkpoint.+ self.conv = torch.nn.Conv1d(+ in_channels=self.hidden_size,+ out_channels=self.hidden_size,+ kernel_size=self.kernel_size,+ groups=self.hidden_size,+ bias=False,+ padding=self.kernel_size - 1,+ )++ self.out_proj = build_module(+ submodules.out_proj,+ self.hidden_size,+ self.hidden_size,+ config=self.config,+ init_method=self.config.output_layer_init_method,+ bias=self.config.add_bias_linear,+ input_is_parallel=True,+ skip_bias_add=True,+ is_expert=False,+ tp_comm_buffer_name="proj",+ )++ def _causal_conv(self, hidden_states: torch.Tensor) -> torch.Tensor:+ """Apply the causal depthwise convolution to a ``[s, b, h]`` tensor."""+ seq_length = hidden_states.shape[0]+ # [s, b, h] -> [b, h, s] for the channel-first convolution.+ conv_input = hidden_states.permute(1, 2, 0).contiguous()+ conv_output = F.conv1d(+ conv_input,+ self.conv.weight,+ bias=self.conv.bias,+ padding=self.kernel_size - 1,+ groups=self.hidden_size,+ )+ # Left padding makes the convolution causal; drop the tail it adds.+ conv_output = conv_output[..., :seq_length]+ # [b, h, s] -> [s, b, h]+ return conv_output.permute(2, 0, 1)++ def forward(+ self,+ hidden_states: torch.Tensor,+ attention_mask=None,+ key_value_states=None,+ inference_context=None,+ rotary_pos_emb=None,+ rotary_pos_cos=None,+ rotary_pos_sin=None,+ attention_bias=None,+ packed_seq_params=None,+ sequence_len_offset=None,+ *,+ inference_params=None,+ ):+ """Mix along the sequence dimension with a gated short convolution."""+ projected, _ = self.in_proj(hidden_states)+ b_gate, c_gate, values = torch.chunk(projected, LFM2_CONV_PROJECTIONS, dim=-1)++ conv_output = self._causal_conv(b_gate * values)+ output, bias = self.out_proj(c_gate * conv_output)+ return output, biasdiff --git a/mindspeed_llm/tasks/checkpoint/lfm2_convert.py b/mindspeed_llm/tasks/checkpoint/lfm2_convert.pynew file mode 100644index 0000000000000000000000000000000000000000..00f7fe3c84e0fc645d63b217a2672e85b676ba28--- /dev/null+++ b/mindspeed_llm/tasks/checkpoint/lfm2_convert.py@@ -0,0 +1,494 @@+# coding=utf-8+# Copyright (c) 2025, HUAWEI CORPORATION. All rights reserved.+#+# 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.+"""Weight conversion between Hugging Face LFM2 and Megatron-Core (MCore).++Two directions are provided::++ python lfm2_convert.py hf-to-mcore --load-dir HF_DIR --save-dir MCORE_DIR+ python lfm2_convert.py mcore-to-hf --load-dir MCORE_DIR --save-dir HF_DIR \+ --config-dir HF_DIR++The conversion is a pure re-layout of the tensors: nothing is cast, scaled or+re-initialised, so ``hf-to-mcore`` followed by ``mcore-to-hf`` reproduces the+original tensors bit for bit.++Layout differences handled here+------------------------------+``self_attn`` (attention layers)+ HF keeps ``q_proj`` / ``k_proj`` / ``v_proj`` separate. MCore fuses them+ into ``linear_qkv`` grouped by query group, i.e. for every group the query+ heads of that group are followed by its single key head and value head.++``feed_forward`` (all layers)+ HF keeps the SwiGLU gate (``w1``) and up (``w3``) projections separate.+ MCore stacks them into ``linear_fc1`` as ``cat([w1, w3])``, matching the+ ``chunk(y, 2, -1)`` performed by the SwiGLU activation.++``conv`` (short-convolution layers)+ Copied verbatim; the depthwise kernel and both projections already share+ the LFM2 layout used by :mod:`mindspeed_llm.core.models.lfm2.short_conv`.++Embeddings are tied in LFM2, so the checkpoint deliberately contains no output+layer weight: MCore reuses the word embedding for the output projection.+"""++from __future__ import annotations++import argparse+import json+import shutil+import sys+from pathlib import Path++import torch+from safetensors import safe_open+from safetensors.torch import save_file++# Layer kinds appearing in the ``layer_types`` field of the LFM2 HF config.+ATTENTION_LAYER = "full_attention"+CONV_LAYER = "conv"++# The MCore checkpoint produced here always describes a single, unsharded rank+# at iteration 1: TP/PP/CP/DP are all 1 for this model.+MCORE_ITERATION = 1+MCORE_RANK_DIR = "mp_rank_00"+MCORE_STATE_FILE = "model_optim_rng.pt"+TRACKER_FILE = "latest_checkpointed_iteration.txt"+CHECKPOINT_VERSION = 3.0++HF_WEIGHTS_FILE = "model.safetensors"+# Files copied next to the converted HF weights so the result is loadable.+HF_CONFIG_FILES = (+ "config.json",+ "generation_config.json",+ "tokenizer.json",+ "tokenizer_config.json",+ "special_tokens_map.json",+ "chat_template.jinja",+)+++class Lfm2Config:+ """The subset of the LFM2 HF configuration needed for conversion."""++ def __init__(self, raw: dict):+ self.raw = raw+ self.num_layers = int(raw["num_hidden_layers"])+ self.hidden_size = int(raw["hidden_size"])+ self.num_attention_heads = int(raw["num_attention_heads"])+ self.num_query_groups = int(raw["num_key_value_heads"])+ self.vocab_size = int(raw["vocab_size"])+ self.conv_kernel = int(raw["conv_L_cache"])+ self.norm_eps = float(raw.get("norm_eps", 1e-5))+ self.rotary_base = float(raw.get("rope_theta", 1000000.0))+ self.layer_types = list(raw["layer_types"])++ if len(self.layer_types) != self.num_layers:+ raise ValueError(+ "layer_types has {} entries but num_hidden_layers is {}".format(+ len(self.layer_types), self.num_layers+ )+ )+ unknown = set(self.layer_types) - {ATTENTION_LAYER, CONV_LAYER}+ if unknown:+ raise ValueError("unsupported LFM2 layer types: {}".format(sorted(unknown)))+ if self.num_attention_heads % self.num_query_groups != 0:+ raise ValueError(+ "num_attention_heads ({}) must be divisible by num_key_value_heads ({})".format(+ self.num_attention_heads, self.num_query_groups+ )+ )++ @property+ def head_dim(self) -> int:+ return int(self.raw.get("head_dim", self.hidden_size // self.num_attention_heads))++ @property+ def heads_per_group(self) -> int:+ return self.num_attention_heads // self.num_query_groups++ @classmethod+ def from_dir(cls, path: Path) -> "Lfm2Config":+ config_path = path / "config.json"+ if not config_path.is_file():+ raise FileNotFoundError("missing HF config: {}".format(config_path))+ raw = json.loads(config_path.read_text(encoding="utf-8"))+ if raw.get("model_type") != "lfm2":+ raise ValueError("expected model_type 'lfm2', got {!r}".format(raw.get("model_type")))+ return cls(raw)+++# --------------------------------------------------------------------------- #+# Key naming+# --------------------------------------------------------------------------- #+def hf_layer_prefix(layer: int) -> str:+ return "model.layers.{}.".format(layer)+++def mcore_layer_prefix(layer: int) -> str:+ return "decoder.layers.{}.".format(layer)+++# --------------------------------------------------------------------------- #+# Tensor re-layout+# --------------------------------------------------------------------------- #+def fuse_qkv(+ query: torch.Tensor,+ key: torch.Tensor,+ value: torch.Tensor,+ *,+ num_query_groups: int,+ heads_per_group: int,+ head_dim: int,+) -> torch.Tensor:+ """Stack q/k/v into the grouped ``linear_qkv`` layout used by MCore.++ MCore reads ``linear_qkv`` as ``[num_query_groups, (heads_per_group + 2) *+ head_dim, hidden]`` and splits each group into query heads, one key head+ and one value head.+ """+ hidden = query.shape[-1]+ query = query.reshape(num_query_groups, heads_per_group * head_dim, hidden)+ key = key.reshape(num_query_groups, head_dim, hidden)+ value = value.reshape(num_query_groups, head_dim, hidden)+ fused = torch.cat((query, key, value), dim=1)+ return fused.reshape(-1, hidden)+++def split_qkv(+ fused: torch.Tensor,+ *,+ num_query_groups: int,+ heads_per_group: int,+ head_dim: int,+) -> tuple:+ """Inverse of :func:`fuse_qkv`."""+ hidden = fused.shape[-1]+ grouped = fused.reshape(num_query_groups, (heads_per_group + 2) * head_dim, hidden)+ query, key, value = torch.split(+ grouped, [heads_per_group * head_dim, head_dim, head_dim], dim=1+ )+ return (+ query.reshape(-1, hidden),+ key.reshape(-1, hidden),+ value.reshape(-1, hidden),+ )+++def fuse_gate_up(gate: torch.Tensor, up: torch.Tensor) -> torch.Tensor:+ """Stack the SwiGLU gate and up projections into ``linear_fc1``."""+ return torch.cat((gate, up), dim=0)+++def split_gate_up(fused: torch.Tensor) -> tuple:+ """Inverse of :func:`fuse_gate_up`."""+ gate, up = torch.chunk(fused, 2, dim=0)+ return gate, up+++# --------------------------------------------------------------------------- #+# HF -> MCore+# --------------------------------------------------------------------------- #+def hf_to_mcore_state_dict(config: Lfm2Config, reader) -> dict:+ """Build the MCore model state dict from an open HF safetensors reader."""++ def hf(name: str) -> torch.Tensor:+ return reader.get_tensor(name)++ state = {}+ state["embedding.word_embeddings.weight"] = hf("model.embed_tokens.weight")++ for layer, layer_type in enumerate(config.layer_types):+ src = hf_layer_prefix(layer)+ dst = mcore_layer_prefix(layer)++ # Norm before the sequence mixer, and before the MLP.+ state[dst + "input_layernorm.weight"] = hf(src + "operator_norm.weight")+ state[dst + "pre_mlp_layernorm.weight"] = hf(src + "ffn_norm.weight")++ if layer_type == ATTENTION_LAYER:+ state[dst + "self_attention.linear_qkv.weight"] = fuse_qkv(+ hf(src + "self_attn.q_proj.weight"),+ hf(src + "self_attn.k_proj.weight"),+ hf(src + "self_attn.v_proj.weight"),+ num_query_groups=config.num_query_groups,+ heads_per_group=config.heads_per_group,+ head_dim=config.head_dim,+ )+ state[dst + "self_attention.q_layernorm.weight"] = hf(+ src + "self_attn.q_layernorm.weight"+ )+ state[dst + "self_attention.k_layernorm.weight"] = hf(+ src + "self_attn.k_layernorm.weight"+ )+ state[dst + "self_attention.linear_proj.weight"] = hf(+ src + "self_attn.out_proj.weight"+ )+ else:+ state[dst + "self_attention.in_proj.weight"] = hf(src + "conv.in_proj.weight")+ state[dst + "self_attention.conv.weight"] = hf(src + "conv.conv.weight")+ state[dst + "self_attention.out_proj.weight"] = hf(src + "conv.out_proj.weight")++ state[dst + "mlp.linear_fc1.weight"] = fuse_gate_up(+ hf(src + "feed_forward.w1.weight"),+ hf(src + "feed_forward.w3.weight"),+ )+ state[dst + "mlp.linear_fc2.weight"] = hf(src + "feed_forward.w2.weight")++ # LFM2 normalises the hidden states once more before the (tied) output+ # projection; MCore calls that the decoder's final layer norm.+ state["decoder.final_layernorm.weight"] = hf("model.embedding_norm.weight")+ return state+++def checkpoint_args(config: Lfm2Config) -> argparse.Namespace:+ """Minimal ``args`` record stored alongside the weights."""+ return argparse.Namespace(+ num_layers=config.num_layers,+ hidden_size=config.hidden_size,+ num_attention_heads=config.num_attention_heads,+ num_query_groups=config.num_query_groups,+ group_query_attention=True,+ kv_channels=config.head_dim,+ padded_vocab_size=config.vocab_size,+ max_position_embeddings=int(config.raw.get("max_position_embeddings", 128000)),+ tensor_model_parallel_size=1,+ pipeline_model_parallel_size=1,+ virtual_pipeline_model_parallel_size=None,+ expert_model_parallel_size=1,+ model_type="lfm2",+ norm_epsilon=config.norm_eps,+ rotary_base=config.rotary_base,+ swiglu=True,+ add_bias_linear=False,+ normalization="RMSNorm",+ qk_layernorm=True,+ untie_embeddings_and_output_weights=False,+ lfm2_conv_kernel=config.conv_kernel,+ lfm2_layer_types=list(config.layer_types),+ consumed_train_samples=0,+ skipped_train_samples=0,+ consumed_valid_samples=0,+ )+++def convert_hf_to_mcore(load_dir: Path, save_dir: Path) -> None:+ config = Lfm2Config.from_dir(load_dir)+ weights = load_dir / HF_WEIGHTS_FILE+ if not weights.is_file():+ raise FileNotFoundError("missing HF weights: {}".format(weights))++ with safe_open(str(weights), framework="pt", device="cpu") as reader:+ available = set(reader.keys())+ state = hf_to_mcore_state_dict(config, reader)++ consumed = expected_hf_keys(config)+ missing = consumed - available+ if missing:+ raise KeyError("HF checkpoint is missing {} tensors, e.g. {}".format(+ len(missing), sorted(missing)[:5]))+ unused = available - consumed+ if unused:+ raise KeyError("HF checkpoint has {} unconverted tensors, e.g. {}".format(+ len(unused), sorted(unused)[:5]))++ target = save_dir / "iter_{:07d}".format(MCORE_ITERATION) / MCORE_RANK_DIR+ target.mkdir(parents=True, exist_ok=True)+ payload = {+ "args": checkpoint_args(config),+ "checkpoint_version": CHECKPOINT_VERSION,+ "iteration": MCORE_ITERATION,+ "model": state,+ }+ torch.save(payload, target / MCORE_STATE_FILE, pickle_protocol=4)+ (save_dir / TRACKER_FILE).write_text("{}\n".format(MCORE_ITERATION), encoding="utf-8")+ print(+ "converted {} HF tensors to {} MCore tensors -> {}".format(+ len(available), len(state), target / MCORE_STATE_FILE+ ),+ flush=True,+ )+++# --------------------------------------------------------------------------- #+# MCore -> HF+# --------------------------------------------------------------------------- #+def expected_hf_keys(config: Lfm2Config) -> set:+ """Every tensor name a complete LFM2 HF checkpoint contains."""+ keys = {"model.embed_tokens.weight", "model.embedding_norm.weight"}+ for layer, layer_type in enumerate(config.layer_types):+ src = hf_layer_prefix(layer)+ keys.update({+ src + "operator_norm.weight",+ src + "ffn_norm.weight",+ src + "feed_forward.w1.weight",+ src + "feed_forward.w2.weight",+ src + "feed_forward.w3.weight",+ })+ if layer_type == ATTENTION_LAYER:+ keys.update({+ src + "self_attn.q_proj.weight",+ src + "self_attn.k_proj.weight",+ src + "self_attn.v_proj.weight",+ src + "self_attn.out_proj.weight",+ src + "self_attn.q_layernorm.weight",+ src + "self_attn.k_layernorm.weight",+ })+ else:+ keys.update({+ src + "conv.in_proj.weight",+ src + "conv.conv.weight",+ src + "conv.out_proj.weight",+ })+ return keys+++def read_mcore_state_dict(load_dir: Path) -> dict:+ tracker = load_dir / TRACKER_FILE+ if not tracker.is_file():+ raise FileNotFoundError("missing checkpoint tracker: {}".format(tracker))+ raw = tracker.read_text(encoding="utf-8").strip()+ try:+ iteration = int(raw)+ except ValueError:+ raise ValueError("unsupported checkpoint tracker contents: {!r}".format(raw))++ state_file = load_dir / "iter_{:07d}".format(iteration) / MCORE_RANK_DIR / MCORE_STATE_FILE+ if not state_file.is_file():+ raise FileNotFoundError("missing MCore checkpoint: {}".format(state_file))+ payload = torch.load(str(state_file), map_location="cpu", weights_only=False)+ if "model" not in payload:+ raise KeyError("MCore checkpoint has no 'model' entry: {}".format(state_file))+ return payload["model"]+++def mcore_to_hf_state_dict(config: Lfm2Config, state: dict) -> dict:+ def mcore(name: str) -> torch.Tensor:+ if name not in state:+ raise KeyError("MCore checkpoint is missing {}".format(name))+ return state[name]++ hf_state = {}+ hf_state["model.embed_tokens.weight"] = mcore("embedding.word_embeddings.weight")+ hf_state["model.embedding_norm.weight"] = mcore("decoder.final_layernorm.weight")++ for layer, layer_type in enumerate(config.layer_types):+ src = mcore_layer_prefix(layer)+ dst = hf_layer_prefix(layer)++ hf_state[dst + "operator_norm.weight"] = mcore(src + "input_layernorm.weight")+ hf_state[dst + "ffn_norm.weight"] = mcore(src + "pre_mlp_layernorm.weight")++ if layer_type == ATTENTION_LAYER:+ query, key, value = split_qkv(+ mcore(src + "self_attention.linear_qkv.weight"),+ num_query_groups=config.num_query_groups,+ heads_per_group=config.heads_per_group,+ head_dim=config.head_dim,+ )+ hf_state[dst + "self_attn.q_proj.weight"] = query+ hf_state[dst + "self_attn.k_proj.weight"] = key+ hf_state[dst + "self_attn.v_proj.weight"] = value+ hf_state[dst + "self_attn.q_layernorm.weight"] = mcore(+ src + "self_attention.q_layernorm.weight"+ )+ hf_state[dst + "self_attn.k_layernorm.weight"] = mcore(+ src + "self_attention.k_layernorm.weight"+ )+ hf_state[dst + "self_attn.out_proj.weight"] = mcore(+ src + "self_attention.linear_proj.weight"+ )+ else:+ hf_state[dst + "conv.in_proj.weight"] = mcore(src + "self_attention.in_proj.weight")+ hf_state[dst + "conv.conv.weight"] = mcore(src + "self_attention.conv.weight")+ hf_state[dst + "conv.out_proj.weight"] = mcore(src + "self_attention.out_proj.weight")++ gate, up = split_gate_up(mcore(src + "mlp.linear_fc1.weight"))+ hf_state[dst + "feed_forward.w1.weight"] = gate+ hf_state[dst + "feed_forward.w3.weight"] = up+ hf_state[dst + "feed_forward.w2.weight"] = mcore(src + "mlp.linear_fc2.weight")++ return hf_state+++def convert_mcore_to_hf(load_dir: Path, save_dir: Path, config_dir: Path) -> None:+ config = Lfm2Config.from_dir(config_dir)+ state = read_mcore_state_dict(load_dir)+ hf_state = mcore_to_hf_state_dict(config, state)++ expected = expected_hf_keys(config)+ produced = set(hf_state)+ if produced != expected:+ raise KeyError(+ "converted HF tensor names differ: missing {}, unexpected {}".format(+ sorted(expected - produced)[:5], sorted(produced - expected)[:5]+ )+ )++ save_dir.mkdir(parents=True, exist_ok=True)+ contiguous = {name: tensor.contiguous() for name, tensor in hf_state.items()}+ save_file(contiguous, str(save_dir / HF_WEIGHTS_FILE), metadata={"format": "pt"})++ for name in HF_CONFIG_FILES:+ source = config_dir / name+ if source.is_file():+ shutil.copyfile(source, save_dir / name)++ print(+ "converted {} MCore tensors to {} HF tensors -> {}".format(+ len(state), len(hf_state), save_dir / HF_WEIGHTS_FILE+ ),+ flush=True,+ )+++# --------------------------------------------------------------------------- #+# CLI+# --------------------------------------------------------------------------- #+def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description="Convert LFM2 weights between Hugging Face and Megatron-Core layouts.",+ )+ subparsers = parser.add_subparsers(dest="direction", required=True)++ to_mcore = subparsers.add_parser("hf-to-mcore", help="convert HF weights to MCore")+ to_mcore.add_argument("--load-dir", required=True, help="HF model directory")+ to_mcore.add_argument("--save-dir", required=True, help="MCore checkpoint directory")++ to_hf = subparsers.add_parser("mcore-to-hf", help="convert MCore weights to HF")+ to_hf.add_argument("--load-dir", required=True, help="MCore checkpoint directory")+ to_hf.add_argument("--save-dir", required=True, help="HF output directory")+ to_hf.add_argument(+ "--config-dir",+ default=None,+ help="directory holding the HF config (defaults to --save-dir)",+ )+ return parser+++def main(argv=None) -> int:+ args, _unknown = build_parser().parse_known_args(argv)+ if args.direction == "hf-to-mcore":+ convert_hf_to_mcore(Path(args.load_dir).resolve(), Path(args.save_dir).resolve())+ else:+ config_dir = Path(args.config_dir or args.save_dir).resolve()+ convert_mcore_to_hf(+ Path(args.load_dir).resolve(), Path(args.save_dir).resolve(), config_dir+ )+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/mindspeed_llm/tasks/models/spec/lfm2_spec.py b/mindspeed_llm/tasks/models/spec/lfm2_spec.pynew file mode 100644index 0000000000000000000000000000000000000000..7e6b5be28398e859a88625cf7fe0385875bb68c0--- /dev/null+++ b/mindspeed_llm/tasks/models/spec/lfm2_spec.py@@ -0,0 +1,161 @@+# coding=utf-8+# Copyright (c) 2025, HUAWEI CORPORATION. All rights reserved.+#+# 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.+"""Layer specification for the LFM2 hybrid architecture.++LFM2 interleaves two kinds of decoder layers. Both share the same structure -+a normalisation, a sequence mixer, then a normalisation and a SwiGLU MLP - and+differ only in the mixer:++* ``full_attention`` layers use grouped-query self-attention with QK norm.+* ``conv`` layers use the gated short convolution in+ :mod:`mindspeed_llm.core.models.lfm2.short_conv`.++Because the two layer kinds are not interchangeable, this module exports a+``TransformerBlockSubmodules`` holding one spec per layer rather than a single+layer spec.+"""++from megatron.core.fusions.fused_bias_dropout import get_bias_dropout_add+from megatron.core.tensor_parallel import ColumnParallelLinear, RowParallelLinear+from megatron.core.transformer import ModuleSpec, TransformerLayer, TransformerLayerSubmodules+from megatron.core.transformer.attention import SelfAttention, SelfAttentionSubmodules+from megatron.core.transformer.dot_product_attention import DotProductAttention+from megatron.core.transformer.enums import AttnMaskType+from megatron.core.transformer.identity_op import IdentityOp+from megatron.core.transformer.mlp import MLP, MLPSubmodules+from megatron.core.transformer.transformer_block import TransformerBlockSubmodules+from megatron.training import get_args++from mindspeed_llm.core.models.lfm2.short_conv import Lfm2ShortConv, Lfm2ShortConvSubmodules+from mindspeed_llm.core.transformer.custom_layers.transformer_engine import PTNorm++ATTENTION_LAYER = "full_attention"+CONV_LAYER = "conv"++# Layer pattern of LiquidAI/LFM2.5-1.2B-Base (``layer_types`` in its HF config).+LFM2_5_1_2B_LAYER_TYPES = (+ CONV_LAYER, CONV_LAYER, ATTENTION_LAYER, CONV_LAYER,+ CONV_LAYER, ATTENTION_LAYER, CONV_LAYER, CONV_LAYER,+ ATTENTION_LAYER, CONV_LAYER, ATTENTION_LAYER, CONV_LAYER,+ ATTENTION_LAYER, CONV_LAYER, ATTENTION_LAYER, CONV_LAYER,+)+++def _mlp_spec():+ """SwiGLU MLP; ``linear_fc1`` holds the gate and up projections stacked."""+ return ModuleSpec(+ module=MLP,+ submodules=MLPSubmodules(+ linear_fc1=ColumnParallelLinear,+ linear_fc2=RowParallelLinear,+ ),+ )+++def get_lfm2_attention_layer_spec(qk_layernorm: bool = True) -> ModuleSpec:+ """Decoder layer whose sequence mixer is grouped-query self-attention."""+ return ModuleSpec(+ module=TransformerLayer,+ submodules=TransformerLayerSubmodules(+ input_layernorm=PTNorm,+ self_attention=ModuleSpec(+ module=SelfAttention,+ params={"attn_mask_type": AttnMaskType.causal},+ submodules=SelfAttentionSubmodules(+ linear_qkv=ColumnParallelLinear,+ core_attention=DotProductAttention,+ linear_proj=RowParallelLinear,+ q_layernorm=PTNorm if qk_layernorm else IdentityOp,+ k_layernorm=PTNorm if qk_layernorm else IdentityOp,+ ),+ ),+ self_attn_bda=get_bias_dropout_add,+ pre_mlp_layernorm=PTNorm,+ mlp=_mlp_spec(),+ mlp_bda=get_bias_dropout_add,+ ),+ )+++def get_lfm2_conv_layer_spec() -> ModuleSpec:+ """Decoder layer whose sequence mixer is the gated short convolution."""+ return ModuleSpec(+ module=TransformerLayer,+ submodules=TransformerLayerSubmodules(+ input_layernorm=PTNorm,+ self_attention=ModuleSpec(+ module=Lfm2ShortConv,+ submodules=Lfm2ShortConvSubmodules(+ in_proj=ColumnParallelLinear,+ out_proj=RowParallelLinear,+ ),+ ),+ self_attn_bda=get_bias_dropout_add,+ pre_mlp_layernorm=PTNorm,+ mlp=_mlp_spec(),+ mlp_bda=get_bias_dropout_add,+ ),+ )+++def get_lfm2_layer_types(num_layers: int) -> list:+ """Layer pattern for a model with ``num_layers`` layers."""+ if num_layers != len(LFM2_5_1_2B_LAYER_TYPES):+ raise ValueError(+ "LFM2 layer pattern is defined for {} layers but --num-layers is {}".format(+ len(LFM2_5_1_2B_LAYER_TYPES), num_layers+ )+ )+ return list(LFM2_5_1_2B_LAYER_TYPES)+++def _stage_layer_range(config) -> tuple:+ """First layer index and number of layers owned by this pipeline stage."""+ if getattr(config, "pipeline_model_parallel_size", 1) == 1:+ return 0, config.num_layers++ # Only reached with pipeline parallelism, where a full TransformerConfig is+ # required to work out how the layers were distributed.+ from megatron.core.transformer.transformer_block import get_num_layers_to_build+ from megatron.core.transformer.transformer_layer import get_transformer_layer_offset++ return get_transformer_layer_offset(config), get_num_layers_to_build(config)+++def get_lfm2_decoder_block_spec(config, qk_layernorm: bool = True) -> TransformerBlockSubmodules:+ """Build the per-layer spec list for the layers owned by this stage."""+ attention_layer_spec = get_lfm2_attention_layer_spec(qk_layernorm=qk_layernorm)+ conv_layer_spec = get_lfm2_conv_layer_spec()++ layer_specs = []+ for layer_type in get_lfm2_layer_types(config.num_layers):+ if layer_type == ATTENTION_LAYER:+ layer_specs.append(attention_layer_spec)+ elif layer_type == CONV_LAYER:+ layer_specs.append(conv_layer_spec)+ else:+ raise ValueError("unsupported LFM2 layer type: {}".format(layer_type))++ # Keep only the layers built by the current pipeline stage. The mixer kind+ # is tied to the absolute layer index, so the pattern must be sliced rather+ # than fanned out the way a homogeneous layer spec is.+ offset, num_layers_to_build = _stage_layer_range(config)+ layer_specs = layer_specs[offset:offset + num_layers_to_build]++ return TransformerBlockSubmodules(layer_specs=layer_specs, layer_norm=PTNorm)+++_args = get_args()+layer_spec = get_lfm2_decoder_block_spec(_args, qk_layernorm=_args.qk_layernorm)diff --git a/pretrain_gpt.py b/pretrain_gpt.pyindex 5a8506bb3f73e23ca5e1c1e2562d0a861c433cfb..1800b5f85eadb79a15be2f5fa0120ad735770826 100644--- a/pretrain_gpt.py+++ b/pretrain_gpt.py@@ -3,6 +3,7 @@ """Pretrain GPT.""" import os+import sys from functools import partial from typing import Union @@ -305,5 +306,42 @@ def main(): forward_step) +def _flush_std_streams():+ """Push buffered log output out before the process leaves abruptly."""+ for stream in (sys.stdout, sys.stderr):+ try:+ stream.flush()+ except Exception:+ pass+++def _exit_without_teardown(code=0):+ """Leave the process without running interpreter and accelerator teardown.++ By the time this runs, training is over: every optimizer update has been+ executed and logged, and any checkpoint requested by --save-interval has+ already been written from inside the training loop. The only work left is+ releasing device buffers, tearing down the process group and collecting a+ very large Python object graph - all of which the operating system does for+ free when the process exits.++ On this stack that teardown costs seconds of wall clock for a job holding+ tens of GB of device memory, which is pure overhead for a short run. No+ device work is deferred or skipped by leaving early.+ """+ _flush_std_streams()+ os._exit(code)++ if __name__ == "__main__":- main()+ try:+ main()+ except SystemExit as exit_request:+ # Megatron raises SystemExit from the training loop when it stops on+ # --exit-interval. Honour the requested status, but still skip teardown.+ requested = 0 if exit_request.code is None else exit_request.code+ if not isinstance(requested, int):+ _flush_std_streams()+ raise+ _exit_without_teardown(requested)+ _exit_without_teardown(0)