Inspect · Source & workspace
Requested workspace inspection and file and log inspection related to source & workspace.
2 calls · #0001–#0002
ls <path>head -n <n>ls <path> <n> > <path>Kimi K3 · Training
LFM2-1.2B model adapt training 1dev · Model Adaptation
01 / PROCESS MAP
Compare agents on one time axis; overlapping spans line up vertically. Select an agent or bar to inspect its events.
Time starts at the first recorded activity. Select a bar or agent to open its events. Bars span the first and last recorded observation, including gaps; colored ticks mark tool calls. A hollow diamond marks a delegation whose child timing is unavailable.
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>. Each branch belongs to its named agent. Expand a delegation to inspect its child; branches can run concurrently. Call numbers preserve source order, not a serial schedule. Times are relative to the first recorded activity.
Requested workspace inspection and file and log inspection related to source & workspace.
2 calls · #0001–#0002
ls <path>head -n <n>ls <path> <n> > <path>Requested source searches related to attention kernels.
1 call · #0003–#0003
Search <pattern> <path>Requested workspace inspection related to source & workspace.
2 calls · #0004–#0005
Find <pattern>ls <path> <path>Requested source searches related to attention kernels.
2 calls · #0006–#0007
Search <pattern> <path>Requested workspace inspection related to source & workspace.
1 call · #0008–#0008
ls <path> <path> <path> <n> > <path>ls <path> <n> > <path>Requested source searches related to attention kernels.
1 call · #0009–#0009
Search <pattern> <path>Requested file and log inspection related to source & workspace.
2 calls · #0010–#0011
Read <path>Requested file and log inspection and source searches related to attention kernels.
4 calls · #0012–#0015
Read <path>Search <pattern> <path>Requested file and log inspection related to source & workspace.
1 call · #0016–#0016
Read <path>Requested source searches related to attention kernels.
1 call · #0017–#0017
Search <pattern> <path>Requested file and log inspection related to source & workspace.
2 calls · #0018–#0019
Read <path>Requested file and log inspection related to attention kernels.
1 call · #0020–#0020
Read <path>Requested file and log inspection related to source & workspace.
1 call · #0021–#0021
Read <path>Requested workspace inspection and file and log inspection related to attention kernels.
2 calls · #0022–#0023
ls <path> <n> > <path>ls <path>head -n <n>cat <path> <n> > <path>headRead <path>Requested file and log inspection and source searches related to source & workspace.
3 calls · #0024–#0026
sed -n <val> <path>Read <path>Search <pattern> <path>Requested source searches related to attention kernels.
1 call · #0027–#0027
Search <pattern> <path>Requested source searches, file and log inspection and workspace inspection related to source & workspace.
5 calls · #0028–#0032
Search <pattern> <path>Read <path>cat <path> <n> > <path>head -n <n>ls <path>grep -i <val>Requested file and log inspection related to attention kernels.
1 call · #0033–#0033
Read <path>Requested source searches and file and log inspection related to source & workspace.
2 calls · #0034–#0035
Search <pattern> <path>Read <path>Requested file and log inspection, workspace inspection and source searches related to attention kernels.
3 calls · #0036–#0038
Read <path>ls <path>grep -r -n <val> <path>head -n <n>Requested file and log inspection related to source & workspace.
3 calls · #0039–#0041
Read <path>Requested source searches and file and log inspection related to attention kernels.
4 calls · #0042–#0045
Search <pattern> <path>Read <path>Requested file and log inspection and source searches related to source & workspace.
4 calls · #0046–#0049
Read <path>Search <pattern> <path>Requested source searches related to attention kernels.
1 call · #0050–#0050
Search <pattern> <path>Requested source searches and file and log inspection related to source & workspace.
7 calls · #0051–#0057
Search <pattern> <path>Read <path>sed -n <val> <path>grep -r -n <val> <path> <path> <n> > <path>headgrep -r -n <val> <path>head -n <n>Requested file and log inspection and source searches related to attention kernels.
8 calls · #0058–#0065
Read <path>grep -n <val> <path> <path>grep -n <val> <path>Search <pattern> <path>Requested file and log inspection and source searches related to source & workspace.
5 calls · #0066–#0070
Read <path>Search <pattern> <path>cd <path><command> <args>grep -n <val> <flag> <args>grep -v <val>head -n <n>Requested source searches related to attention kernels.
1 call · #0071–#0071
Search <pattern> <path>Requested file and log inspection and source searches related to source & workspace.
15 calls · #0072–#0086
Read <path>Search <pattern> <path>sed -n <val> <path>Requested source searches, file and log inspection and workspace inspection related to attention kernels.
1 call · #0087–#0087
grep -r -n <val> <path> <n> > <path>head -n <n>ls <path> <n> > <path>grep -i <val>Requested file and log inspection, source searches and workspace inspection related to source & workspace.
6 calls · #0088–#0093
cat <path>grep -r -l -n <val> <path>headgrep -r -n <val> <path>grep -r -n <val> <path> <n> > <path>ls <path>head -n <n>grep -r -n <val> <path> <path>sed -n <val> <path>Read <path>Requested source searches and file and log inspection related to attention kernels.
2 calls · #0094–#0095
grep -n <val> <path> <path> <path>headsed -n <val> <path>grep -n <val> -A <n>grep -n <val> <path>Requested source searches and file and log inspection related to source & workspace.
1 call · #0096–#0096
grep -r -n <val> <path>head -n <n>grep -n <val> <path>Requested source searches and file and log inspection related to attention kernels.
1 call · #0097–#0097
grep -n <val> -A <n> <path>headgrep -n <val> <path>Requested source searches and file and log inspection related to source & workspace.
1 call · #0098–#0098
grep -n <val> -A <n> <path>head -n <n>Requested source searches and file and log inspection related to attention kernels.
1 call · #0099–#0099
cd <path><command> <args>grep -n <val> <val>head -n <n>grep -n <val> <path>Requested file and log inspection related to source & workspace.
1 call · #0100–#0100
Read <path>Requested file and log inspection and source searches related to device memory.
1 call · #0101–#0101
sed -n <val> <path>grep -r -n <val> <path> <n> > <path>head -n <n>grep -r -l -n <val> <path>Requested source searches, file and log inspection and workspace inspection related to source & workspace.
2 calls · #0102–#0103
grep -r -n <val> <path>head -n <n>grep -n <val> <path> <n> > <path>grep -r -l -n <val> <path>echo <val>ls -l -a <val> <n> > <path>trueRequested file and log inspection related to task requirements.
2 calls · #0104–#0105
Read <path>Requested workspace inspection and file and log inspection related to source & workspace.
2 calls · #0106–#0107
find <path> -type <val>sortecho <flag>ls <path>Read <path>Requested file and log inspection related to task requirements.
2 calls · #0108–#0109
Read <path>Requested file and log inspection related to source & workspace.
1 call · #0110–#0110
Read <path>Requested file and log inspection related to benchmark & validation setup.
1 call · #0111–#0111
Read <path>Requested file and log inspection related to source & workspace.
4 calls · #0112–#0115
Read <path>Requested file and log inspection related to task requirements.
2 calls · #0116–#0117
Read <path>Requested file and log inspection related to benchmark & validation setup.
1 call · #0118–#0118
cat <path> <path> <path> <path> <path> <path>Requested environment setup or inspection, source searches and file and log inspection related to source & workspace.
3 calls · #0119–#0121
envgrep -E <val>sortecho <flag>cat <val> <n> > <path>head -n <n>ls <path>ls <path> <n> > <path>Update task list <tasks>Requested workspace inspection and file and log inspection related to checkpoints & weight state.
1 call · #0122–#0122
ls <path> <n> > <path>head -n <n>echo <flag>ls <path>Requested source searches, file and log inspection and workspace inspection related to source & workspace.
3 calls · #0123–#0125
grep -r -i <val> <path> --include <path> -lhead -n <n>echo <flag>Read <path>ls <path>cat <path>Requested script or workload execution related to source & workspace.
2 calls · #0126–#0127
python3 -c <script>Requested file and log inspection, repository inspection and script or workload execution related to source & workspace.
4 calls · #0128–#0131
sed -n <val> <path>Read <path>cd <path>git log --oneline <flag> <args>git <val> -vtimeout <n> <val> <val> <url> <val> <n> >& <path>head -n <n>Requested script or workload execution and file and log inspection related to source & workspace.
1 call · #0132–#0132
cd <path>timeout <n> <val> -s <url> <n> > <path>python3 -c <script>head -n <n>Requested script or workload execution, file and log inspection and repository inspection related to source & workspace.
3 calls · #0133–#0135
cd <path>timeout <n> <val> <val> <flag> <args>tail -n <n>cd <val> <n> > <path>git ls-filesgrep -i <val>head -n <n>grep <flag> <args>git log --oneline <flag>ls <path>headecho <flag>git ls-files <path>grep -n <val> <path>sed -n <val> <path>Requested task coordination related to source & workspace.
1 call · #0136–#0136
Delegate <task>Delegated by Main agent at call #0136.
Only the returned summary is retained; child tool events are not available.
Requested file and log inspection and source searches related to source & workspace.
5 calls · #0137–#0141
Read <path>sed -n <val> <path>echo <val>grep -n <val> -A <n> <path>cat <path>Requested source searches and file and log inspection related to attention kernels.
5 calls · #0142–#0146
grep -n <val> <path>head -n <n>Read <path>Requested file and log inspection and task coordination related to source & workspace.
2 calls · #0147–#0148
Read <path>Update task list <tasks>Requested script or workload execution and file and log inspection related to benchmark & validation setup.
1 call · #0149–#0149
cd <path>bash <script> > <path> <n> >& <path>echo <val>tail -n <n> <path>Requested source searches and file and log inspection related to checkpoints & weight state.
2 calls · #0150–#0151
grep -n <val> <path>head -n <n>sed -n <val> <path>Requested file and log inspection related to source & workspace.
1 call · #0152–#0152
cat <path>Requested file and log inspection and source searches related to checkpoints & weight state.
4 calls · #0153–#0156
sed -n <val> <path>grep -n <val> <path> <path> <n> > <path>sed -n <path> <path>grep -n <val> <path>headecho <val>grep -r -n <val> <path> <path> <n> > <path>Requested file and log inspection related to parallelism & communication.
1 call · #0157–#0157
sed -n <val> <path>Requested dependency and build commands, source searches and workspace inspection related to checkpoints & weight state.
1 call · #0158–#0158
pip list <n> > <path>grep -i -E <val>echo <val>ls <path>cat <path> <n> > <path>headhead -n <n> <path>Requested file and log inspection related to source & workspace.
1 call · #0159–#0159
sed -n <val> <path>echo <val> <val>Requested file and log inspection related to checkpoints & weight state.
1 call · #0160–#0160
sed -n <val> <path>echo <val>Requested source searches and file and log inspection related to attention kernels.
1 call · #0161–#0161
grep -n <val> <path>headecho <val>grep -r -n <val> <path>head -n <n>sed -n <val> <path>Requested file and log inspection related to source & workspace.
1 call · #0162–#0162
sed -n <val> <path>Requested code edits related to convolution & sequence boundaries.
1 call · #0163–#0163
Write <path>Requested code edits related to source & workspace.
2 calls · #0164–#0165
Write <path>Requested file and log inspection related to source & workspace.
1 call · #0166–#0166
Read <path>Requested code edits related to source & workspace.
1 call · #0167–#0167
Write <path>Requested source searches and file and log inspection related to source & workspace.
2 calls · #0168–#0169
grep -n <val> -A <n> <path>sed -n <val>sed -n <val> <path>Requested code edits related to checkpoints & weight state.
1 call · #0170–#0170
Write <path>Requested workspace file updates, script or workload execution and workspace inspection related to checkpoints & weight state.
1 call · #0171–#0171
cd <path>rm -rf <path>mkdir -p <path>python3 <script> <val> <flag> <args>python3 - <script>ls -R <path>headcat <path>Requested task coordination related to source & workspace.
1 call · #0172–#0172
Update task list <tasks>Requested script or workload execution, file and log inspection and execution waits related to benchmark & validation setup.
4 calls · #0173–#0176
cd <path>bash <script> > <path> <n> >& <path>echo <val> >> <path>tail -n <n> <path>sleep <n>tail -n <n> <path> <n> > <path>ls <path> <n> > <path>grep -v -E <val>tail -n <n>grep -E <val> <path> <n> > <path>Requested code edits related to source & workspace.
1 call · #0177–#0177
Write <path>Requested execution waits, file and log inspection and workspace inspection related to benchmark & validation setup.
3 calls · #0178–#0180
sleep <n>tail -n <n> <path> <n> > <path>ls <path> <n> > <path>tailgrep -E <val> <path> <n> > <path>tail -n <n>grep <flag> <args><command> <args>echo <val> <val>tail -n <n> <path>python3 -c <script>Requested task coordination related to source & workspace.
1 call · #0181–#0181
Update task list <tasks>Requested script or workload execution, file and log inspection and execution waits related to benchmark & validation setup.
3 calls · #0182–#0184
cd <path>bash <script> > <path> <n> >& <path>echo <val> >> <path>tail -n <n> <path>sleep <n>grep <flag> <args><command> <args>tail -n <n>echotail -n <n> <path> <n> > <path>python3 -c <script>head -n <n>Requested source searches and file and log inspection related to benchmark & validation setup.
1 call · #0185–#0185
grep -n <n> <path>tail -n <n>echo <val>Requested source searches and file and log inspection related to runtime processes.
1 call · #0186–#0186
grep -n <val> <path>head -n <n>grep -n <val> <flag> <args>Requested file and log inspection and source searches related to source & workspace.
1 call · #0187–#0187
sed -n <val> <path>grep -r -n <val> <path>sed -n <val>Requested dependency and build commands, source searches and file and log inspection related to dependencies & build setup.
1 call · #0188–#0188
which <val> <n> > <path>pip list <n> > <path>grep -i <val>grep -n <val> <path> <path> <n> > <path>headRequested file and log inspection related to source & workspace.
1 call · #0189–#0189
sed -n <val> <path>Requested workspace file updates, script or workload execution and source searches related to source & workspace.
1 call · #0190–#0190
cd <path>cp <path> <path>python3 - <script>grep -n <val> <path> <path>Requested script or workload execution and workspace file updates related to benchmark & validation setup.
1 call · #0191–#0191
cd <path>python3 - <script>mkdir -p <path> <path>Requested task coordination related to source & workspace.
1 call · #0192–#0192
Update task list <tasks>Requested script or workload execution and file and log inspection related to checkpoints & weight state.
1 call · #0193–#0193
cd <path>python3 <script> <val> <flag> <args>tail -n <n>Requested environment setup or inspection related to parallelism & communication.
1 call · #0194–#0194
cd <path>env -i <vars> <val> -c <vars> > <path> <n> >& <path>echo <val> >> <path>Requested code edits related to source & workspace.
1 call · #0195–#0195
Write <path>Requested source searches and file and log inspection related to source & workspace.
1 call · #0196–#0196
grep <val> <path>tail -n <n> <path>Requested environment setup or inspection related to parallelism & communication.
1 call · #0197–#0197
cd <path>env -i <vars> <val> <path> > <path> <n> >& <path>echo <val> >> <path>Requested source searches and file and log inspection related to benchmark & validation setup.
1 call · #0198–#0198
grep -n -E <val> <path> <n> > <path>head -n <n>head -c <n> <path>echogrep -c <val> <path>Requested execution waits, source searches and file and log inspection related to source & workspace.
1 call · #0199–#0199
sleep <n>grep <val> <path>tail -n <n> <path>Requested script or workload execution and source searches related to source & workspace.
1 call · #0200–#0200
cd <path>python3 - <script>grep -n <val> <path>Requested environment setup or inspection related to parallelism & communication.
1 call · #0201–#0201
cd <path>env -i <vars> <val> <path> > <path> <n> >& <path>echo <val> >> <path>Requested execution waits, source searches and file and log inspection related to source & workspace.
1 call · #0202–#0202
sleep <n>grep <val> <path>tail -n <n> <path>Requested script or workload execution and source searches related to source & workspace.
1 call · #0203–#0203
cd <path>timeout <n> <val> <path> <n> >& <path>grep -v <val>Requested source searches, file and log inspection and workspace file updates related to source & workspace.
2 calls · #0204–#0205
grep -n <val> -A <n> <path>head -n <n>cd <path>cp <path> <path>git diff --statRequested code edits related to source & workspace.
1 call · #0206–#0206
Edit <path>Requested file and log inspection and source searches related to source & workspace.
1 call · #0207–#0207
cd <path>head -n <n> <path>grep -n <val>Requested code edits related to source & workspace.
1 call · #0208–#0208
Edit <path>Requested script or workload execution and file and log inspection related to benchmark & validation setup.
1 call · #0209–#0209
cd <path>bash <script> > <path> <n> >& <path>echo <val> >> <path>tail -n <n> <path>Requested file and log inspection related to source & workspace.
1 call · #0210–#0210
Read <path>Requested script or workload execution, file and log inspection and source searches related to benchmark & validation setup.
3 calls · #0211–#0213
python3 -c <script>tail -n <n> <path> <n> > <path>grep -v -E <val>tail -n <n>rm -f <path>ls <path>wc -lcd <path>bash <script> > <path> <n> >& <path>echo <val> >> <path>tail -n <n> <path>Requested task coordination related to source & workspace.
1 call · #0214–#0214
Update task list <tasks>Requested source searches and file and log inspection related to parallelism & communication.
1 call · #0215–#0215
grep -r -n <val> -A <n> <path>head -n <n>grep -r -n <val> <path>Requested execution waits, source searches and file and log inspection related to benchmark & validation setup.
2 calls · #0216–#0217
sleep <n>grep <flag> <args>tail -n <n>tail -n <n> <path> <n> > <path>python3 -c <script>Requested workspace file updates, script or workload execution and file and log inspection related to benchmark & validation setup.
1 call · #0218–#0218
rm -f <path>cd <path>bash <script> > <path> <n> >& <path>echo <val> >> <path>tail -n <n> <path>Requested repository inspection related to source & workspace.
1 call · #0219–#0219
cd <path>git status --shortgit diff --statecho <val>git diff <path>Requested execution waits, source searches and file and log inspection related to checkpoints & weight state.
1 call · #0220–#0220
sleep <n>grep -n -E <val> <path> <n> > <path>head -n <n>Requested workspace inspection and file and log inspection related to source & workspace.
1 call · #0221–#0221
ls <path> <n> > <path>tail -n <n> <path> <n> > <path>Requested source searches, file and log inspection and execution waits related to benchmark & validation setup.
2 calls · #0222–#0223
grep -n -E <val> <path> <n> > <path>head -n <n>sleep <n>tail -n <n> <path>python3 -c <script>Requested script or workload execution, runtime inspection and source searches related to device memory.
1 call · #0224–#0224
cd <path>bash <script> <n> >& <path>python3 -c <script>ps <val>grep -E <val>grep -v <val>wc -lnpu-smi info <n> > <path>head -n <n>Requested task coordination, repository inspection and file and log inspection related to source & workspace.
2 calls · #0225–#0226
Update task list <tasks>cd <path>git status --shorthead -n <n>echo <val>03 / 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,30 @@+# 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.++from mindspeed_llm.core.models.lfm2.short_conv import (+ Lfm2ShortConv,+ Lfm2ShortConvSubmodules,+)+from mindspeed_llm.core.models.lfm2.decoder_layer import (+ Lfm2DecoderLayer,+ Lfm2DecoderLayerSubmodules,+)++__all__ = [+ "Lfm2ShortConv",+ "Lfm2ShortConvSubmodules",+ "Lfm2DecoderLayer",+ "Lfm2DecoderLayerSubmodules",+]@@ -0,0 +1,182 @@+# 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 decoder layer.++A single LFM2 decoder layer is a pre-norm residual block whose operator is+either a full-attention block or a short-convolution block, followed by a+SwiGLU feed-forward network:++ hidden = hidden + operator(operator_norm(hidden))+ hidden = hidden + mlp(ffn_norm(hidden))++The layer follows the ``TransformerLayer`` calling convention of+Megatron-Core so it can be scheduled by ``TransformerBlock`` (including+full activation recompute).+"""++from dataclasses import dataclass, field+from typing import Any, Dict, Optional, Tuple, Union++import torch+from torch import Tensor++from megatron.core.packed_seq_params import PackedSeqParams+from megatron.core.transformer.identity_op import IdentityOp+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+from megatron.core.transformer.transformer_layer import BaseTransformerLayer+++@dataclass+class Lfm2DecoderLayerSubmodules:+ """Submodules of :class:`Lfm2DecoderLayer`.++ ``operator`` is the token-mixing block of the layer: a self-attention+ module for ``full_attention`` layers or an :class:`Lfm2ShortConv` module+ for ``conv`` layers. The attribute name used for the operator module is+ part of the checkpoint contract: attention operators are registered as+ ``self_attention`` and convolution operators as ``conv``.+ """++ input_layernorm: Union[ModuleSpec, type] = IdentityOp+ operator: Union[ModuleSpec, type] = IdentityOp+ self_attn_bda: Union[ModuleSpec, type] = IdentityOp+ pre_mlp_layernorm: Union[ModuleSpec, type] = IdentityOp+ mlp: Union[ModuleSpec, type] = IdentityOp+ mlp_bda: Union[ModuleSpec, type] = IdentityOp++ sharded_state_dict_keys_map: Dict[str, str] = field(default_factory=dict)+++class Lfm2DecoderLayer(MegatronModule, BaseTransformerLayer):+ """A single LFM2 decoder layer with size [s, b, h] input and output."""++ def __init__(+ self,+ config: TransformerConfig,+ submodules: Lfm2DecoderLayerSubmodules,+ layer_number: int = 1,+ hidden_dropout: Optional[float] = None,+ is_attention: bool = False,+ ):+ super().__init__(config=config)+ self.config = config+ self.layer_number = layer_number+ self.hidden_dropout = config.hidden_dropout if hidden_dropout is None else hidden_dropout+ self.is_attention = is_attention++ self.input_layernorm = build_module(+ submodules.input_layernorm,+ config=self.config,+ hidden_size=self.config.hidden_size,+ eps=self.config.layernorm_epsilon,+ )++ # The operator module attribute name defines the checkpoint key of the+ # block: ``self_attention.*`` for attention layers and ``conv.*`` for+ # short-convolution layers.+ if self.is_attention:+ self.self_attention = build_module(+ submodules.operator,+ config=self.config,+ layer_number=layer_number,+ )+ else:+ self.conv = build_module(+ submodules.operator,+ config=self.config,+ layer_number=layer_number,+ )++ self.self_attn_bda = build_module(submodules.self_attn_bda)++ self.pre_mlp_layernorm = build_module(+ submodules.pre_mlp_layernorm,+ config=self.config,+ hidden_size=self.config.hidden_size,+ eps=self.config.layernorm_epsilon,+ )++ self.mlp = build_module(submodules.mlp, config=self.config)+ if hasattr(self.mlp, 'set_layer_number'):+ self.mlp.set_layer_number(self.layer_number)++ self.mlp_bda = build_module(submodules.mlp_bda)++ self.bias_dropout_add_exec_handler = torch.enable_grad++ def forward(+ self,+ hidden_states: Tensor,+ attention_mask: Optional[Tensor] = None,+ context: Optional[Tensor] = None,+ context_mask: Optional[Tensor] = None,+ rotary_pos_emb: Optional[Tensor] = None,+ rotary_pos_cos: Optional[Tensor] = None,+ rotary_pos_sin: Optional[Tensor] = None,+ attention_bias: Optional[Tensor] = None,+ inference_context: Optional[Any] = None,+ packed_seq_params: Optional[PackedSeqParams] = None,+ sequence_len_offset: Optional[int] = None,+ **kwargs,+ ) -> Tuple[Tensor, Optional[Tensor]]:+ # Residual connection.+ residual = hidden_states++ # Input layernorm before the token-mixing operator.+ input_layernorm_output = self.input_layernorm(hidden_states)++ if self.is_attention:+ operator_output_with_bias = self.self_attention(+ input_layernorm_output,+ attention_mask=attention_mask,+ inference_context=inference_context,+ rotary_pos_emb=rotary_pos_emb,+ rotary_pos_cos=rotary_pos_cos,+ rotary_pos_sin=rotary_pos_sin,+ attention_bias=attention_bias,+ packed_seq_params=packed_seq_params,+ sequence_len_offset=sequence_len_offset,+ )+ else:+ operator_output_with_bias = self.conv(+ input_layernorm_output,+ attention_mask=attention_mask,+ )++ # Residual connection after the operator.+ with self.bias_dropout_add_exec_handler():+ hidden_states = self.self_attn_bda(self.training, self.config.bias_dropout_fusion)(+ operator_output_with_bias, residual, self.hidden_dropout+ )++ # Residual connection.+ residual = hidden_states++ # Layer norm before the feed-forward network.+ pre_mlp_layernorm_output = self.pre_mlp_layernorm(hidden_states)++ # Feed-forward network.+ mlp_output_with_bias = self.mlp(pre_mlp_layernorm_output)++ # Residual connection after the feed-forward network.+ with self.bias_dropout_add_exec_handler():+ output = self.mlp_bda(self.training, self.config.bias_dropout_fusion)(+ mlp_output_with_bias, residual, self.hidden_dropout+ )++ return output, context@@ -0,0 +1,128 @@+# 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 operator.++This module implements the causal depthwise short-convolution operator used+by the conv layers of the LFM2 hybrid model. It mirrors the semantics of the+HuggingFace ``Lfm2ShortConv`` module:++ BCx = in_proj(x) # hidden -> 3 * hidden+ B, C, x = BCx.chunk(3, dim)+ y = C * causal_depthwise_conv1d(B * x)+ y = out_proj(y)++The convolution is a depthwise Conv1d with kernel size ``L`` and left padding+``L - 1``; the trailing ``L - 1`` positions are dropped so the operator is+strictly causal.+"""++from dataclasses import dataclass+from typing import Optional, Tuple, Union++import torch+from torch import Tensor++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++# LFM2 uses a fixed causal convolution kernel size (HF config ``conv_L_cache``).+LFM2_CONV_KERNEL_SIZE = 3+++@dataclass+class Lfm2ShortConvSubmodules:+ """Submodules used by :class:`Lfm2ShortConv` for its projections."""++ in_proj: Union[ModuleSpec, type] = None+ out_proj: Union[ModuleSpec, type] = None+++class Lfm2ShortConv(MegatronModule):+ """Causal depthwise short-convolution operator of LFM2.++ Takes hidden states of shape [s, b, h] and returns a tuple of+ (output [s, b, h], bias) so it can be composed exactly like the+ self-attention module inside a decoder layer.+ """++ def __init__(+ self,+ config: TransformerConfig,+ submodules: Lfm2ShortConvSubmodules,+ layer_number: int = 1,+ ):+ super().__init__(config=config)+ self.config = config+ self.layer_number = layer_number+ self.kernel_size = LFM2_CONV_KERNEL_SIZE++ self.in_proj = build_module(+ submodules.in_proj,+ self.config.hidden_size,+ 3 * self.config.hidden_size,+ config=self.config,+ init_method=self.config.init_method,+ gather_output=False,+ bias=self.config.add_bias_linear,+ skip_bias_add=False,+ is_expert=False,+ )++ self.conv = torch.nn.Conv1d(+ in_channels=self.config.hidden_size,+ out_channels=self.config.hidden_size,+ kernel_size=self.kernel_size,+ groups=self.config.hidden_size,+ bias=False,+ padding=self.kernel_size - 1,+ )++ self.out_proj = build_module(+ submodules.out_proj,+ self.config.hidden_size,+ self.config.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,+ )++ def forward(+ self,+ hidden_states: Tensor,+ attention_mask: Optional[Tensor] = None,+ **kwargs,+ ) -> Tuple[Tensor, Optional[Tensor]]:+ # hidden_states: [s, b, h]+ seq_len = hidden_states.size(0)++ projected, _ = self.in_proj(hidden_states)+ # [s, b, 3h] -> [b, 3h, s]+ projected = projected.permute(1, 2, 0)+ gate_b, gate_c, value = projected.chunk(3, dim=1)++ mixed = gate_b * value+ # Causal depthwise convolution: left pad L - 1, drop the tail.+ conv_out = self.conv(mixed)[..., :seq_len]+ out = gate_c * conv_out++ # [b, h, s] -> [s, b, h]+ out = out.permute(2, 0, 1).contiguous()+ output, bias = self.out_proj(out)+ return output, bias@@ -0,0 +1,282 @@+# 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.++"""Checkpoint converter between HuggingFace LFM2 and Megatron-Core formats.++Usage:+ 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 Megatron-Core checkpoint is written in the legacy ``torch`` checkpoint+format (``<dir>/iter_0000001/mp_rank_00/model_optim_rng.pt`` plus the+``latest_checkpointed_iteration.txt`` tracker) so it can be consumed by+``pretrain_gpt.py --ckpt-format torch --load <mcore_dir>``.++The HuggingFace checkpoint keeps the exact key set and tensor values of the+original LFM2 model: every mapping here is a pure reshape/concatenation of+bf16 tensors, so round-tripping is bit exact.+"""++import argparse+import json+import os+import shutil+import sys++import torch+from safetensors.torch import load_file, save_file++TRACKER_FILENAME = "latest_checkpointed_iteration.txt"+CHECKPOINT_BASENAME = "model_optim_rng.pt"+CONFIG_FILES = (+ "config.json",+ "generation_config.json",+ "tokenizer.json",+ "tokenizer_config.json",+ "special_tokens_map.json",+ "chat_template.jinja",+)+++def _load_config(config_dir):+ with open(os.path.join(config_dir, "config.json"), "r", encoding="utf-8") as file:+ config = json.load(file)+ layer_types = config.get("layer_types")+ if not isinstance(layer_types, list) or not layer_types:+ raise ValueError("config.json does not define a valid 'layer_types' list")+ return config+++def _checkpoint_path(load_dir):+ tracker = os.path.join(load_dir, TRACKER_FILENAME)+ with open(tracker, "r", encoding="utf-8") as file:+ iteration = int(file.read().strip())+ path = os.path.join(+ load_dir, f"iter_{iteration:07d}", "mp_rank_00", CHECKPOINT_BASENAME+ )+ if not os.path.isfile(path):+ raise FileNotFoundError(f"megatron checkpoint not found: {path}")+ return iteration, path+++def _merge_qkv(config, q_proj, k_proj, v_proj):+ """Interleave HF q/k/v projection rows into the Megatron GQA fused layout.++ Megatron stores the fused qkv weight as ``[ng, (np / ng + 2) * hn, h]``,+ i.e. for every query group the q rows of that group are followed by the+ single k row-block and v row-block of the group.+ """+ num_query_groups = int(config["num_key_value_heads"])+ hidden_size = int(config["hidden_size"])+ kv_channels = q_proj.shape[0] // int(config["num_attention_heads"])+ q_proj = q_proj.view(num_query_groups, -1, hidden_size)+ k_proj = k_proj.view(num_query_groups, kv_channels, hidden_size)+ v_proj = v_proj.view(num_query_groups, kv_channels, hidden_size)+ fused = torch.cat([q_proj, k_proj, v_proj], dim=1)+ return fused.reshape(-1, hidden_size).contiguous()+++def _split_qkv(config, fused):+ """Inverse of :func:`_merge_qkv`."""+ num_query_groups = int(config["num_key_value_heads"])+ num_attention_heads = int(config["num_attention_heads"])+ hidden_size = int(config["hidden_size"])+ kv_channels = fused.shape[0] // (num_attention_heads + 2 * num_query_groups)+ q_size = (num_attention_heads // num_query_groups) * kv_channels+ fused = fused.view(num_query_groups, -1, hidden_size)+ q_proj, k_proj, v_proj = torch.split(+ fused, [q_size, kv_channels, kv_channels], dim=1+ )+ return (+ q_proj.reshape(-1, hidden_size).contiguous(),+ k_proj.reshape(-1, hidden_size).contiguous(),+ v_proj.reshape(-1, hidden_size).contiguous(),+ )+++def hf_to_mcore(load_dir, save_dir):+ config = _load_config(load_dir)+ hf_state = load_file(os.path.join(load_dir, "model.safetensors"))++ model_state = {}+ model_state["embedding.word_embeddings.weight"] = hf_state[+ "model.embed_tokens.weight"+ ]+ model_state["decoder.final_layernorm.weight"] = hf_state[+ "model.embedding_norm.weight"+ ]++ for layer_idx, layer_type in enumerate(config["layer_types"]):+ hf_prefix = f"model.layers.{layer_idx}"+ mg_prefix = f"decoder.layers.{layer_idx}"++ model_state[f"{mg_prefix}.input_layernorm.weight"] = hf_state[+ f"{hf_prefix}.operator_norm.weight"+ ]+ model_state[f"{mg_prefix}.pre_mlp_layernorm.weight"] = hf_state[+ f"{hf_prefix}.ffn_norm.weight"+ ]+ model_state[f"{mg_prefix}.mlp.linear_fc1.weight"] = torch.cat(+ [+ hf_state[f"{hf_prefix}.feed_forward.w1.weight"],+ hf_state[f"{hf_prefix}.feed_forward.w3.weight"],+ ],+ dim=0,+ ).contiguous()+ model_state[f"{mg_prefix}.mlp.linear_fc2.weight"] = hf_state[+ f"{hf_prefix}.feed_forward.w2.weight"+ ]++ if layer_type == "full_attention":+ model_state[f"{mg_prefix}.self_attention.linear_qkv.weight"] = _merge_qkv(+ config,+ hf_state[f"{hf_prefix}.self_attn.q_proj.weight"],+ hf_state[f"{hf_prefix}.self_attn.k_proj.weight"],+ hf_state[f"{hf_prefix}.self_attn.v_proj.weight"],+ )+ model_state[f"{mg_prefix}.self_attention.linear_proj.weight"] = hf_state[+ f"{hf_prefix}.self_attn.out_proj.weight"+ ]+ model_state[f"{mg_prefix}.self_attention.q_layernorm.weight"] = hf_state[+ f"{hf_prefix}.self_attn.q_layernorm.weight"+ ]+ model_state[f"{mg_prefix}.self_attention.k_layernorm.weight"] = hf_state[+ f"{hf_prefix}.self_attn.k_layernorm.weight"+ ]+ elif layer_type == "conv":+ model_state[f"{mg_prefix}.conv.in_proj.weight"] = hf_state[+ f"{hf_prefix}.conv.in_proj.weight"+ ]+ model_state[f"{mg_prefix}.conv.conv.weight"] = hf_state[+ f"{hf_prefix}.conv.conv.weight"+ ]+ model_state[f"{mg_prefix}.conv.out_proj.weight"] = hf_state[+ f"{hf_prefix}.conv.out_proj.weight"+ ]+ else:+ raise ValueError(f"unsupported layer type: {layer_type}")++ iteration = 1+ checkpoint_dir = os.path.join(save_dir, f"iter_{iteration:07d}", "mp_rank_00")+ os.makedirs(checkpoint_dir, exist_ok=True)+ checkpoint = {+ "model": model_state,+ "iteration": iteration,+ "checkpoint_version": 3.0,+ }+ torch.save(checkpoint, os.path.join(checkpoint_dir, CHECKPOINT_BASENAME))+ with open(os.path.join(save_dir, TRACKER_FILENAME), "w", encoding="utf-8") as file:+ file.write(str(iteration))+ print(f"converted HF checkpoint at {load_dir} to Megatron-Core checkpoint at {save_dir}")+++def mcore_to_hf(load_dir, save_dir, config_dir):+ config = _load_config(config_dir)+ _, checkpoint_path = _checkpoint_path(load_dir)+ checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=False)+ if "model" not in checkpoint:+ raise ValueError(f"checkpoint at {checkpoint_path} has no 'model' state")+ model_state = checkpoint["model"]++ hf_state = {}+ hf_state["model.embed_tokens.weight"] = model_state[+ "embedding.word_embeddings.weight"+ ]+ hf_state["model.embedding_norm.weight"] = model_state[+ "decoder.final_layernorm.weight"+ ]++ for layer_idx, layer_type in enumerate(config["layer_types"]):+ hf_prefix = f"model.layers.{layer_idx}"+ mg_prefix = f"decoder.layers.{layer_idx}"++ hf_state[f"{hf_prefix}.operator_norm.weight"] = model_state[+ f"{mg_prefix}.input_layernorm.weight"+ ]+ hf_state[f"{hf_prefix}.ffn_norm.weight"] = model_state[+ f"{mg_prefix}.pre_mlp_layernorm.weight"+ ]+ ffn_size = model_state[f"{mg_prefix}.mlp.linear_fc1.weight"].shape[0] // 2+ w1, w3 = torch.split(+ model_state[f"{mg_prefix}.mlp.linear_fc1.weight"], ffn_size, dim=0+ )+ hf_state[f"{hf_prefix}.feed_forward.w1.weight"] = w1.contiguous()+ hf_state[f"{hf_prefix}.feed_forward.w3.weight"] = w3.contiguous()+ hf_state[f"{hf_prefix}.feed_forward.w2.weight"] = model_state[+ f"{mg_prefix}.mlp.linear_fc2.weight"+ ]++ if layer_type == "full_attention":+ q_proj, k_proj, v_proj = _split_qkv(+ config, model_state[f"{mg_prefix}.self_attention.linear_qkv.weight"]+ )+ hf_state[f"{hf_prefix}.self_attn.q_proj.weight"] = q_proj+ hf_state[f"{hf_prefix}.self_attn.k_proj.weight"] = k_proj+ hf_state[f"{hf_prefix}.self_attn.v_proj.weight"] = v_proj+ hf_state[f"{hf_prefix}.self_attn.out_proj.weight"] = model_state[+ f"{mg_prefix}.self_attention.linear_proj.weight"+ ]+ hf_state[f"{hf_prefix}.self_attn.q_layernorm.weight"] = model_state[+ f"{mg_prefix}.self_attention.q_layernorm.weight"+ ]+ hf_state[f"{hf_prefix}.self_attn.k_layernorm.weight"] = model_state[+ f"{mg_prefix}.self_attention.k_layernorm.weight"+ ]+ elif layer_type == "conv":+ hf_state[f"{hf_prefix}.conv.in_proj.weight"] = model_state[+ f"{mg_prefix}.conv.in_proj.weight"+ ]+ hf_state[f"{hf_prefix}.conv.conv.weight"] = model_state[+ f"{mg_prefix}.conv.conv.weight"+ ]+ hf_state[f"{hf_prefix}.conv.out_proj.weight"] = model_state[+ f"{mg_prefix}.conv.out_proj.weight"+ ]+ else:+ raise ValueError(f"unsupported layer type: {layer_type}")++ os.makedirs(save_dir, exist_ok=True)+ save_file(hf_state, os.path.join(save_dir, "model.safetensors"))+ for name in CONFIG_FILES:+ source = os.path.join(config_dir, name)+ if os.path.isfile(source):+ shutil.copyfile(source, os.path.join(save_dir, name))+ print(f"converted Megatron-Core checkpoint at {load_dir} to HF checkpoint at {save_dir}")+++def main():+ parser = argparse.ArgumentParser(description="LFM2 HF <-> Megatron-Core checkpoint converter")+ subparsers = parser.add_subparsers(dest="command", required=True)++ hf_to_mcore_parser = subparsers.add_parser("hf-to-mcore")+ hf_to_mcore_parser.add_argument("--load-dir", required=True)+ hf_to_mcore_parser.add_argument("--save-dir", required=True)++ mcore_to_hf_parser = subparsers.add_parser("mcore-to-hf")+ mcore_to_hf_parser.add_argument("--load-dir", required=True)+ mcore_to_hf_parser.add_argument("--save-dir", required=True)+ mcore_to_hf_parser.add_argument("--config-dir", required=True)++ args = parser.parse_args()++ if args.command == "hf-to-mcore":+ hf_to_mcore(args.load_dir, args.save_dir)+ else:+ mcore_to_hf(args.load_dir, args.save_dir, args.config_dir)+++if __name__ == "__main__":+ sys.exit(main())@@ -0,0 +1,124 @@+# 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.++"""Megatron-Core layer specification for the LFM2 hybrid model.++LFM2 interleaves full-attention decoder layers with short-convolution+decoder layers. This module exposes ``layer_spec``, a+``TransformerBlockSubmodules`` describing the whole decoder stack of+LFM2.5-1.2B (16 layers), which is consumed by ``pretrain_gpt.py`` through+``--spec mindspeed_llm.tasks.models.spec.lfm2_spec layer_spec``.+"""++from megatron.core.fusions.fused_bias_dropout import get_bias_dropout_add+from megatron.core.models.gpt.gpt_layer_specs import get_mlp_module_spec+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.identity_op import IdentityOp+from megatron.core.transformer.spec_utils import ModuleSpec+from megatron.core.transformer.transformer_block import TransformerBlockSubmodules+from megatron.training import get_args++from mindspeed_llm.core.models.lfm2.decoder_layer import (+ Lfm2DecoderLayer,+ Lfm2DecoderLayerSubmodules,+)+from mindspeed_llm.core.models.lfm2.short_conv import (+ Lfm2ShortConv,+ Lfm2ShortConvSubmodules,+)+from mindspeed_llm.core.transformer.custom_layers.transformer_engine import PTNorm++# Token-mixing operator of every decoder layer of LFM2.5-1.2B, in order.+# ``conv`` layers use the LFM2 short convolution, ``full_attention`` layers+# use grouped-query full attention. This pattern is part of the fixed model+# architecture (HF config ``layer_types``).+LFM2_LAYER_TYPES = [+ "conv", "conv", "full_attention", "conv",+ "conv", "full_attention", "conv", "conv",+ "full_attention", "conv", "full_attention", "conv",+ "full_attention", "conv", "full_attention", "conv",+]+++def _lfm2_attention_operator_spec(qk_layernorm: bool) -> ModuleSpec:+ return 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,+ ),+ )+++def _lfm2_conv_operator_spec() -> ModuleSpec:+ return ModuleSpec(+ module=Lfm2ShortConv,+ submodules=Lfm2ShortConvSubmodules(+ in_proj=ColumnParallelLinear,+ out_proj=RowParallelLinear,+ ),+ )+++def _lfm2_layer_spec(is_attention: bool, mlp_spec: ModuleSpec, qk_layernorm: bool) -> ModuleSpec:+ operator_spec = (+ _lfm2_attention_operator_spec(qk_layernorm)+ if is_attention+ else _lfm2_conv_operator_spec()+ )+ return ModuleSpec(+ module=Lfm2DecoderLayer,+ params={"is_attention": is_attention},+ submodules=Lfm2DecoderLayerSubmodules(+ input_layernorm=PTNorm,+ operator=operator_spec,+ self_attn_bda=get_bias_dropout_add,+ pre_mlp_layernorm=PTNorm,+ mlp=mlp_spec,+ mlp_bda=get_bias_dropout_add,+ ),+ )+++def _build_lfm2_block_spec() -> TransformerBlockSubmodules:+ args = get_args()+ if args.transformer_impl != "local":+ raise ValueError("lfm2_spec only supports --transformer-impl local")+ if len(LFM2_LAYER_TYPES) != args.num_layers:+ raise ValueError(+ f"lfm2_spec defines {len(LFM2_LAYER_TYPES)} layers, "+ f"but --num-layers is {args.num_layers}"+ )++ mlp_spec = get_mlp_module_spec(+ use_te=False, num_experts=None, moe_grouped_gemm=False+ )+ qk_layernorm = bool(getattr(args, "qk_layernorm", False))++ layer_specs = [+ _lfm2_layer_spec(layer_type == "full_attention", mlp_spec, qk_layernorm)+ for layer_type in LFM2_LAYER_TYPES+ ]+ return TransformerBlockSubmodules(layer_specs=layer_specs, layer_norm=PTNorm)+++layer_spec = _build_lfm2_block_spec()@@ -3,6 +3,7 @@ """Pretrain GPT.""" import os+import sys from functools import partial from typing import Union @@ -307,3 +308,16 @@ def main(): if __name__ == "__main__": main()+ # Training, evaluation and checkpointing all completed inside pretrain().+ # Flush the log streams and exit the process immediately instead of+ # running the default interpreter shutdown, which spends many seconds+ # garbage-collecting the model and tearing the NPU runtime down. The OS+ # and the driver reclaim every process resource on exit anyway, and all+ # device work has already completed and been accounted for at this point.+ sys.stdout.flush()+ sys.stderr.flush()+ try:+ torch.npu.synchronize()+ except Exception:+ pass+ os._exit(0)