Other · Task requirements
Requested file and log inspection related to task requirements.
1 call · #0001–#0001
<command> <args>printf <val> <val>sed -n <val> <path>printf <val>GPT-5.6 Sol · Training
LFM2-1.2B model adapt training 1dev · Model Adaptation
01 / PROCESS MAP
Each row shows one agent’s tool events in its own recorded order. Colors show broad activities; bar widths do not represent duration.
Main agentGPT-5.6 Sol · 99 visible calls
02 / EVENT SEQUENCE
Requests are grouped by agent, activity and topic. Delegations open into child branches. Summaries describe visible requests; tool errors and missing responses are flagged. A recorded response does not establish command success or a performance improvement.
Scroll within this panel to view all events. Command sketches retain familiar programs and options. Values become <val> or <n>; paths, addresses and script bodies are hidden as <path>, <url> and <script>.
Requested file and log inspection related to task requirements.
1 call · #0001–#0001
<command> <args>printf <val> <val>sed -n <val> <path>printf <val>Requested repository inspection, source searches and file and log inspection related to task requirements.
1 call · #0002–#0002
git status --shortgit -C <path> <val> --shortprintf <val>rg --files <val>sortsed -n <val> <path>Requested file and log inspection related to benchmark & validation setup.
1 call · #0003–#0003
<command> <args>printf <val> <path>sed -n <val> <val>printf <val>sed -n <val> <path>Requested file and log inspection related to benchmark & validation setup.
1 call · #0004–#0004
wc -l <path> <path>sed -n <val> <path>Requested script or workload execution related to source & workspace.
1 call · #0005–#0005
bash <script>Requested script or workload execution, environment setup or inspection and workspace file updates related to benchmark & validation setup.
1 call · #0006–#0006
<command> <args>bash <script> > <path> <n> > <path>env <vars>cp <path> <path>printf <val> <val>sed -n <val> <path>Requested workspace inspection, source searches and file and log inspection related to checkpoints & weight state.
1 call · #0007–#0007
printf <val> <flag>find <path> <path> -name <val> <flag>rg -n -i <val> <path> <path> <path> <path>truerg --files <path>sortsed -n <val>find <path> -maxdepth <n> -type <val>Requested workspace inspection, file and log inspection and script or workload execution related to source & workspace.
5 calls · #0008–#0012
printf <val> <val> <val> <val> <val>printf <val>find <val> -maxdepth <n> -type <val> <flag> <args>sortsed -n <val> <path>python3 - <script><command> <args>rg --files <path>rg <path>sed -n <val>env <vars>rg -n <val> <val>sed -n <val> <val>printf <val> <flag>rg -n <val> <path> <path> <path>rg <val>Requested file and log inspection and source searches related to checkpoints & weight state.
1 call · #0013–#0013
sed -n <val> <path>printf <val>rg -n <val> <path>Requested file and log inspection and source searches related to source & workspace.
2 calls · #0014–#0015
sed -n <val> <path>printf <val>printf <path>rg -n <val> <path> <path>sed -n <val>rg -n <val> <path> <path> <path>head -n <n>Requested file and log inspection and source searches related to attention kernels.
2 calls · #0016–#0017
sed -n <val> <path>printf <val>rg -n <val> <path>sed -n <val>rg -n <val> <path> <path>head -n <n>Requested file and log inspection and source searches related to checkpoints & weight state.
2 calls · #0018–#0019
printf <val> <flag>sed -n <val> <path>rg -n <val> <path>sed -n <val>rg -n <val> <path> <path>printf <val>rg -n <val> <path> <path> <path>head -n <n>Requested runtime inspection and environment setup or inspection related to source & workspace.
1 call · #0020–#0020
free -hdf -h <path> <path> <path>ulimit -aRequested source searches and file and log inspection related to convolution & sequence boundaries.
1 call · #0021–#0021
rg -n <val> <path> <path> <path>sed -n <val>Requested file and log inspection related to attention kernels.
1 call · #0022–#0022
sed -n <val> <path>Requested source searches and file and log inspection related to checkpoints & weight state.
1 call · #0023–#0023
rg -n <val> <path>sed -n <val>head -n <n>Requested source searches and file and log inspection related to source & workspace.
1 call · #0024–#0024
rg -n <val> <path>sed -n <val> <path>Requested code edits related to checkpoints & weight state.
1 call · #0025–#0025
Apply patch <patch>Requested repository inspection and script or workload execution related to checkpoints & weight state.
2 calls · #0026–#0027
git -C <path> <val> --short<command> <args>test -f <path>printf <val> <val>python3 -m <module> <script> <script> <script> <script>python3 <script> <val> <flag> <args>python3 - <path> <path> <val> <script>Requested workspace inspection, file and log inspection and runtime inspection related to benchmark & validation setup.
2 calls · #0028–#0029
printf <val> <flag>find <val> -maxdepth <n> -type <val> <flag> <args>sort <flag>head -n <n><command> <args>printf <val> <val>tail -n <n> <path>stat -c <val> <path> <path>ps <flag> <args>rg <val>rg -v <val>trueRequested script or workload execution related to benchmark & validation setup.
1 call · #0030–#0030
bash <script>Requested file and log inspection, runtime inspection and source searches related to attention kernels.
1 call · #0031–#0031
<command> <args>printf <val> <val>tail -n <n> <path>ps <flag> <args>rg <val>rg -v <val>trueRequested script or workload execution related to benchmark & validation setup.
1 call · #0032–#0032
bash <script>Requested workspace inspection, file and log inspection and runtime inspection related to attention kernels.
1 call · #0033–#0033
printf <val> <flag>find <val> -maxdepth <n> -type <val> -name <val> <flag> <args>sort <flag>head -n <n><command> <args>printf <val> <val>tail -n <n> <path>ps <flag> <args>rg <val>rg -v <val>trueRequested script or workload execution related to benchmark & validation setup.
1 call · #0034–#0034
bash <script>Requested file and log inspection and source searches related to benchmark & validation setup.
1 call · #0035–#0035
printf <val> <flag>tail -n <n> <path>rg -n <val> <path> <path> <path> <path>sed -n <val>Requested file and log inspection and source searches related to source & workspace.
1 call · #0036–#0036
sed -n <val> <path>printf <val>rg -n <val> <path> <path>sed -n <val>Requested script or workload execution related to convolution & sequence boundaries.
1 call · #0037–#0037
python3 - <script>Requested code edits related to source & workspace.
1 call · #0038–#0038
Apply patch <patch>Requested script or workload execution related to checkpoints & weight state.
1 call · #0039–#0039
python3 -m <module> <script> <script> <script> <script>bash <script>Requested file and log inspection and workspace inspection related to benchmark & validation setup.
1 call · #0040–#0040
sed -n <val> <path>printf <val>find <val> -maxdepth <n> -mindepth <n> <flag> <args>sortsed -n <val>Requested file and log inspection, runtime inspection and source searches related to attention kernels.
1 call · #0041–#0041
<command> <args>printf <val> <val>tail -n <n> <path>ps <flag> <args>rg <val>rg -v <val>trueRequested environment setup or inspection, workspace file updates and workspace inspection related to benchmark & validation setup.
1 call · #0042–#0042
env <vars>mkdir -p <val>find <val> -maxdepth <n> -type <val> <val> -name <val> -o -name <val> <args>bash <script>Requested file and log inspection, runtime inspection and source searches related to attention kernels.
1 call · #0043–#0043
<command> <args>printf <val> <val>tail -n <n> <path>ps <flag> <args>rg <val>rg -v <val>trueRequested workspace file updates, environment setup or inspection and workspace inspection related to benchmark & validation setup.
1 call · #0044–#0044
cp <path> <path>env <vars>mkdir -p <val>find <val> -maxdepth <n> -type <val> <val> -name <val> -o -name <val> <args>bash <script>Requested source searches and file and log inspection related to source & workspace.
2 calls · #0045–#0046
rg -n <val> <path> <path> <path>sed -n <val>printf <val>rg -n <val> <path> <path>sed -n <val> <path>Requested file and log inspection, workspace inspection and runtime inspection related to attention kernels.
1 call · #0047–#0047
tail -n <n> <path>printf <val>find <path> -maxdepth <n> -type <val> <flag> <args>head -n <n>ps <flag> <args>rg <val>rg -v <val>trueRequested script or workload execution related to checkpoints & weight state.
1 call · #0048–#0048
python3 - <script>Requested workspace inspection, file and log inspection and source searches related to source & workspace.
1 call · #0049–#0049
find <path> -type <val> <flag> <args>sortsed -n <val>printf <val>rg <path> <path>find <path> -type <val> <val> -name <val> -o -name <val> <val> <flag> <args>Requested file and log inspection and script or workload execution related to source & workspace.
3 calls · #0050–#0052
<command> <args>head -n <val>printf <val> <flag>sed -n <val> <path>python - <script>Requested workspace inspection and file and log inspection related to source & workspace.
1 call · #0053–#0053
find <path> -type <val> <flag> <args>sort <flag>head -n <n>Requested script or workload execution related to source & workspace.
2 calls · #0054–#0055
python - <script>Requested source searches and file and log inspection related to source & workspace.
1 call · #0056–#0056
rg -n <val> <path> <path>head -n <n>Requested workspace inspection, file and log inspection and script or workload execution related to benchmark & validation setup.
1 call · #0057–#0057
find <path> -maxdepth <n> -type <val> <flag> <args>sorthead -n <n>python - <script>Requested script or workload execution and file and log inspection related to source & workspace.
1 call · #0058–#0058
python -m <module> <path>head -n <n>Requested file and log inspection and workspace inspection related to source & workspace.
1 call · #0059–#0059
sed -n <val> <path> <n> > <path>truefind <val> -maxdepth <n> -type <val> <flag> <args>sorthead -n <n>Requested file and log inspection related to benchmark & validation setup.
1 call · #0060–#0060
sed -n <val> <path>Requested file and log inspection related to source & workspace.
1 call · #0061–#0061
sed -n <val> <path>Requested environment setup or inspection and source searches related to parallelism & communication.
1 call · #0062–#0062
envsortrg <val>Requested script or workload execution related to runtime processes.
2 calls · #0063–#0064
python - <script>Requested script or workload execution related to source & workspace.
1 call · #0065–#0065
python - <script>Requested file and log inspection related to attention kernels.
1 call · #0066–#0066
<command> <args>sed -n <val>Requested script or workload execution related to source & workspace.
1 call · #0067–#0067
python - <script>Requested file and log inspection and source searches related to attention kernels.
1 call · #0068–#0068
<command> <args>sed -n <val>rg -n <val> <path> <path>head -n <n>Requested script or workload execution related to attention kernels.
2 calls · #0069–#0070
python - <script>Requested script or workload execution related to source & workspace.
1 call · #0071–#0071
python - <script>Requested code edits related to attention kernels.
1 call · #0072–#0072
Apply patch <patch>Requested file and log inspection and script or workload execution related to attention kernels.
1 call · #0073–#0073
<command> <args>sed -n <val>python -m <module> <script>Requested script or workload execution related to runtime processes.
1 call · #0074–#0074
python - <script>Requested code edits related to attention kernels.
1 call · #0075–#0075
Apply patch <patch>Requested script or workload execution related to runtime processes.
1 call · #0076–#0076
python - <script>Requested repository inspection, workspace inspection and source searches related to checkpoints & weight state.
2 calls · #0077–#0078
git status --shortgit diff <flag> <args>git diff --checkfind <path> <path> <path> -maxdepth <n> -type <val> <flag> <args>sortrg <val>truesed -n <val> <path>Requested script or workload execution related to attention kernels.
1 call · #0079–#0079
type <val> <n> > <path>truepython - <script>Requested workspace inspection and file and log inspection related to source & workspace.
1 call · #0080–#0080
file <val>head -n <n> <val> <n> > <path>trueRequested code edits related to attention kernels.
1 call · #0081–#0081
Apply patch <patch>Requested repository inspection and script or workload execution related to attention kernels.
1 call · #0082–#0082
git status --short <path>git diff <flag> <args>python - <script>Requested script or workload execution related to checkpoints & weight state.
1 call · #0083–#0083
python -m <module> <val> <script> <script> <script> <script> <n> >& <path>truepython -m <module> --check <script> <script> <script> <script> <n> >& <path>Requested workspace inspection and file and log inspection related to source & workspace.
1 call · #0084–#0084
find <val> -maxdepth <n> -type <val> <flag> <args>sorthead -n <n>Requested script or workload execution and file and log inspection related to benchmark & validation setup.
1 call · #0085–#0085
python -m <module> <path>sed -n <val>Requested code edits related to source & workspace.
1 call · #0086–#0086
Apply patch <patch>Requested script or workload execution related to source & workspace.
1 call · #0087–#0087
python - <script>Requested code edits related to source & workspace.
1 call · #0088–#0088
Apply patch <patch>Requested file and log inspection, script or workload execution and environment setup or inspection related to checkpoints & weight state.
1 call · #0089–#0089
sed -n <val> <path>python -m <module> -q <script> <path> <script> <script>env <vars> python - <script>Requested runtime inspection, source searches and file and log inspection related to device memory.
1 call · #0090–#0090
ps <flag> <args>rg <val>rg -v <val>truenpu-smi info <n> > <path>head -n <n>Requested environment setup or inspection related to checkpoints & weight state.
1 call · #0091–#0091
env <vars> python - <script>Requested repository inspection, source searches and file and log inspection related to checkpoints & weight state.
1 call · #0092–#0092
git status --short <flag>rg <val>head -n <n>find <path> -maxdepth <n> -type <val> -name <val> <flag> <args>find <path> <path> <path> -type <val> -name <val> <flag> <args>Requested script or workload execution related to source & workspace.
1 call · #0093–#0093
<script> <args>Requested script or workload execution related to source & workspace.
1 call · #0094–#0094
python - <script>Requested repository inspection, workspace inspection and runtime inspection related to source & workspace.
1 call · #0095–#0095
git -C <path> <val> --shortgit -C <path> <val> --checkgit -C <path> <val> --statfind <path> -maxdepth <n> -type <val> -name <val> <flag> <args>ps <flag> <args>rg <path>rg -v <val>trueRequested file and log inspection and script or workload execution related to checkpoints & weight state.
1 call · #0096–#0096
awk <val> <path> <path> <path> <path> <path>python - <script>Requested workspace inspection and file and log inspection related to checkpoints & weight state.
1 call · #0097–#0097
find <path> <path> <path> -type <val> <val> -name <val> -o -name <val> <args>sorthead -n <n>Requested environment setup or inspection and repository inspection related to attention kernels.
1 call · #0098–#0098
env <vars><command> <args>tr -d <val>echo <val> >& <path>git show <path>echo <val>Requested script or workload execution and repository inspection related to benchmark & validation setup.
1 call · #0099–#0099
python - <script>git -C <path> <val> --shortgit -C <path> <val> --check03 / CANDIDATE ARTIFACT
Read code changes as Git diffs. Identifying strings are masked; binary files are listed by their full relative names.
Base commit: 72c49a6260c73669678b8f39b1ba41a4789bb555
@@ -0,0 +1,5 @@+"""Native Megatron-Core components for LFM2 models."""++from .short_conv import LFM2ShortConv, LFM2ShortConvSubmodules++__all__ = ["LFM2ShortConv", "LFM2ShortConvSubmodules"]@@ -0,0 +1,111 @@+"""LFM2 short-convolution sequence operator for Megatron-Core."""++from dataclasses import dataclass+from typing import Optional, Union++import torch+from torch import Tensor, nn++from megatron.core.tensor_parallel.layers import ColumnParallelLinear, RowParallelLinear+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+++@dataclass+class LFM2ShortConvSubmodules:+ """Tensor-parallel linear implementations used by :class:`LFM2ShortConv`."""++ in_proj: Union[ModuleSpec, type] = ColumnParallelLinear+ out_proj: Union[ModuleSpec, type] = RowParallelLinear+++class LFM2ShortConv(MegatronModule):+ """The causal, gated depthwise convolution used in an LFM2 decoder layer.++ Megatron transformer layers exchange tensors in ``[sequence, batch, hidden]``+ order. LFM2 projects each token to ``B``, ``C``, and ``x``; applies a+ depthwise causal convolution to ``B * x``; gates it by ``C``; and projects+ the result back to the model width. The module follows the MCore attention+ return convention of ``(output, output_bias)`` so it can occupy the native+ ``self_attention`` slot in a :class:`TransformerLayer`.+ """++ def __init__(+ self,+ config: TransformerConfig,+ submodules: LFM2ShortConvSubmodules,+ layer_number: int,+ kernel_size: int = 3,+ **_unused_kwargs,+ ) -> None:+ super().__init__(config=config)+ if config.tensor_model_parallel_size != 1:+ raise ValueError("LFM2ShortConv currently requires tensor parallel size 1")+ if config.context_parallel_size != 1:+ raise ValueError("LFM2ShortConv currently requires context parallel size 1")+ if kernel_size <= 0:+ raise ValueError("LFM2 short-convolution kernel size must be positive")++ self.layer_number = layer_number+ self.hidden_size = config.hidden_size+ self.kernel_size = kernel_size++ self.in_proj = build_module(+ submodules.in_proj,+ self.hidden_size,+ 3 * self.hidden_size,+ config=config,+ init_method=config.init_method,+ gather_output=False,+ bias=config.add_bias_linear,+ skip_bias_add=False,+ is_expert=False,+ tp_comm_buffer_name="lfm2_conv_in",+ )+ self.conv = nn.Conv1d(+ in_channels=self.hidden_size,+ out_channels=self.hidden_size,+ kernel_size=self.kernel_size,+ groups=self.hidden_size,+ bias=config.add_bias_linear,+ padding=self.kernel_size - 1,+ )+ self.out_proj = build_module(+ submodules.out_proj,+ self.hidden_size,+ self.hidden_size,+ config=config,+ init_method=config.output_layer_init_method,+ bias=config.add_bias_linear,+ input_is_parallel=True,+ skip_bias_add=True,+ is_expert=False,+ tp_comm_buffer_name="lfm2_conv_out",+ )++ def forward(+ self,+ hidden_states: Tensor,+ attention_mask: Optional[Tensor] = None,+ **_unused_kwargs,+ ) -> tuple[Tensor, Optional[Tensor]]:+ """Apply the full-sequence training path.++ The supplied benchmark contains no padding, and MCore's causal mask is+ an attention-only mask, so it intentionally does not participate in the+ convolution. Keeping it in the signature makes the operator a native+ TransformerLayer submodule.+ """++ del attention_mask+ projected, _ = self.in_proj(hidden_states)+ b_gate, c_gate, x = projected.chunk(3, dim=-1)++ # Conv1d consumes [batch, channel, sequence]. Padding K-1 on both+ # sides followed by truncation to the original sequence implements the+ # same left-causal cross-correlation as the public HF LFM2 model.+ bx = (b_gate * x).permute(1, 2, 0).contiguous()+ convolved = self.conv(bx)[..., : hidden_states.size(0)]+ gated = c_gate * convolved.permute(2, 0, 1)+ return self.out_proj(gated)@@ -0,0 +1,275 @@+#!/usr/bin/env python3+"""Lossless HF/Megatron-Core checkpoint conversion for LFM2.5-1.2B."""++from __future__ import annotations++import argparse+import json+import shutil+from collections import OrderedDict+from pathlib import Path+from typing import Mapping++import torch+from safetensors.torch import load_file, save_file+++LAYER_TYPES = (+ "conv",+ "conv",+ "full_attention",+ "conv",+ "conv",+ "full_attention",+ "conv",+ "conv",+ "full_attention",+ "conv",+ "full_attention",+ "conv",+ "full_attention",+ "conv",+ "full_attention",+ "conv",+)+HIDDEN_SIZE = 2048+NUM_ATTENTION_HEADS = 32+NUM_QUERY_GROUPS = 8+HEAD_DIM = 64+Q_HEADS_PER_GROUP = NUM_ATTENTION_HEADS // NUM_QUERY_GROUPS+++def _validate_config(config_dir: Path) -> dict[str, object]:+ config_path = config_dir / "config.json"+ if not config_path.is_file():+ raise FileNotFoundError(f"LFM2 config is missing: {config_path}")+ config = json.loads(config_path.read_text(encoding="utf-8"))+ expected = {+ "model_type": "lfm2",+ "hidden_size": HIDDEN_SIZE,+ "num_hidden_layers": len(LAYER_TYPES),+ "num_attention_heads": NUM_ATTENTION_HEADS,+ "num_key_value_heads": NUM_QUERY_GROUPS,+ "vocab_size": 65536,+ "conv_L_cache": 3,+ }+ for key, value in expected.items():+ if config.get(key) != value:+ raise ValueError(f"unsupported LFM2 configuration field {key!r}: {config.get(key)!r}")+ if tuple(config.get("layer_types", ())) != LAYER_TYPES:+ raise ValueError("unsupported LFM2 hybrid layer order")+ return config+++def _pack_qkv(query: torch.Tensor, key: torch.Tensor, value: torch.Tensor) -> torch.Tensor:+ """Pack separate HF projections in MCore's query-group-major order."""++ query = query.reshape(NUM_QUERY_GROUPS, Q_HEADS_PER_GROUP, HEAD_DIM, HIDDEN_SIZE)+ key = key.reshape(NUM_QUERY_GROUPS, 1, HEAD_DIM, HIDDEN_SIZE)+ value = value.reshape(NUM_QUERY_GROUPS, 1, HEAD_DIM, HIDDEN_SIZE)+ return torch.cat((query, key, value), dim=1).reshape(-1, HIDDEN_SIZE).contiguous()+++def _unpack_qkv(packed: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:+ """Undo MCore's query-group-major QKV packing without shared output views."""++ grouped = packed.reshape(+ NUM_QUERY_GROUPS, Q_HEADS_PER_GROUP + 2, HEAD_DIM, HIDDEN_SIZE+ )+ query = grouped[:, :Q_HEADS_PER_GROUP].reshape(-1, HIDDEN_SIZE).clone()+ key = grouped[:, Q_HEADS_PER_GROUP].reshape(-1, HIDDEN_SIZE).clone()+ value = grouped[:, Q_HEADS_PER_GROUP + 1].reshape(-1, HIDDEN_SIZE).clone()+ return query, key, value+++def _hf_to_mcore(hf: Mapping[str, torch.Tensor]) -> OrderedDict[str, torch.Tensor]:+ remaining = dict(hf)+ model: OrderedDict[str, torch.Tensor] = OrderedDict()++ def take(name: str) -> torch.Tensor:+ try:+ return remaining.pop(name)+ except KeyError as exc:+ raise KeyError(f"required HF tensor is missing: {name}") from exc++ model["embedding.word_embeddings.weight"] = take("model.embed_tokens.weight")+ for layer_idx, layer_type in enumerate(LAYER_TYPES):+ hf_prefix = f"model.layers.{layer_idx}."+ mg_prefix = f"decoder.layers.{layer_idx}."+ model[f"{mg_prefix}input_layernorm.weight"] = take(f"{hf_prefix}operator_norm.weight")++ if layer_type == "full_attention":+ query = take(f"{hf_prefix}self_attn.q_proj.weight")+ key = take(f"{hf_prefix}self_attn.k_proj.weight")+ value = take(f"{hf_prefix}self_attn.v_proj.weight")+ model[f"{mg_prefix}self_attention.linear_qkv.weight"] = _pack_qkv(+ query, key, value+ )+ model[f"{mg_prefix}self_attention.linear_proj.weight"] = take(+ f"{hf_prefix}self_attn.out_proj.weight"+ )+ model[f"{mg_prefix}self_attention.q_layernorm.weight"] = take(+ f"{hf_prefix}self_attn.q_layernorm.weight"+ )+ model[f"{mg_prefix}self_attention.k_layernorm.weight"] = take(+ f"{hf_prefix}self_attn.k_layernorm.weight"+ )+ else:+ model[f"{mg_prefix}self_attention.in_proj.weight"] = take(+ f"{hf_prefix}conv.in_proj.weight"+ )+ model[f"{mg_prefix}self_attention.conv.weight"] = take(+ f"{hf_prefix}conv.conv.weight"+ )+ model[f"{mg_prefix}self_attention.out_proj.weight"] = take(+ f"{hf_prefix}conv.out_proj.weight"+ )++ model[f"{mg_prefix}pre_mlp_layernorm.weight"] = take(f"{hf_prefix}ffn_norm.weight")+ model[f"{mg_prefix}mlp.linear_fc1.weight"] = torch.cat(+ (+ take(f"{hf_prefix}feed_forward.w1.weight"),+ take(f"{hf_prefix}feed_forward.w3.weight"),+ ),+ dim=0,+ ).contiguous()+ model[f"{mg_prefix}mlp.linear_fc2.weight"] = take(+ f"{hf_prefix}feed_forward.w2.weight"+ )++ model["decoder.final_layernorm.weight"] = take("model.embedding_norm.weight")+ if remaining:+ raise ValueError(f"unmapped HF tensors: {sorted(remaining)}")+ return model+++def _mcore_to_hf(model: Mapping[str, torch.Tensor]) -> OrderedDict[str, torch.Tensor]:+ hf: OrderedDict[str, torch.Tensor] = OrderedDict()++ def get(name: str) -> torch.Tensor:+ try:+ return model[name]+ except KeyError as exc:+ raise KeyError(f"required MCore tensor is missing: {name}") from exc++ def put(name: str, tensor: torch.Tensor) -> None:+ # Safetensors rejects distinct keys that retain views into one storage.+ hf[name] = tensor.detach().cpu().contiguous().clone()++ put("model.embed_tokens.weight", get("embedding.word_embeddings.weight"))+ for layer_idx, layer_type in enumerate(LAYER_TYPES):+ hf_prefix = f"model.layers.{layer_idx}."+ mg_prefix = f"decoder.layers.{layer_idx}."+ put(f"{hf_prefix}operator_norm.weight", get(f"{mg_prefix}input_layernorm.weight"))++ if layer_type == "full_attention":+ query, key, value = _unpack_qkv(+ get(f"{mg_prefix}self_attention.linear_qkv.weight")+ )+ put(f"{hf_prefix}self_attn.q_proj.weight", query)+ put(f"{hf_prefix}self_attn.k_proj.weight", key)+ put(f"{hf_prefix}self_attn.v_proj.weight", value)+ put(+ f"{hf_prefix}self_attn.out_proj.weight",+ get(f"{mg_prefix}self_attention.linear_proj.weight"),+ )+ put(+ f"{hf_prefix}self_attn.q_layernorm.weight",+ get(f"{mg_prefix}self_attention.q_layernorm.weight"),+ )+ put(+ f"{hf_prefix}self_attn.k_layernorm.weight",+ get(f"{mg_prefix}self_attention.k_layernorm.weight"),+ )+ else:+ put(+ f"{hf_prefix}conv.in_proj.weight",+ get(f"{mg_prefix}self_attention.in_proj.weight"),+ )+ put(+ f"{hf_prefix}conv.conv.weight",+ get(f"{mg_prefix}self_attention.conv.weight"),+ )+ put(+ f"{hf_prefix}conv.out_proj.weight",+ get(f"{mg_prefix}self_attention.out_proj.weight"),+ )++ put(f"{hf_prefix}ffn_norm.weight", get(f"{mg_prefix}pre_mlp_layernorm.weight"))+ gate, up = get(f"{mg_prefix}mlp.linear_fc1.weight").chunk(2, dim=0)+ put(f"{hf_prefix}feed_forward.w1.weight", gate)+ put(f"{hf_prefix}feed_forward.w3.weight", up)+ put(+ f"{hf_prefix}feed_forward.w2.weight",+ get(f"{mg_prefix}mlp.linear_fc2.weight"),+ )++ put("model.embedding_norm.weight", get("decoder.final_layernorm.weight"))+ return hf+++def _checkpoint_file(load_dir: Path) -> Path:+ tracker = load_dir / "latest_checkpointed_iteration.txt"+ if not tracker.is_file():+ raise FileNotFoundError(f"MCore checkpoint tracker is missing: {tracker}")+ try:+ iteration = int(tracker.read_text(encoding="utf-8").strip())+ except ValueError as exc:+ raise ValueError("MCore checkpoint tracker must contain an iteration") from exc+ checkpoint = load_dir / f"iter_{iteration:07d}" / "mp_rank_00" / "model_optim_rng.pt"+ if not checkpoint.is_file():+ raise FileNotFoundError(f"MCore checkpoint is missing: {checkpoint}")+ return checkpoint+++def hf_to_mcore(load_dir: Path, save_dir: Path) -> None:+ _validate_config(load_dir)+ weights = load_file(load_dir / "model.safetensors", device="cpu")+ model = _hf_to_mcore(weights)+ checkpoint_dir = save_dir / "iter_0000001" / "mp_rank_00"+ checkpoint_dir.mkdir(parents=True, exist_ok=False)+ torch.save(+ {"model": model, "checkpoint_version": 3.0, "iteration": 1},+ checkpoint_dir / "model_optim_rng.pt",+ )+ (save_dir / "latest_checkpointed_iteration.txt").write_text("1\n", encoding="utf-8")+++def mcore_to_hf(load_dir: Path, save_dir: Path, config_dir: Path) -> None:+ _validate_config(config_dir)+ state = torch.load(_checkpoint_file(load_dir), map_location="cpu", weights_only=False)+ if not isinstance(state, dict) or not isinstance(state.get("model"), Mapping):+ raise ValueError("invalid MCore checkpoint payload")+ weights = _mcore_to_hf(state["model"])+ save_dir.mkdir(parents=True, exist_ok=False)+ save_file(weights, save_dir / "model.safetensors", metadata={"format": "pt"})+ shutil.copyfile(config_dir / "config.json", save_dir / "config.json")+++def parse_args() -> argparse.Namespace:+ parser = argparse.ArgumentParser(description=__doc__)+ subparsers = parser.add_subparsers(dest="operation", required=True)++ hf_parser = subparsers.add_parser("hf-to-mcore")+ hf_parser.add_argument("--load-dir", type=Path, required=True)+ hf_parser.add_argument("--save-dir", type=Path, required=True)++ mg_parser = subparsers.add_parser("mcore-to-hf")+ mg_parser.add_argument("--load-dir", type=Path, required=True)+ mg_parser.add_argument("--save-dir", type=Path, required=True)+ mg_parser.add_argument("--config-dir", type=Path, required=True)+ return parser.parse_args()+++def main() -> None:+ args = parse_args()+ if args.operation == "hf-to-mcore":+ hf_to_mcore(args.load_dir.resolve(), args.save_dir.resolve())+ else:+ mcore_to_hf(+ args.load_dir.resolve(), args.save_dir.resolve(), args.config_dir.resolve()+ )+++if __name__ == "__main__":+ main()@@ -0,0 +1,96 @@+"""Native Megatron-Core layer specification for LFM2.5-1.2B."""++from megatron.core.fusions.fused_bias_dropout import get_bias_dropout_add+from megatron.core.tensor_parallel.layers import ColumnParallelLinear, RowParallelLinear+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.mlp import MLP, MLPSubmodules+from megatron.core.transformer.spec_utils import ModuleSpec+from megatron.core.transformer.transformer_block import TransformerBlockSubmodules+from megatron.core.transformer.transformer_layer import TransformerLayer, TransformerLayerSubmodules++from mindspeed_llm.core.models.lfm2.short_conv import (+ LFM2ShortConv,+ LFM2ShortConvSubmodules,+)+from mindspeed_llm.core.transformer.custom_layers.transformer_engine import PTNorm+++LAYER_TYPES = (+ "conv",+ "conv",+ "full_attention",+ "conv",+ "conv",+ "full_attention",+ "conv",+ "conv",+ "full_attention",+ "conv",+ "full_attention",+ "conv",+ "full_attention",+ "conv",+ "full_attention",+ "conv",+)+++_mlp = ModuleSpec(+ module=MLP,+ submodules=MLPSubmodules(+ linear_fc1=ColumnParallelLinear,+ linear_fc2=RowParallelLinear,+ ),+)++_attention = ModuleSpec(+ module=SelfAttention,+ params={"attn_mask_type": AttnMaskType.causal},+ submodules=SelfAttentionSubmodules(+ linear_qkv=ColumnParallelLinear,+ core_attention=DotProductAttention,+ linear_proj=RowParallelLinear,+ q_layernorm=PTNorm,+ k_layernorm=PTNorm,+ ),+)++_short_conv = ModuleSpec(+ module=LFM2ShortConv,+ params={"kernel_size": 3},+ submodules=LFM2ShortConvSubmodules(+ in_proj=ColumnParallelLinear,+ out_proj=RowParallelLinear,+ ),+)+++def _transformer_layer(operator: ModuleSpec) -> ModuleSpec:+ return ModuleSpec(+ module=TransformerLayer,+ submodules=TransformerLayerSubmodules(+ input_layernorm=PTNorm,+ self_attention=operator,+ self_attn_bda=get_bias_dropout_add,+ pre_mlp_layernorm=PTNorm,+ mlp=_mlp,+ mlp_bda=get_bias_dropout_add,+ ),+ )+++_attention_layer = _transformer_layer(_attention)+_conv_layer = _transformer_layer(_short_conv)++# ``--spec ... lfm2_spec layer_spec`` imports this object directly. Supplying+# TransformerBlockSubmodules lets MCore build the authenticated heterogeneous+# layer order instead of fanning one homogeneous layer spec across the block.+layer_spec = TransformerBlockSubmodules(+ layer_specs=[+ _attention_layer if layer_type == "full_attention" else _conv_layer+ for layer_type in LAYER_TYPES+ ],+ layer_norm=PTNorm,+)@@ -3,6 +3,7 @@ """Pretrain GPT.""" import os+import sys from functools import partial from typing import Union @@ -305,5 +306,27 @@ def main(): forward_step) +def _finish_lfm2_process() -> None:+ """Avoid a long Python object-destruction tail after native LFM2 training.++ The framework has completed its writers and other finalizers when ``main``+ returns. Synchronize explicitly so all accelerator work is finished, then+ flush the observable streams before letting the operating system reclaim+ the large model/optimizer object graph in one operation.+ """++ args = get_args()+ if tuple(args.spec or ()) != (+ "mindspeed_llm.tasks.models.spec.lfm2_spec",+ "layer_spec",+ ):+ return+ torch.cuda.synchronize()+ sys.stdout.flush()+ sys.stderr.flush()+ os._exit(0)++ if __name__ == "__main__": main()+ _finish_lfm2_process()