MiniMax M3 · Training

T05 · Training adapt

Correctness rejected

LFM2-1.2B model adapt training 1dev · Model Adaptation

—PERFORMANCE RATIO
365TOOL EVENTS
1TEXT PATCHES
0BINARY NAMES

01 / PROCESS MAP

Tool activity

Each row shows one agent’s tool events in its own recorded order. Colors show broad activities; bar widths do not represent duration.

Main agentMiniMax M3 · 365 visible calls

InspectEditValidateExecuteBuildProfileRollbackOther
200Inspect
28Edit
7Build
84Validate
22Execute
24Other

02 / EVENT SEQUENCE

Event timeline

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.

Show event timelineHide event timeline165 groups · 365 calls

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>.

Main agent

  1. Inspect · Task requirements

    Requested workspace inspection and file and log inspection related to task requirements.

    4 calls · #0001–#0004

    echo <val>ls -l -a <val> <n> > <path>Read <path>ls -l -a <path> <path> <path> <path> <path> <n> >& <path>
  2. Inspect · Source & workspace

    Requested workspace inspection and file and log inspection related to source & workspace.

    2 calls · #0005–#0006

    ls <path>echo <flag>ls <path> <n> >& <path>Read <path>
  3. Inspect · Benchmark & validation setup

    Requested file and log inspection related to benchmark & validation setup.

    1 call · #0007–#0007

    Read <path>
  4. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    2 calls · #0008–#0009

    Read <path>
  5. Inspect · Benchmark & validation setup

    Requested file and log inspection related to benchmark & validation setup.

    1 call · #0010–#0010

    Read <path>
  6. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0011–#0011

    Read <path>
  7. Inspect · Benchmark & validation setup

    Requested file and log inspection related to benchmark & validation setup.

    3 calls · #0012–#0014

    Read <path>
  8. Inspect · Task requirements

    Requested file and log inspection related to task requirements.

    2 calls · #0015–#0016

    Read <path>
  9. Inspect · Benchmark & validation setup

    Requested file and log inspection related to benchmark & validation setup.

    1 call · #0017–#0017

    Read <path>
  10. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    3 calls · #0018–#0020

    Read <path>
  11. Inspect · Task requirements

    Requested file and log inspection related to task requirements.

    1 call · #0021–#0021

    cat <path> <n> >& <path>echo <flag>
  12. Inspect · Source & workspace

    Requested workspace inspection related to source & workspace.

    1 call · #0022–#0022

    ls <path>echo <flag>ls <path> <n> >& <path>
  13. Inspect · Checkpoints & weight state

    Requested workspace inspection related to checkpoints & weight state.

    1 call · #0023–#0023

    ls <path>echo <flag>ls <path> <n> >& <path>
  14. Inspect · Source & workspace

    Requested workspace inspection and file and log inspection related to source & workspace.

    6 calls · #0024–#0029

    ls <path> <n> >& <path>echo <flag>ls <path>cat <path> <n> >& <path>head -n <n>
  15. Inspect · Attention kernels

    Requested file and log inspection related to attention kernels.

    1 call · #0030–#0030

    cat <path> <n> >& <path>head -n <n>
  16. Inspect · Checkpoints & weight state

    Requested workspace inspection and file and log inspection related to checkpoints & weight state.

    2 calls · #0031–#0032

    ls <path> <path> <n> >& <path>cat <path> <n> >& <path>head -n <n>
  17. Other · Source & workspace

    Requested task coordination related to source & workspace.

    2 calls · #0033–#0034

    Create task <task>
  18. Other · Convolution & sequence boundaries

    Requested task coordination related to convolution & sequence boundaries.

    1 call · #0035–#0035

    Create task <task>
  19. Other · Attention kernels

    Requested task coordination related to attention kernels.

    1 call · #0036–#0036

    Create task <task>
  20. Other · Source & workspace

    Requested task coordination related to source & workspace.

    1 call · #0037–#0037

    Create task <task>
  21. Other · Checkpoints & weight state

    Requested task coordination related to checkpoints & weight state.

    1 call · #0038–#0038

    Create task <task>
  22. Other · Source & workspace

    Requested task coordination related to source & workspace.

    1 call · #0039–#0039

    Create task <task>
  23. Validate · Benchmark & validation setup

    Requested task coordination related to benchmark & validation setup.

    1 call · #0040–#0040

    Create task <task>
  24. Other · Source & workspace

    Requested task coordination related to source & workspace.

    1 call · #0041–#0041

    Update task <task>
  25. Inspect · Source & workspace

    Requested workspace inspection, environment setup or inspection and source searches related to source & workspace.

    8 calls · #0042–#0049

    ls <path> <n> >& <path>echo <flag>echo <val>envgrep -E <val> <n> >& <path>head -n <n>
    2 more command sketches
    Read <path>python3 -c <script> <n> >& <path>
  26. Inspect · Dependencies & build setup

    Requested dependency and build commands, file and log inspection and workspace inspection related to dependencies & build setup.

    1 call · #0050–#0050

    pip show <val> <n> >& <path>head -n <n>find <path> -name <val> <n> > <path>
  27. Inspect · Source & workspace

    Requested workspace inspection related to source & workspace.

    1 call · #0051–#0051

    ls <path> <n> >& <path>
  28. Other · Source & workspace

    Requested task coordination related to source & workspace.

    1 call · #0052–#0052

    Update task <task>
  29. Inspect · Source & workspace

    Requested file and log inspection, source searches and workspace inspection related to source & workspace.

    10 calls · #0053–#0062

    Read <path>cat <path> <n> >& <path>head -n <n>grep -r -n <val> <path> <n> >& <path>echo <flag>ls <path> <n> >& <path>
    4 more command sketches
    grep -n <val> <path> <n> >& <path>sed -n <val>find <path> -name <val> <n> >& <path>grep -r -l -n <val> <path> <n> >& <path>
  30. Other · Source & workspace

    Requested task coordination related to source & workspace.

    3 calls · #0063–#0065

    Update task <task>
  31. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    2 calls · #0066–#0067

    cat <path> <n> >& <path>sed -n <val>head -n <n>
  32. Inspect · Attention kernels

    Requested source searches and file and log inspection related to attention kernels.

    1 call · #0068–#0068

    grep -n <val> <path> <n> >& <path>head -n <n>echo <flag>cat <path> <n> >& <path>
  33. Inspect · Source & workspace

    Requested source searches and file and log inspection related to source & workspace.

    1 call · #0069–#0069

    grep -n <val> <path> <n> >& <path>head -n <n>echo <flag>cat <path> <n> >& <path>sed -n <val>
  34. Inspect · Checkpoints & weight state

    Requested file and log inspection and source searches related to checkpoints & weight state.

    4 calls · #0070–#0073

    cat <path> <n> >& <path>head -n <n>grep -n <val> <path> <n> >& <path>echo <flag>wc -l <path>
  35. Inspect · Source & workspace

    Requested file and log inspection and source searches related to source & workspace.

    2 calls · #0074–#0075

    cat <path> <n> >& <path>sed -n <val>grep -n <val> <path> <n> >& <path>head -n <n>
  36. Build · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0076–#0076

    cat <path> <n> >& <path>sed -n <val>
  37. Inspect · Source & workspace

    Requested source searches, file and log inspection and workspace inspection related to source & workspace.

    4 calls · #0077–#0080

    grep -n <val> <path> <n> >& <path>head -n <n>echo <flag>cat <path> <n> >& <path>grep -r -n <val> <path> <n> >& <path>ls <path> <n> >& <path>
  38. Inspect · Attention kernels

    Requested source searches and file and log inspection related to attention kernels.

    1 call · #0081–#0081

    grep -n <val> <path> <n> >& <path>head -n <n>echo <flag>cat <path> <n> >& <path>
  39. Inspect · Source & workspace

    Requested workspace file updates and workspace inspection related to source & workspace.

    1 call · #0082–#0082

    mkdir -p <path>touch <path>ls <path>
  40. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0083–#0083

    Write <path>
  41. Edit · Convolution & sequence boundaries

    Requested code edits related to convolution & sequence boundaries.

    1 call · #0084–#0084

    Write <path>
  42. Inspect · Parallelism & communication

    Requested source searches and file and log inspection related to parallelism & communication.

    2 calls · #0085–#0086

    grep -n <val> <path> <n> >& <path>head -n <n>cat <path> <n> >& <path>sed -n <val>
  43. Edit · Convolution & sequence boundaries

    Requested code edits related to convolution & sequence boundaries.

    1 call · #0087–#0087

    Write <path>
  44. Other · Source & workspace

    Requested task coordination related to source & workspace.

    2 calls · #0088–#0089

    Update task <task>
  45. Inspect · Attention kernels

    Requested source searches and file and log inspection related to attention kernels.

    3 calls · #0090–#0092

    grep -n <val> <path> <n> >& <path>head -n <n>cat <path> <n> >& <path>sed -n <val>
  46. Edit · Attention kernels

    Requested code edits related to attention kernels.

    1 call · #0093–#0093

    Write <path>
  47. Inspect · Attention kernels

    Requested source searches and file and log inspection related to attention kernels.

    5 calls · #0094–#0098

    grep -n <val> <path> <n> >& <path>head -n <n>cat <path> <n> >& <path>sed -n <val>echo <flag>
  48. Edit · Attention kernels

    Requested code edits related to attention kernels.

    1 call · #0099–#0099

    Write <path>
  49. Inspect · Attention kernels

    Requested source searches and file and log inspection related to attention kernels.

    4 calls · #0100–#0103

    grep -n <val> <path> <n> >& <path>head -n <n>echo <flag>cat <path> <n> >& <path>sed -n <val>
  50. Inspect · Source & workspace

    Requested file and log inspection and source searches related to source & workspace.

    5 calls · #0104–#0108

    cat <path> <n> >& <path>sed -n <val>grep -n <val> <path> <n> >& <path>echo <flag>head -n <n>
  51. Inspect · Checkpoints & weight state

    Requested source searches and file and log inspection related to checkpoints & weight state.

    3 calls · #0109–#0111

    grep -r -n <val> <path> <n> >& <path>head -n <n>cat <path> <n> >& <path>sed -n <val>
  52. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0112–#0112

    Write <path>
  53. Inspect · Source & workspace

    Requested source searches and file and log inspection related to source & workspace.

    2 calls · #0113–#0114

    grep -n <val> <path> <n> >& <path>head -n <n>cat <path> <n> >& <path>sed -n <val>
  54. Inspect · Attention kernels

    Requested source searches and file and log inspection related to attention kernels.

    10 calls · #0115–#0124

    grep -n <val> <path> <n> >& <path>head -n <n>cat <path> <n> >& <path>sed -n <val>echo <flag>
  55. Edit · Attention kernels

    Requested code edits related to attention kernels.

    1 call · #0125–#0125

    Write <path>
  56. Inspect · Source & workspace

    Requested source searches and file and log inspection related to source & workspace.

    2 calls · #0126–#0127

    grep -r -n <val> <path> <n> >& <path>head -n <n>cat <path> <n> >& <path>sed -n <val>
  57. Edit · Source & workspace

    Requested code edits related to source & workspace.

    2 calls · #0128–#0129

    Edit <path>
  58. Inspect · Source & workspace

    Requested source searches and file and log inspection related to source & workspace.

    2 calls · #0130–#0131

    grep -n <val> <path> <n> >& <path>head -n <n>echo <flag>cat <path> <n> >& <path>sed -n <val>
  59. Inspect · Checkpoints & weight state

    Requested source searches and file and log inspection related to checkpoints & weight state.

    1 call · #0132–#0132

    grep -n <val> <path> <n> >& <path>echo <flag>cat <path> <n> >& <path>sed -n <val>
  60. Inspect · Source & workspace

    Requested source searches and file and log inspection related to source & workspace.

    2 calls · #0133–#0134

    grep -n <val> <path> <n> >& <path>head -n <n>Read <path>
  61. Other · Source & workspace

    Requested task coordination related to source & workspace.

    2 calls · #0135–#0136

    Update task <task>
  62. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0137–#0137

    Write <path>
  63. Inspect · Source & workspace

    Requested source searches and file and log inspection related to source & workspace.

    10 calls · #0138–#0147

    grep -n <val> <path> <n> >& <path>echo <flag>cat <path> <n> >& <path>sed -n <val>grep -r -n <val> <path> <n> >& <path>head -n <n>
    1 more command sketches
    grep -r -n <val> <path> <path> <n> >& <path>
  64. Other · Source & workspace

    Requested workspace file updates related to source & workspace.

    1 call · #0148–#0148

    rm <path>
  65. Edit · Source & workspace

    Requested code edits related to source & workspace.

    2 calls · #0149–#0150

    Write <path>
  66. Inspect · Source & workspace

    Requested file and log inspection and source searches related to source & workspace.

    3 calls · #0151–#0153

    cat <path> <n> >& <path>head -n <n>grep -n <val> <path> <n> >& <path>echo <flag>sed -n <val>
  67. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0154–#0154

    Write <path>
  68. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0155–#0155

    cat <path> <n> >& <path>sed -n <val>
  69. Edit · Source & workspace

    Requested code edits related to source & workspace.

    2 calls · #0156–#0157

    Edit <path>
  70. Inspect · Source & workspace

    Requested file and log inspection, source searches and environment setup or inspection related to source & workspace.

    7 calls · #0158–#0164

    cat <path> <n> >& <path>head -n <n>grep -n <val> <path> <n> >& <path>cd <path>env <vars> python3 -c <script> <n> >& <path>tail -n <n>
    4 more command sketches
    python3 -c <script> <n> >& <path>echo <flag>find <path> -name <val> -type <val> <n> > <path>find <path> -name <val> <n> > <path>
  71. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0165–#0165

    Edit <path>
  72. Inspect · Source & workspace

    Requested environment setup or inspection and file and log inspection related to source & workspace.

    1 call · #0166–#0166

    env <vars> python3 -c <script> <n> >& <path>tail -n <n>
  73. Build · Attention kernels

    Requested environment setup or inspection related to attention kernels.

    4 calls · #0167–#0170

    env <vars> python3 <script>
  74. Inspect · Attention kernels

    Requested source searches and file and log inspection related to attention kernels.

    2 calls · #0171–#0172

    grep -n <val> <path> <n> >& <path>head -n <n>echo <flag>
  75. Build · Attention kernels

    Requested environment setup or inspection related to attention kernels.

    1 call · #0173–#0173

    env <vars> python3 <script>
  76. Inspect · Attention kernels

    Requested environment setup or inspection related to attention kernels.

    1 call · #0174–#0174

    env <vars> python3 <script>
  77. Inspect · Source & workspace

    Requested source searches and file and log inspection related to source & workspace.

    1 call · #0175–#0175

    grep -n <val> <path> <n> >& <path>head -n <n>echo <flag>cat <path> <n> >& <path>
  78. Build · Attention kernels

    Requested environment setup or inspection related to attention kernels.

    1 call · #0176–#0176

    env <vars> python3 <script>
  79. Other · Source & workspace

    Requested task coordination related to source & workspace.

    2 calls · #0177–#0178

    Update task <task>
  80. Inspect · Source & workspace

    Requested workspace inspection, environment setup or inspection and script or workload execution related to source & workspace.

    2 calls · #0179–#0180

    echo <val>cd <path>ls <val> <n> >& <path>echo <flag>export <vars>bash <script> <n> >& <path>
    1 more command sketches
    tail -n <n>
  81. Validate · Benchmark & validation setup

    Requested environment setup or inspection, script or workload execution and file and log inspection related to benchmark & validation setup.

    1 call · #0181–#0181

    export <vars>timeout <n> <val> <path> <n> >& <path>tail -n <n>
  82. Other · Source & workspace

    Requested task coordination related to source & workspace.

    1 call · #0182–#0182

    Update task <task>
  83. Inspect · Checkpoints & weight state

    Requested workspace file updates, workspace inspection and source searches related to checkpoints & weight state.

    6 calls · #0183–#0188

    touch <path> <n> >& <path>ls <path>grep -r -n <val> <path> <n> >& <path>head -n <n>echo <flag>cat <path> <n> >& <path>
  84. Edit · Checkpoints & weight state

    Requested code edits related to checkpoints & weight state.

    1 call · #0189–#0189

    Write <path>
  85. Inspect · Checkpoints & weight state

    Requested source searches and file and log inspection related to checkpoints & weight state.

    3 calls · #0190–#0192

    grep -n <val> <path> <n> >& <path>head -n <n>cat <path> <n> >& <path>sed -n <val>
  86. Inspect · Optimizer & gradients

    Requested source searches and file and log inspection related to optimizer & gradients.

    1 call · #0193–#0193

    grep -n <val> <path> <n> >& <path>head -n <n>
  87. Inspect · Source & workspace

    Requested file and log inspection and source searches related to source & workspace.

    2 calls · #0194–#0195

    cat <path> <n> >& <path>sed -n <val>grep -n <val> <path> <n> >& <path>head -n <n>echo <flag>grep -n <flag> <args>
  88. Inspect · Checkpoints & weight state

    Requested source searches and file and log inspection related to checkpoints & weight state.

    9 calls · #0196–#0204

    grep -n <val> <path> <n> >& <path>head -n <n>cat <path> <n> >& <path>sed -n <val>echo <flag>grep -n <flag> <args>
  89. Edit · Checkpoints & weight state

    Requested code edits related to checkpoints & weight state.

    1 call · #0205–#0205

    Edit <path>
  90. Validate · Benchmark & validation setup

    Requested environment setup or inspection, script or workload execution and file and log inspection related to benchmark & validation setup.

    1 call · #0206–#0206

    export <vars>timeout <n> <val> <path> <n> >& <path>tail -n <n>
  91. Inspect · Source & workspace

    Requested workspace inspection and file and log inspection related to source & workspace.

    1 call · #0207–#0207

    ls -l -a <path> <n> >& <path>tail -n <n>
  92. Validate · Benchmark & validation setup

    Requested file and log inspection and workspace inspection related to benchmark & validation setup.

    3 calls · #0208–#0210

    cat <path> <n> >& <path>tail -n <n>echo <flag>ls <path> <n> >& <path>
  93. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0211–#0211

    Edit <path>
  94. Validate · Benchmark & validation setup

    Requested environment setup or inspection, script or workload execution and execution waits related to benchmark & validation setup.

    3 calls · #0212–#0214

    export <vars>bash <script> <n> >& <path> > <path>echo <val>sleep <n>cat <path> <n> >& <path>tail -n <n>
    1 more command sketches
    python3 -c <script> <n> >& <path>
  95. Inspect · Source & workspace

    Requested workspace file updates and workspace inspection related to source & workspace.

    1 call · #0215–#0215

    rm -f <path> <path> <n> >& <path>ls <path> <n> >& <path>
  96. Validate · Benchmark & validation setup

    1 tool error

    Requested environment setup or inspection, script or workload execution and execution waits related to benchmark & validation setup.

    3 calls · #0216–#0218

    export <vars>bash <script> > <path> <n> >& <path>echo <val>sleep <n>cat <path> <n> >& <path>python3 -c <script> <n> >& <path>
    2 more command sketches
    echo <flag>ls <path> <n> >& <path>
  97. Edit · Attention kernels

    1 tool error

    Requested code edits related to attention kernels.

    1 call · #0219–#0219

    Edit <path>
  98. Inspect · Attention kernels

    Requested file and log inspection related to attention kernels.

    1 call · #0220–#0220

    Read <path>
  99. Edit · Attention kernels

    Requested code edits related to attention kernels.

    1 call · #0221–#0221

    Edit <path>
  100. Validate · Benchmark & validation setup

    1 tool error

    Requested workspace file updates, environment setup or inspection and script or workload execution related to benchmark & validation setup.

    8 calls · #0222–#0229

    rm -f <path> <path> <n> >& <path>export <vars>bash <script> > <path> <n> >& <path>echo <val>sleep <n>cat <path> <n> >& <path>
    7 more command sketches
    python3 -c <script> <n> >& <path>ls <path> <n> >& <path>echo <flag>head -n <n>tail -n <n>grep -i -E <val>tail -n <n> <path> <n> >& <path>
  101. Edit · Attention kernels

    Requested code edits related to attention kernels.

    2 calls · #0230–#0231

    Edit <path>
  102. Validate · Benchmark & validation setup

    1 tool error

    Requested workspace file updates, environment setup or inspection and script or workload execution related to benchmark & validation setup.

    12 calls · #0232–#0243

    rm -f <path> <path> <n> >& <path>export <vars>bash <script> > <path> <n> >& <path>echo <val>sleep <n>tail -n <n> <path> <n> >& <path>
    13 more command sketches
    cat <path> <n> >& <path>grep -i -E <val>tail -n <n>python3 -c <script> <n> >& <path>ls <path> <n> >& <path>echo <flag>grep -n -E <val> <path> <n> >& <path>wc -l <path> <n> >& <path>sed -n <val>grep -n <val> <path>head -n <n>ls -l -a <path> <n> >& <path>grep -n <val> <path> <n> >& <path>
  103. Edit · Checkpoints & weight state

    Requested code edits related to checkpoints & weight state.

    1 call · #0244–#0244

    Edit <path>
  104. Inspect · Source & workspace

    Requested source searches and file and log inspection related to source & workspace.

    2 calls · #0245–#0246

    grep -n <val> <path> <n> >& <path>head -n <n>cat <path> <n> >& <path>sed -n <val>
  105. Validate · Benchmark & validation setup

    1 tool error

    Requested workspace file updates, environment setup or inspection and script or workload execution related to benchmark & validation setup.

    5 calls · #0247–#0251

    rm -f <path> <path> <n> >& <path>export <vars>bash <script> > <path> <n> >& <path>echo <val>sleep <n>cat <path> <n> >& <path>
    6 more command sketches
    grep -i -E <val>tail -n <n>grep -E <val>grep -v <val>grep -A <n> <val> <path> <n> >& <path>grep -B <n> <val> <path> <n> >& <path>
  106. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0252–#0252

    Edit <path>
  107. Validate · Benchmark & validation setup

    1 tool error

    Requested workspace file updates, environment setup or inspection and script or workload execution related to benchmark & validation setup.

    5 calls · #0253–#0257

    rm -f <path> <path> <n> >& <path>export <vars>bash <script> > <path> <n> >& <path>echo <val>sleep <n>cat <path> <n> >& <path>
    4 more command sketches
    grep -A <n> <val>tail -n <n>echo <flag>ls -l -a <path> <n> >& <path>
  108. Inspect · Attention kernels

    Requested source searches and file and log inspection related to attention kernels.

    2 calls · #0258–#0259

    grep -n <val> <path> <n> >& <path>head -n <n>cat <path> <n> >& <path>sed -n <val>
  109. Edit · Attention kernels

    Requested code edits related to attention kernels.

    1 call · #0260–#0260

    Edit <path>
  110. Validate · Benchmark & validation setup

    2 tool errors

    Requested workspace file updates, environment setup or inspection and script or workload execution related to benchmark & validation setup.

    12 calls · #0261–#0272

    rm -f <path> <path> <n> >& <path>export <vars>bash <script> > <path> <n> >& <path>echo <val>sleep <n>ls <path> <n> >& <path>
    15 more command sketches
    echo <flag>cat <path> <n> >& <path>python3 -c <script> <n> >& <path>grep -i -E <val>tail -n <n>wc -chead -n <n> <path> <n> >& <path>tail -n <n> <path> <n> >& <path>grep -E <val> <path> <n> >& <path>head -n <n>ls <path>grep -E <val>wc -l <path> <path> <n> >& <path>pgrep <flag> <args>ls -l -a <path> <n> >& <path>
  111. Inspect · Runtime processes

    Requested execution waits, workspace inspection and runtime inspection related to runtime processes.

    1 call · #0273–#0273

    sleep <n>ls <path> <n> >& <path>echo <flag>pgrep <flag> <args>head -n <n>
  112. Validate · Benchmark & validation setup

    Requested file and log inspection and script or workload execution related to benchmark & validation setup.

    1 call · #0274–#0274

    cat <path> <n> >& <path>python3 -c <script> <n> >& <path>
  113. Other · Source & workspace

    Requested task coordination related to source & workspace.

    3 calls · #0275–#0277

    Update task <task>
  114. Validate · Benchmark & validation setup

    Requested workspace file updates, environment setup or inspection and script or workload execution related to benchmark & validation setup.

    1 call · #0278–#0278

    rm -f <path> <path> <n> >& <path>export <vars>bash <script> > <path> <n> >& <path>echo <val>
  115. Validate · Precision & numerical checks

    Requested execution waits, file and log inspection and source searches related to precision & numerical checks.

    1 call · #0279–#0279

    sleep <n>cat <path> <n> >& <path>grep -i -E <val>tail -n <n>
  116. Validate · Benchmark & validation setup

    1 tool error

    Requested file and log inspection and script or workload execution related to benchmark & validation setup.

    1 call · #0280–#0280

    cat <path> <n> >& <path>python3 -c <script> <n> >& <path>
  117. Inspect · Runtime processes

    Requested workspace inspection, runtime inspection and file and log inspection related to runtime processes.

    1 call · #0281–#0281

    ls -l -a <path> <n> >& <path>echo <flag>pgrep <flag> <args>head -n <n>
  118. Validate · Benchmark & validation setup

    Requested file and log inspection related to benchmark & validation setup.

    1 call · #0282–#0282

    cat <path> <n> >& <path>echo <flag>
  119. Inspect · Runtime processes

    Requested workspace inspection, runtime inspection and file and log inspection related to runtime processes.

    1 call · #0283–#0283

    ls -l -a <path> <n> >& <path>echo <flag>pgrep <flag> <args>head -n <n>
  120. Validate · Benchmark & validation setup

    2 tool errors

    Requested execution waits, workspace inspection and runtime inspection related to benchmark & validation setup.

    3 calls · #0284–#0286

    sleep <n>ls -l -a <path> <n> >& <path>echo <flag>pgrep <flag> <args>head -n <n>cat <path> <n> >& <path>
    2 more command sketches
    tail -n <n>python3 -c <script> <n> >& <path>
  121. Inspect · Runtime processes

    Requested workspace inspection, runtime inspection and file and log inspection related to runtime processes.

    1 call · #0287–#0287

    ls <path> <n> >& <path>echo <flag>pgrep <flag> <args>head -n <n>
  122. Validate · Benchmark & validation setup

    2 tool errors

    Requested source searches, file and log inspection and workspace inspection related to benchmark & validation setup.

    6 calls · #0288–#0293

    grep -E <val> <path> <n> >& <path>grep -E <val>tail -n <n>echo <flag>ls -l -a <path> <n> >& <path>tail -n <n> <path> <n> >& <path>
    7 more command sketches
    cat <path> <n> >& <path>python3 -c <script> <n> >& <path>rm -f <path> <path> <n> >& <path>export <vars>bash <script> > <path> <n> >& <path>echo <val>sleep <n>
  123. Inspect · Runtime processes

    Requested workspace inspection, runtime inspection and file and log inspection related to runtime processes.

    1 call · #0294–#0294

    ls <path> <n> >& <path>echo <flag>pgrep <flag> <args>head -n <n>
  124. Validate · Benchmark & validation setup

    Requested file and log inspection, workspace inspection and runtime inspection related to benchmark & validation setup.

    1 call · #0295–#0295

    cat <path> <n> >& <path>head -n <n>echo <flag>ls -l -a <path> <n> >& <path>pgrep <flag> <args>
  125. Inspect · Source & workspace

    Requested file and log inspection and workspace inspection related to source & workspace.

    1 call · #0296–#0296

    cat <path> <n> >& <path>tail -n <n>echo <flag>ls <path> <n> >& <path>
  126. Validate · Benchmark & validation setup

    1 tool error

    Requested execution waits, file and log inspection and script or workload execution related to benchmark & validation setup.

    1 call · #0297–#0297

    sleep <n>cat <path> <n> >& <path>python3 -c <script> <n> >& <path>
  127. Inspect · Runtime processes

    Requested workspace inspection, runtime inspection and file and log inspection related to runtime processes.

    1 call · #0298–#0298

    ls <path> <n> >& <path>echo <flag>pgrep <flag> <args>head -n <n>
  128. Validate · Benchmark & validation setup

    1 tool error

    Requested execution waits, file and log inspection and script or workload execution related to benchmark & validation setup.

    1 call · #0299–#0299

    sleep <n>cat <path> <n> >& <path>python3 -c <script> <n> >& <path>
  129. Inspect · Runtime processes

    Requested workspace inspection, runtime inspection and file and log inspection related to runtime processes.

    1 call · #0300–#0300

    ls <path> <n> >& <path>echo <flag>pgrep <flag> <args>head -n <n>
  130. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0301–#0301

    Read <path>
  131. Validate · Benchmark & validation setup

    Requested file and log inspection related to benchmark & validation setup.

    1 call · #0302–#0302

    cat <path> <n> >& <path>head -n <n>echo <flag>tail -n <n>
  132. Inspect · Benchmark & validation setup

    Requested workspace inspection, file and log inspection and runtime inspection related to benchmark & validation setup.

    1 call · #0303–#0303

    ls -l -a <path> <n> >& <path>echo <flag>cat <path> <n> >& <path>pgrep <flag> <args>
  133. Validate · Benchmark & validation setup

    Requested file and log inspection related to benchmark & validation setup.

    1 call · #0304–#0304

    cat <path> <n> >& <path>
  134. Inspect · Runtime processes

    Requested runtime inspection, file and log inspection and workspace inspection related to runtime processes.

    1 call · #0305–#0305

    pgrep <flag> <args>head -n <n>echo <flag>ls <path>sort
  135. Validate · Benchmark & validation setup

    1 tool error

    Requested execution waits, file and log inspection and script or workload execution related to benchmark & validation setup.

    1 call · #0306–#0306

    sleep <n>cat <path> <n> >& <path>python3 -c <script> <n> >& <path>echo <flag>ls -l -a <path>sort
  136. Inspect · Benchmark & validation setup

    Requested workspace inspection, runtime inspection and file and log inspection related to benchmark & validation setup.

    1 call · #0307–#0307

    ls -l -a <path> <n> >& <path>sortecho <flag>pgrep <flag> <args>head -n <n>
  137. Validate · Benchmark & validation setup

    Requested file and log inspection, script or workload execution and source searches related to benchmark & validation setup.

    2 calls · #0308–#0309

    cat <path> <n> >& <path>python3 -c <script> <n> >& <path>grep <val> <path> <n> >& <path>head -n <n>
  138. Inspect · Attention kernels

    Requested source searches and file and log inspection related to attention kernels.

    1 call · #0310–#0310

    grep -n <val> <path> <n> >& <path>head -n <n>echo <flag>
  139. Inspect · Source & workspace

    Requested source searches and file and log inspection related to source & workspace.

    1 call · #0311–#0311

    grep -n <val> <path> <n> >& <path>head -n <n>echo <flag>grep -B <n> -A <n> <val> <path> <n> >& <path>
  140. Inspect · Attention kernels

    Requested source searches and file and log inspection related to attention kernels.

    4 calls · #0312–#0315

    grep -n <val> <path> <n> >& <path>head -n <n>grep -r -n <val> <path> <n> >& <path>grep -n <val> <path> <n> >& <path> -r -n
  141. Inspect · Source & workspace

    Requested file and log inspection, workspace inspection and source searches related to source & workspace.

    7 calls · #0316–#0322

    cat <path> <n> >& <path>head -n <n>find <path> -name <val> -type <val> <n> >& <path>grep -n <val> <path> <n> >& <path>sed -n <val>echo <flag>
  142. Execute · Benchmark & validation setup

    1 tool error

    Requested workspace file updates, environment setup or inspection and script or workload execution related to benchmark & validation setup.

    5 calls · #0323–#0327

    rm -f <path> <path> <n> >& <path>export <vars>bash <script> > <path> <n> >& <path>echo <val>sleep <n>grep -E <val> <path> <path> <n> >& <path>
    9 more command sketches
    tail -n <n>echo <flag>ls <path>pgrep <flag> <args>head -n <n>tail -n <n> <path> <n> >& <path>cat <path> <n> >& <path>ls -l -a <path>sort
  143. Inspect · Runtime processes

    Requested runtime inspection and file and log inspection related to runtime processes.

    1 call · #0328–#0328

    pgrep <flag> <args>head -n <n>echo <flag>
  144. Execute · Benchmark & validation setup

    2 tool errors

    Requested execution waits, file and log inspection and script or workload execution related to benchmark & validation setup.

    4 calls · #0329–#0332

    sleep <n>cat <path> <n> >& <path>python3 -c <script> <n> >& <path>ls -l -a <path> <n> >& <path>sortecho <flag>
    4 more command sketches
    pgrep <flag> <args>head -n <n>grep -E <val> <path> <n> >& <path>tail -n <n>
  145. Inspect · Runtime processes

    Requested workspace inspection, runtime inspection and file and log inspection related to runtime processes.

    1 call · #0333–#0333

    ls <path> <n> >& <path>echo <flag>pgrep <flag> <args>head -n <n>
  146. Execute · Benchmark & validation setup

    Requested execution waits, file and log inspection and script or workload execution related to benchmark & validation setup.

    2 calls · #0334–#0335

    sleep <n>cat <path> <n> >& <path>python3 -c <script> <n> >& <path>
  147. Other · Source & workspace

    Requested task coordination related to source & workspace.

    1 call · #0336–#0336

    Update task <task>
  148. Validate · Benchmark & validation setup

    2 tool errors

    Requested workspace file updates, environment setup or inspection and script or workload execution related to benchmark & validation setup.

    3 calls · #0337–#0339

    rm -f <path> <path> <n> >& <path>export <vars>bash <script> > <path> <n> >& <path>echo <val>sleep <n>cat <path> <n> >& <path>
    1 more command sketches
    python3 -c <script> <n> >& <path>
  149. Inspect · Runtime processes

    Requested workspace inspection, runtime inspection and file and log inspection related to runtime processes.

    1 call · #0340–#0340

    ls <path> <n> >& <path>echo <flag>pgrep <flag> <args>head -n <n>
  150. Validate · Benchmark & validation setup

    1 tool error

    Requested execution waits, file and log inspection and script or workload execution related to benchmark & validation setup.

    1 call · #0341–#0341

    sleep <n>cat <path> <n> >& <path>python3 -c <script> <n> >& <path>
  151. Inspect · Runtime processes

    Requested workspace inspection, runtime inspection and file and log inspection related to runtime processes.

    1 call · #0342–#0342

    ls <path> <n> >& <path>echo <flag>pgrep <flag> <args>head -n <n>
  152. Validate · Benchmark & validation setup

    1 tool error

    Requested execution waits, file and log inspection and script or workload execution related to benchmark & validation setup.

    1 call · #0343–#0343

    sleep <n>cat <path> <n> >& <path>python3 -c <script> <n> >& <path>
  153. Inspect · Runtime processes

    Requested workspace inspection, runtime inspection and file and log inspection related to runtime processes.

    1 call · #0344–#0344

    ls <path> <n> >& <path>echo <flag>pgrep <flag> <args>head -n <n>
  154. Validate · Benchmark & validation setup

    Requested file and log inspection and script or workload execution related to benchmark & validation setup.

    1 call · #0345–#0345

    cat <path> <n> >& <path>python3 -c <script> <n> >& <path>
  155. Inspect · Source & workspace

    Requested source searches and file and log inspection related to source & workspace.

    1 call · #0346–#0346

    grep -n <val> <path> <n> >& <path>head -n <n>
  156. Validate · Benchmark & validation setup

    Requested file and log inspection, script or workload execution and workspace inspection related to benchmark & validation setup.

    2 calls · #0347–#0348

    echo <val>cat <path> <n> >& <path>python3 -c <script>ls <path> <n> >& <path>echo <flag>
  157. Execute · Benchmark & validation setup

    2 tool errors

    Requested workspace file updates, environment setup or inspection and script or workload execution related to benchmark & validation setup.

    7 calls · #0349–#0355

    rm -f <path> <path> <n> >& <path>export <vars>bash <script> > <path> <n> >& <path>echo <val>sleep <n>ls <path> <n> >& <path>
    8 more command sketches
    sortecho <flag>grep -E <path> <path> <n> >& <path>head -n <n>ls -l -a <path>cat <path> <n> >& <path>python3 -c <script>pgrep <flag> <args>
  158. Inspect · Runtime processes

    Requested workspace inspection, runtime inspection and file and log inspection related to runtime processes.

    1 call · #0356–#0356

    ls -l -a <path> <n> >& <path>echo <flag>pgrep <flag> <args>head -n <n>
  159. Execute · Benchmark & validation setup

    2 tool errors

    Requested execution waits, file and log inspection and script or workload execution related to benchmark & validation setup.

    3 calls · #0357–#0359

    sleep <n>cat <path> <n> >& <path>python3 -c <script>ls -l -a <path> <n> >& <path>echo <flag>pgrep <flag> <args>
    1 more command sketches
    head -n <n>
  160. Inspect · Runtime processes

    Requested workspace inspection, runtime inspection and file and log inspection related to runtime processes.

    1 call · #0360–#0360

    ls -l -a <path> <n> >& <path>sortecho <flag>pgrep <flag> <args>head -n <n>
  161. Execute · Benchmark & validation setup

    Requested file and log inspection and script or workload execution related to benchmark & validation setup.

    1 call · #0361–#0361

    cat <path> <n> >& <path>python3 -c <script>
  162. Edit · Device memory

    Requested code edits related to device memory.

    1 call · #0362–#0362

    Write <path>
  163. Inspect · Device memory

    1 tool error

    Requested file and log inspection related to device memory.

    1 call · #0363–#0363

    Read <path>
  164. Edit · Device memory

    Requested code edits related to device memory.

    1 call · #0364–#0364

    Write <path>
  165. Inspect · Source & workspace

    Requested repository inspection and file and log inspection related to source & workspace.

    1 call · #0365–#0365

    cd <path>git status --short <n> >& <path>head -n <n>

03 / CANDIDATE ARTIFACT

Text patches & binary names

Read code changes as Git diffs. Identifying strings are masked; binary files are listed by their full relative names.

mindspeed_llm · 6 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..746d7f7a93e0fbaded9451fbea6e5996d4296da4--- /dev/null+++ b/mindspeed_llm/core/models/lfm2/__init__.py@@ -0,0 +1,17 @@+# Copyright (c) 2026, HUAWEI CORPORATION.  All rights reserved.++from .short_conv import Lfm2ShortConv, Lfm2ShortConvSubmodules+from .lfm2_attention import Lfm2Attention, Lfm2AttentionSubmodules+from .lfm2_transformer_layer import (+    Lfm2TransformerLayer,+    Lfm2TransformerLayerSubmodules,+)++__all__ = [+    "Lfm2ShortConv",+    "Lfm2ShortConvSubmodules",+    "Lfm2Attention",+    "Lfm2AttentionSubmodules",+    "Lfm2TransformerLayer",+    "Lfm2TransformerLayerSubmodules",+]diff --git a/mindspeed_llm/core/models/lfm2/lfm2_attention.py b/mindspeed_llm/core/models/lfm2/lfm2_attention.pynew file mode 100644index 0000000000000000000000000000000000000000..e34f390ac30c4f4e014ca1e25af3a5f288f33424--- /dev/null+++ b/mindspeed_llm/core/models/lfm2/lfm2_attention.py@@ -0,0 +1,242 @@+# Copyright (c) 2026, HUAWEI CORPORATION.  All rights reserved.+"""LFM2 grouped-query self-attention.++The LFM2 attention block projects the hidden states into ``q``, ``k`` and ``v``+with three column-parallel projections, applies a per-head RMSNorm to ``q`` and+``k``, runs causal grouped-query attention, and finally projects back through a+row-parallel linear.+"""++from dataclasses import dataclass+from typing import Optional, Tuple, Union++import torch+from torch import Tensor++from megatron.core import parallel_state+from megatron.core.models.common.embeddings.rope_utils import apply_rotary_pos_emb+from megatron.core.packed_seq_params import PackedSeqParams+from megatron.core.transformer.attention import Attention+from megatron.core.transformer.attention import SelfAttentionSubmodules+from megatron.core.transformer.spec_utils import ModuleSpec, build_module+from megatron.core.transformer.transformer_config import TransformerConfig+from megatron.core.transformer.enums import AttnMaskType+from megatron.core.transformer.identity_op import IdentityOp+++@dataclass+class Lfm2AttentionSubmodules:+    """Submodules for the LFM2 self-attention block."""++    linear_q: Union[ModuleSpec, type] = None+    linear_k: Union[ModuleSpec, type] = None+    linear_v: Union[ModuleSpec, type] = None+    core_attention: Union[ModuleSpec, type] = None+    linear_proj: Union[ModuleSpec, type] = None+    q_layernorm: Union[ModuleSpec, type] = None+    k_layernorm: Union[ModuleSpec, type] = None+++class Lfm2Attention(Attention):+    """Self-attention layer tailored to the LFM2 architecture.++    The layer projects the hidden states into ``q``, ``k`` and ``v`` with three+    separate column-parallel projections (instead of ``linear_qkv``), applies a+    per-head RMSNorm to ``q`` and ``k``, runs causal grouped-query attention,+    and finally projects back through a row-parallel linear.+    """++    def __init__(+        self,+        config: TransformerConfig,+        submodules: Lfm2AttentionSubmodules,+        layer_number: int,+        attn_mask_type=AttnMaskType.causal,+        cp_comm_type: Optional[str] = None,+    ):+        # ``Attention`` is the MCore base class. ``linear_qkv`` is supplied as+        # a no-op so the parent's constructor runs unchanged; the three+        # independent projections are built below.+        base_submodules = SelfAttentionSubmodules(+            linear_qkv=IdentityOp(),+            linear_proj=submodules.linear_proj,+            core_attention=submodules.core_attention,+        )+        super().__init__(+            config=config,+            submodules=base_submodules,+            layer_number=layer_number,+            attn_mask_type=attn_mask_type,+            attention_type="self",+            cp_comm_type=cp_comm_type,+        )++        self.head_dim = getattr(+            self.config, "kv_channels",+            self.config.hidden_size // self.config.num_attention_heads,+        )+        self.num_heads = self.config.num_attention_heads+        self.num_query_groups = getattr(self.config, "num_query_groups", self.num_heads)+        assert self.num_heads % self.num_query_groups == 0, (+            "num_attention_heads must be divisible by num_query_groups for "+            "LFM2 grouped-query attention"+        )+        self.num_kv_heads = (+            self.num_query_groups+            if getattr(self.config, "group_query_attention", False)+            else self.num_heads+        )+        self.query_projection_size = self.num_heads * self.head_dim+        self.kv_projection_size = self.num_kv_heads * self.head_dim+        self.scaling = self.head_dim ** -0.5++        # Three independent column-parallel projections. ``gather_output=False``+        # keeps the output distributed across the tensor-parallel ranks.+        self.q_proj = build_module(+            submodules.linear_q,+            self.config.hidden_size,+            self.query_projection_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,+            tp_comm_buffer_name="lfm2_q_proj",+        )+        self.k_proj = build_module(+            submodules.linear_k,+            self.config.hidden_size,+            self.kv_projection_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,+            tp_comm_buffer_name="lfm2_k_proj",+        )+        self.v_proj = build_module(+            submodules.linear_v,+            self.config.hidden_size,+            self.kv_projection_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,+            tp_comm_buffer_name="lfm2_v_proj",+        )++        if submodules.q_layernorm is not None:+            self.q_layernorm = build_module(+                submodules.q_layernorm,+                hidden_size=self.head_dim,+                config=self.config,+                eps=self.config.layernorm_epsilon,+            )+        else:+            self.q_layernorm = None++        if submodules.k_layernorm is not None:+            self.k_layernorm = build_module(+                submodules.k_layernorm,+                hidden_size=self.head_dim,+                config=self.config,+                eps=self.config.layernorm_epsilon,+            )+        else:+            self.k_layernorm = None++    def get_query_key_value_tensors(+        self, hidden_states: Tensor, key_value_states: Optional[Tensor] = None+    ) -> Tuple[Tensor, Tensor, Tensor]:+        """Return ``(query, key, value)`` in MCore ``[S, B, N, H]`` layout.++        Implements the abstract base-class hook so the layer instantiates.+        ``key_value_states`` is ignored - LFM2 only supports self attention.+        The per-head RMSNorms (``qk_layernorm``) are applied here so they+        hook into the standard MCore fast paths.+        """+        del key_value_states+        query, _ = self.q_proj(hidden_states)+        key, _ = self.k_proj(hidden_states)+        value, _ = self.v_proj(hidden_states)++        sq, bq, _ = query.shape+        query = query.view(sq, bq, self.num_heads, self.head_dim)+        key = key.view(sq, bq, self.num_kv_heads, self.head_dim)+        value = value.view(sq, bq, self.num_kv_heads, self.head_dim)++        if getattr(self.config, "qk_layernorm", False) and self.q_layernorm is not None:+            query = self.q_layernorm(query)+        if getattr(self.config, "qk_layernorm", False) and self.k_layernorm is not None:+            key = self.k_layernorm(key)+        return query, key, value++    def forward(+        self,+        hidden_states: Tensor,+        attention_mask: Tensor,+        key_value_states: Optional[Tensor] = None,+        inference_context=None,+        rotary_pos_emb: Optional[Tensor] = None,+        rotary_pos_cos: Optional[Tensor] = None,+        rotary_pos_sin: Optional[Tensor] = None,+        attention_bias: Optional[Tensor] = None,+        packed_seq_params: Optional[PackedSeqParams] = None,+        sequence_len_offset: Optional[Tensor] = None,+        *,+        inference_params=None,+    ) -> Tuple[Tensor, Optional[Tensor]]:+        """Apply LFM2 self-attention.++        Args:+            hidden_states: Tensor shaped ``[S, B, D]``.++        Returns:+            Tuple ``(output, bias)`` where ``output`` is ``[S, B, D]`` and+            ``bias`` is the residual bias of the output linear.+        """+        query, key, value = self.get_query_key_value_tensors(hidden_states)+        sq, bq, _, _ = query.shape++        # Apply rotary embeddings. MCore passes a packed ``rotary_pos_emb``+        # (``[S, 1, 1, H]``) when RoPE fusion is enabled, and separate+        # ``rotary_pos_cos``/``rotary_pos_sin`` (``[S, ..., H/2]``) when the+        # cos/sin path is used; we support both through the public API.+        if rotary_pos_cos is not None and rotary_pos_sin is not None:+            from megatron.core.models.common.embeddings.rope_utils import (+                apply_rotary_pos_emb_with_cos_sin,+            )+            query, key = apply_rotary_pos_emb_with_cos_sin(+                query, key, rotary_pos_cos, rotary_pos_sin+            )+        elif rotary_pos_emb is not None:+            # MCore's ``apply_rotary_pos_emb`` expects the rotary tensor in+            # MCore's standard ``[S, 1, 1, H]`` layout, which is exactly the+            # layout produced by ``RotaryEmbedding.forward``. Forward it+            # unchanged and let the kernel handle the broadcast.+            rp = rotary_pos_emb.to(query.dtype)+            if rp.dim() != 4:+                raise ValueError(+                    f"Expected rotary_pos_emb to have 4 dims (got {rp.dim()})"+                )+            query = apply_rotary_pos_emb(query.contiguous(), rp, self.config)+            key = apply_rotary_pos_emb(key.contiguous(), rp, self.config)++        # ``core_attention`` returns ``[S, B, N, H]``; reshape to ``[S, B, N*H]``+        # for the row-parallel ``linear_proj``.+        core_output = self.core_attention(+            query,+            key,+            value,+            attention_mask=attention_mask,+            attn_mask_type=self.attn_mask_type,+            packed_seq_params=packed_seq_params,+            attention_bias=attention_bias,+        )+        core_output = core_output.contiguous().view(sq, bq, -1)+        output, bias = self.linear_proj(core_output)+        return output, biasdiff --git a/mindspeed_llm/core/models/lfm2/lfm2_transformer_layer.py b/mindspeed_llm/core/models/lfm2/lfm2_transformer_layer.pynew file mode 100644index 0000000000000000000000000000000000000000..62b2e01ff29938a5ca241c01368449c2a1a62d59--- /dev/null+++ b/mindspeed_llm/core/models/lfm2/lfm2_transformer_layer.py@@ -0,0 +1,251 @@+# Copyright (c) 2026, HUAWEI CORPORATION.  All rights reserved.+"""LFM2 transformer layer.++The LFM2 architecture alternates between short convolution and grouped-query+attention blocks. Each block follows the standard Megatron pre-norm residual+structure with two RMSNorms (one before the operator and one before the MLP).+"""++from dataclasses import dataclass, field+from typing import Dict, Optional, Union++import torch+from torch import Tensor++from megatron.core.fusions.fused_bias_dropout import get_bias_dropout_add+from megatron.core.transformer.enums import AttnMaskType+from megatron.core.transformer.identity_op import IdentityFuncOp, 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+from megatron.core.utils import make_viewless_tensor++from mindspeed_llm.core.models.lfm2.short_conv import Lfm2ShortConv, Lfm2ShortConvSubmodules+++@dataclass+class Lfm2TransformerLayerSubmodules:+    """Submodules for a hybrid LFM2 transformer layer.++    The ``attention`` and ``short_conv`` slots are mutually exclusive at+    runtime; the layer selects one based on its ``layer_number`` against the+    ``layer_types`` list attached to the transformer configuration.+    """++    operator_norm: Union[ModuleSpec, type] = IdentityOp+    attention: Union[ModuleSpec, type] = IdentityOp+    short_conv: Union[ModuleSpec, type] = IdentityOp+    operator_bda: Union[ModuleSpec, type] = IdentityFuncOp+    ffn_norm: Union[ModuleSpec, type] = IdentityOp+    mlp: Union[ModuleSpec, type] = IdentityOp+    mlp_bda: Union[ModuleSpec, type] = IdentityFuncOp++    # Mapping for sharded tensor keys to be applied in ``sharded_state_dict``.+    sharded_state_dict_keys_map: Dict[str, str] = field(default_factory=dict)+++class Lfm2TransformerLayer(MegatronModule, BaseTransformerLayer):+    """Single hybrid LFM2 decoder layer.++    The layer routes to either ``self.attention`` or ``self.short_conv`` for the+    along-sequence operator based on the layer index. The MLP block mirrors the+    standard Megatron transformer layer so ``dense_mlp_block`` / fusing+    optimizations continue to apply.+    """++    LFM2_OPERATOR_TYPES = ("conv", "full_attention")++    def __init__(+        self,+        config: TransformerConfig,+        submodules: Lfm2TransformerLayerSubmodules,+        layer_number: int = 1,+        lfm2_layer_types=None,+        hidden_dropout: Optional[float] = None,+    ):+        super().__init__(config=config)+        self.config = config+        self.submodules_config = submodules+        self.layer_number = layer_number+        self.hidden_dropout = (+            hidden_dropout+            if hidden_dropout is not None+            else getattr(config, "hidden_dropout", 0.0)+        )++        # Resolve the layer-type manifest. ``spec.params["lfm2_layer_types"]``+        # is the canonical source; ``config.lfm2_layer_types`` is exposed as a+        # fall-back so the same layer also works with heterogeneous specs.+        if lfm2_layer_types is None:+            lfm2_layer_types = getattr(self.config, "lfm2_layer_types", None)+        if not lfm2_layer_types or len(lfm2_layer_types) < self.layer_number:+            raise ValueError(+                "Lfm2TransformerLayer requires `lfm2_layer_types` either via "+                "spec params or `config.lfm2_layer_types`; got "+                f"{lfm2_layer_types!r}"+            )+        self._lfm2_layer_types = list(lfm2_layer_types)+        # Stash on the config as well so downstream code (e.g. sharding) can+        # read it without an explicit kwarg.+        self.config.lfm2_layer_types = self._lfm2_layer_types++        layer_type = self._lfm2_layer_types[self.layer_number - 1]+        if layer_type not in self.LFM2_OPERATOR_TYPES:+            raise ValueError(+                f"Lfm2TransformerLayer layer_number={self.layer_number} has "+                f"unsupported layer_type={layer_type!r}"+            )+        self.is_attention_layer = layer_type == "full_attention"+        self.conv_kernel_size = getattr(self.config, "conv_kernel_size", 3)++        # Pre-operator RMSNorm (matches HF ``operator_norm``).+        self.operator_norm = build_module(+            submodules.operator_norm,+            config=self.config,+            hidden_size=self.config.hidden_size,+            eps=self.config.layernorm_epsilon,+        )+        if self.is_attention_layer:+            self.attention = build_module(+                submodules.attention,+                config=self.config,+                layer_number=self.layer_number,+            )+            self.short_conv = None+        else:+            self.short_conv = build_module(+                submodules.short_conv,+                config=self.config,+                submodules=Lfm2ShortConvSubmodules(+                    in_proj=submodules.short_conv.submodules.in_proj,+                    out_proj=submodules.short_conv.submodules.out_proj,+                ),+                layer_number=self.layer_number,+                conv_kernel_size=self.conv_kernel_size,+            )+            self.attention = None++        # Operator residual merge (bias-dropout-add). Falls back to a no-op+        # additive identity when no linear biases are present.+        if self.config.add_bias_linear:+            self.operator_bda = build_module(submodules.operator_bda)+        else:+            self.operator_bda = IdentityFuncOp()++        # Pre-MLP RMSNorm (matches HF ``ffn_norm``).+        self.ffn_norm = build_module(+            submodules.ffn_norm,+            config=self.config,+            hidden_size=self.config.hidden_size,+            eps=self.config.layernorm_epsilon,+        )+        # Standard Megatron MLP block.+        self.mlp = build_module(+            submodules.mlp,+            config=self.config,+            is_expert=False,+        )+        if self.config.add_bias_linear:+            self.mlp_bda = build_module(submodules.mlp_bda)+        else:+            self.mlp_bda = IdentityFuncOp()++        self.bias_dropout_add_exec_handler = torch.enable_grad++    @property+    def self_attention(self):+        """Backwards-compatible alias used by MCore dispatch helpers.++        Returns the attention module when this is an attention layer, otherwise+        ``None``.+        """+        return self.attention++    def forward(+        self,+        hidden_states: Tensor,+        attention_mask: Tensor,+        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,+        inference_context=None,+        inference_params=None,+        packed_seq_params=None,+        attention_bias: Optional[Tensor] = None,+        sequence_len_offset=None,+    ) -> Tensor:+        """Apply the hybrid LFM2 transformer layer.++        Args:+            hidden_states: Tensor shaped ``[S, B, D]`` (MCore convention).++        Returns:+            Tensor shaped ``[S, B, D]`` carrying the residual-stream update.+        """+        residual = hidden_states+        operator_input = self.operator_norm(hidden_states)++        if self.is_attention_layer:+            attention_output_with_bias = self.attention(+                operator_input,+                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,+                inference_params=inference_params,+            )+            operator_output, bias = (+                attention_output_with_bias+                if isinstance(attention_output_with_bias, tuple)+                else (attention_output_with_bias, None)+            )+            if bias is not None:+                operator_output = operator_output + bias+        else:+            operator_output = self.short_conv(operator_input)++        hidden_states = make_viewless_tensor(+            inp=operator_output + residual,+            requires_grad=operator_output.requires_grad,+            keep_graph=True,+        )++        residual = hidden_states+        mlp_output, bias = self.mlp(self.ffn_norm(hidden_states))+        if bias is not None:+            mlp_output = mlp_output + bias+        hidden_states = make_viewless_tensor(+            inp=mlp_output + residual,+            requires_grad=mlp_output.requires_grad,+            keep_graph=True,+        )++        # MCore's :class:`TransformerBlock` expects the per-layer forward to+        # return ``(hidden_states, context)``; LFM2 has no cross-attention so+        # ``context`` is always ``None``.+        return hidden_states, None++    def sharded_state_dict(self, prefix: str = "", sharded_offsets=(), metadata=None):+        """Return the sharded state dictionary for this layer.++        The sharded state dictionary is delegated to the underlying+        :class:`MegatronModule` implementation; the operator submodule is+        renamed via ``sharded_state_dict_keys_map`` so HF roundtrip tooling+        (built around the standard MCore layout) matches the checkpoint.+        """+        state_dict = super().sharded_state_dict(prefix, sharded_offsets, metadata)+        rename_map = self.submodules_config.sharded_state_dict_keys_map or {}+        new_state = {}+        for key, value in state_dict.items():+            new_key = key+            for needle, replacement in rename_map.items():+                new_key = new_key.replace(needle, replacement)+            new_state[new_key] = value+        return new_statediff --git a/mindspeed_llm/core/models/lfm2/short_conv.py b/mindspeed_llm/core/models/lfm2/short_conv.pynew file mode 100644index 0000000000000000000000000000000000000000..b055796cf724aeb16b23046a004d4ba9112eccac--- /dev/null+++ b/mindspeed_llm/core/models/lfm2/short_conv.py@@ -0,0 +1,145 @@+# Copyright (c) 2026, HUAWEI CORPORATION.  All rights reserved.+"""LFM2 short convolution block.++Implements the depthwise short convolution operator used by the LFM2 hybrid model.+The pre-norm input is projected into three chunks (B, C, x); the depthwise+convolution is applied to ``B * x``; the result is gated by ``C`` and then+projected back to the model width.+"""++from dataclasses import dataclass+from typing import Union++import torch+import torch.nn as nn+import torch.nn.functional as F+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+++@dataclass+class Lfm2ShortConvSubmodules:+    """Submodules for the LFM2 short convolution block."""++    in_proj: Union[ModuleSpec, type] = None+    out_proj: Union[ModuleSpec, type] = None+++class DepthwiseCausalConv1d(nn.Module):+    """Depthwise causal 1D convolution matching ``torch.nn.Conv1d`` with+    ``groups=hidden_size`` and kernel-size ``L_cache`` followed by truncation to+    the input sequence length.+    """++    def __init__(self, hidden_size: int, kernel_size: int):+        super().__init__()+        self.hidden_size = hidden_size+        self.kernel_size = kernel_size+        # HF stores the per-channel weight as ``[hidden_size, 1, kernel_size]``+        # so that the depthwise conv1d weight aligns without rank-promotion.+        self.weight = nn.Parameter(torch.empty(hidden_size, 1, kernel_size))+        nn.init.kaiming_uniform_(self.weight, a=5 ** 0.5)++    def forward(self, x: Tensor) -> Tensor:+        """Apply the depthwise causal convolution.++        ``x`` arrives shaped ``[B, D, L]``; right padding ``K - 1`` preserves+        causality and the trailing tokens are discarded to match the HF+        reference implementation.+        """+        y = F.conv1d(+            x,+            self.weight,+            bias=None,+            stride=1,+            padding=self.kernel_size - 1,+            groups=self.hidden_size,+        )+        return y[..., : x.shape[-1]]+++class Lfm2ShortConv(MegatronModule):+    """LFM2 short convolution block (operator).++    The block performs ``out_proj(C * conv1d(B * x))`` where ``B``, ``C`` and+    ``x`` are slices of an input projection of width ``3 * hidden_size`` with a+    depthwise convolution of kernel-size 3 along the sequence dimension.+    """++    def __init__(+        self,+        config: TransformerConfig,+        submodules: Lfm2ShortConvSubmodules,+        layer_number: int = 1,+        conv_kernel_size: int = 3,+    ):+        super().__init__(config=config)+        self.config = config+        self.layer_number = layer_number+        self.conv_kernel_size = conv_kernel_size++        # ``in_proj`` produces three channel chunks; we always split the output+        # of a column-parallel linear so tensor parallelism composes naturally.+        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,+            tp_comm_buffer_name="conv_in_proj",+        )++        # Depthwise causal convolution lives on every tensor-parallel rank.+        self.conv = DepthwiseCausalConv1d(+            self.config.hidden_size, kernel_size=self.conv_kernel_size+        )++        # Output projection maps back to the model width as a row-parallel+        # linear that consumes the (tensor-parallel split) gated output.+        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,+            tp_comm_buffer_name="conv_out_proj",+        )++    def forward(self, hidden_states: Tensor) -> Tensor:+        """Apply the LFM2 short convolution operator.++        Args:+            hidden_states: Tensor shaped ``[S, B, D]``; the pre-norm operator+                input (output of the operator-norm layer).++        Returns:+            Tensor shaped ``[S, B, D]``.+        """+        # Move from MCore's ``[S, B, D]`` layout to ``[B, S, D]`` so the+        # sequence dimension is well-defined before transposing for the+        # depthwise convolution.+        x = hidden_states.transpose(0, 1).contiguous()  # [B, S, D]+        bcx, _ = self.in_proj(x)  # [B, S, 3D] (tensor-parallel split)+        bcx = bcx.transpose(-1, -2)  # [B, 3 * D_chunk, S]+        b_chunk, c_chunk, x_chunk = bcx.chunk(3, dim=-2)+        bx = b_chunk * x_chunk  # multiplicative pre-conv gate++        conv_out = self.conv(bx)  # [B, D_chunk, S]+        y = c_chunk * conv_out  # multiplicative post-conv gate++        # Back to ``[B, S, D_chunk]`` ready for the row-parallel projection.+        y = y.transpose(-1, -2).contiguous()+        out, _ = self.out_proj(y)+        # Restore MCore ``[S, B, D]`` layout.+        return out.transpose(0, 1)diff --git a/mindspeed_llm/tasks/checkpoint/lfm2_convert.py b/mindspeed_llm/tasks/checkpoint/lfm2_convert.pynew file mode 100644index 0000000000000000000000000000000000000000..6996d444d8c1c6af68fb7a71e642601d0753d7ae--- /dev/null+++ b/mindspeed_llm/tasks/checkpoint/lfm2_convert.py@@ -0,0 +1,416 @@+# Copyright (c) 2026, HUAWEI CORPORATION.  All rights reserved.+"""HF <-> Megatron-Core checkpoint conversion for the LFM2 hybrid architecture.++This script exposes two subcommands:++* ``hf-to-mcore`` - materialise an MCore ``GPTModel`` checkpoint (under+  ``--save-dir``) from a HuggingFace ``Lfm2ForCausalLM`` directory. The MCore+  checkpoint uses the same directory layout produced by ``pretrain_gpt``'s+  ``--ckpt-format=torch`` path (``iter_0000001/mp_rank_00_000/.distcp`` style)+  so downstream training can ``--load`` the checkpoint directly.+* ``mcore-to-hf`` - inverse direction. Reads an MCore checkpoint and+  materialises a HuggingFace-compatible ``model.safetensors``. Used by the+  correctness oracle to validate round-trip weight conversion.+"""++from __future__ import annotations++import argparse+import json+import logging+import os+import sys+from pathlib import Path+from typing import Dict, Iterable, List, Sequence, Tuple++import torch++# ``mindspeed_llm`` ships its own CLT extensions at import time; the import is+# deferred to the top of the script to keep parser paths simple.+import mindspeed_llm  # noqa: F401++from megatron.training import get_args+import megatron.training+++LOGGER = logging.getLogger("lfm2_convert")+logging.basicConfig(format="%(levelname)s %(message)s", level=logging.INFO)+++DEFAULT_LAYER_TYPES: Tuple[str, ...] = (+    "conv", "conv", "full_attention", "conv",+    "conv", "full_attention", "conv", "conv",+    "full_attention", "conv", "full_attention", "conv",+    "full_attention", "conv", "full_attention", "conv",+)+++def parse_args() -> argparse.Namespace:+    """Parse the conversion arguments."""+    parser = argparse.ArgumentParser(+        description="HF <-> Megatron-Core conversion for the LFM2 architecture."+    )+    sub = parser.add_subparsers(dest="op", required=True)++    common = argparse.ArgumentParser(add_help=False)+    common.add_argument("--num-layers", type=int, default=16)+    common.add_argument(+        "--layer-types",+        type=str,+        default=None,+        help=(+            "Comma-separated list of `conv`/`full_attention` for each layer. "+            "Defaults to the LFM2.5-1.2B pattern (10 conv + 6 full_attention)."+        ),+    )++    hf2m = sub.add_parser("hf-to-mcore", parents=[common])+    hf2m.add_argument("--load-dir", required=True, help="HuggingFace model directory (with model.safetensors).")+    hf2m.add_argument("--save-dir", required=True, help="Megatron checkpoint output directory.")++    m2hf = sub.add_parser("mcore-to-hf", parents=[common])+    m2hf.add_argument("--load-dir", required=True, help="Megatron checkpoint directory.")+    m2hf.add_argument("--save-dir", required=True, help="Output HuggingFace directory (will be created).")+    m2hf.add_argument("--config-dir", required=True, help="HuggingFace config.json (for metadata).")++    return parser.parse_args()+++def _resolve_layer_types(arg_value: str | None, num_layers: int) -> List[str]:+    if arg_value is None:+        chosen = list(DEFAULT_LAYER_TYPES)+    else:+        chosen = [token.strip() for token in arg_value.split(",") if token.strip()]+    if len(chosen) != num_layers:+        raise ValueError(+            f"Expected {num_layers} layer types, got {len(chosen)} ({chosen!r})."+        )+    for kind in chosen:+        if kind not in ("conv", "full_attention"):+            raise ValueError(f"Unsupported layer type {kind!r}")+    return chosen+++def _iter_hf_tensors(weights: Dict[str, torch.Tensor]) -> Iterable[Tuple[str, torch.Tensor]]:+    """Yield ``(hf_key, tensor)`` from a HuggingFace state-dict-like mapping.++    Filters out non-tensor entries (e.g. cached metadata) which can appear in+    ``safetensors`` index dictionaries.+    """+    for key, value in weights.items():+        if isinstance(value, torch.Tensor):+            yield key, value+++def _load_hf_safetensors(load_dir: Path) -> Dict[str, torch.Tensor]:+    """Load all tensors from ``model.safetensors``/``.bin`` files into CPU."""+    state_dict: Dict[str, torch.Tensor] = {}+    candidates = sorted(load_dir.glob("*.safetensors"))+    if not candidates:+        candidates = sorted(load_dir.glob("*.bin"))+    for path in candidates:+        if path.suffix == ".safetensors":+            from safetensors import safe_open++            with safe_open(str(path), framework="pt", device="cpu") as f:+                for key in f.keys():+                    state_dict[key] = f.get_tensor(key)+        else:+            partial = torch.load(str(path), map_location="cpu", weights_only=False)+            if isinstance(partial, dict):+                state_dict.update(partial)+    if not state_dict:+        raise FileNotFoundError(f"No weight files found under {load_dir}.")+    return state_dict+++def _convert_hf_to_mcore(+    hf_state: Dict[str, torch.Tensor], layer_types: Sequence[str], num_layers: int+) -> Dict[str, torch.Tensor]:+    """Translate HuggingFace tensors to MCore checkpoint keys.++    The MCore state-dict is laid out to match ``GPTModel`` with the+    ``Lfm2TransformerLayer`` spec - ``decoder.layers.{i}.<module>.*`` keys+    with router/norm naming matching the MCore conventions.+    """+    out: Dict[str, torch.Tensor] = {}++    embed = hf_state.get("model.embed_tokens.weight")+    if embed is None:+        raise KeyError("HF state is missing `model.embed_tokens.weight`.")+    out["embedding.word_embeddings.weight"] = embed.contiguous()++    final_norm = hf_state.get("model.embedding_norm.weight")+    if final_norm is None:+        raise KeyError("HF state is missing `model.embedding_norm.weight`.")+    out["decoder.final_layernorm.weight"] = final_norm.contiguous()++    # Tied embeddings: MCore's ``GPTModel`` skips the ``output_layer.weight``+    # parameter when ``share_embeddings_and_output_weights=True`` is set and+    # reuses ``embedding.word_embeddings.weight`` instead, so we deliberately+    # do not emit a duplicate ``output_layer.weight`` here.++    for layer_idx in range(num_layers):+        layer_type = layer_types[layer_idx]+        mg_prefix = f"decoder.layers.{layer_idx}"++        op_norm = hf_state.get(f"model.layers.{layer_idx}.operator_norm.weight")+        if op_norm is None:+            raise KeyError(f"Missing operator_norm.weight for layer {layer_idx}.")+        out[f"{mg_prefix}.operator_norm.weight"] = op_norm.contiguous()++        ffn_norm = hf_state.get(f"model.layers.{layer_idx}.ffn_norm.weight")+        if ffn_norm is None:+            raise KeyError(f"Missing ffn_norm.weight for layer {layer_idx}.")+        out[f"{mg_prefix}.ffn_norm.weight"] = ffn_norm.contiguous()++        if layer_type == "conv":+            for src_key, target in (+                (f"model.layers.{layer_idx}.conv.conv.weight", f"{mg_prefix}.short_conv.conv.weight"),+                (f"model.layers.{layer_idx}.conv.in_proj.weight", f"{mg_prefix}.short_conv.in_proj.weight"),+                (f"model.layers.{layer_idx}.conv.out_proj.weight", f"{mg_prefix}.short_conv.out_proj.weight"),+            ):+                tensor = hf_state.get(src_key)+                if tensor is None:+                    raise KeyError(f"Missing HF tensor {src_key!r}.")+                out[target] = tensor.contiguous()+        else:+            for src_name, target in (+                ("q_proj", "q_proj"),+                ("k_proj", "k_proj"),+                ("v_proj", "v_proj"),+                ("out_proj", "linear_proj"),+            ):+                src_key = f"model.layers.{layer_idx}.self_attn.{src_name}.weight"+                tensor = hf_state.get(src_key)+                if tensor is None:+                    raise KeyError(f"Missing HF tensor {src_key!r}.")+                out[f"{mg_prefix}.attention.{target}.weight"] = tensor.contiguous()+            for src_name, target in (+                ("q_layernorm", "q_layernorm"),+                ("k_layernorm", "k_layernorm"),+            ):+                src_key = f"model.layers.{layer_idx}.self_attn.{src_name}.weight"+                tensor = hf_state.get(src_key)+                if tensor is None:+                    raise KeyError(f"Missing HF tensor {src_key!r}.")+                out[f"{mg_prefix}.attention.{target}.weight"] = tensor.contiguous()++        # SwiGLU MLP: gate + up concat into ``linear_fc1``, down into+        # ``linear_fc2``.+        w1 = hf_state.get(f"model.layers.{layer_idx}.feed_forward.w1.weight")+        w3 = hf_state.get(f"model.layers.{layer_idx}.feed_forward.w3.weight")+        w2 = hf_state.get(f"model.layers.{layer_idx}.feed_forward.w2.weight")+        if w1 is None or w3 is None or w2 is None:+            raise KeyError(f"Missing feed_forward weights for layer {layer_idx}.")+        out[f"{mg_prefix}.mlp.linear_fc1.weight"] = torch.cat(+            [w1.contiguous(), w3.contiguous()], dim=0+        )+        out[f"{mg_prefix}.mlp.linear_fc2.weight"] = w2.contiguous()++    return out+++def _convert_mcore_to_hf(+    mcore_state: Dict[str, torch.Tensor], layer_types: Sequence[str], num_layers: int+) -> Dict[str, torch.Tensor]:+    """Translate MCore tensors to HuggingFace keys for roundtrip validation."""+    out: Dict[str, torch.Tensor] = {}++    embed = mcore_state.get("embedding.word_embeddings.weight")+    if embed is None:+        raise KeyError("MCore state missing embedding.word_embeddings.weight.")+    out["model.embed_tokens.weight"] = embed.contiguous()++    final_norm = mcore_state.get("decoder.final_layernorm.weight")+    if final_norm is None:+        raise KeyError("MCore state missing decoder.final_layernorm.weight.")+    out["model.embedding_norm.weight"] = final_norm.contiguous()++    for layer_idx in range(num_layers):+        layer_type = layer_types[layer_idx]+        mg_prefix = f"decoder.layers.{layer_idx}"++        op_norm = mcore_state.get(f"{mg_prefix}.operator_norm.weight")+        if op_norm is None:+            raise KeyError(f"Missing {mg_prefix}.operator_norm.weight.")+        out[f"model.layers.{layer_idx}.operator_norm.weight"] = op_norm.contiguous()++        ffn_norm = mcore_state.get(f"{mg_prefix}.ffn_norm.weight")+        if ffn_norm is None:+            raise KeyError(f"Missing {mg_prefix}.ffn_norm.weight.")+        out[f"model.layers.{layer_idx}.ffn_norm.weight"] = ffn_norm.contiguous()++        if layer_type == "conv":+            for src_name, target in (+                ("conv", "conv"),+                ("in_proj", "in_proj"),+                ("out_proj", "out_proj"),+            ):+                src_key = f"{mg_prefix}.short_conv.{src_name}.weight"+                tensor = mcore_state.get(src_key)+                if tensor is None:+                    raise KeyError(f"Missing {src_key!r}.")+                out[f"model.layers.{layer_idx}.conv.{target}.weight"] = tensor.contiguous()+        else:+            for src_name, target in (+                ("q_proj", "q_proj"),+                ("k_proj", "k_proj"),+                ("v_proj", "v_proj"),+                ("linear_proj", "out_proj"),+            ):+                src_key = f"{mg_prefix}.attention.{src_name}.weight"+                tensor = mcore_state.get(src_key)+                if tensor is None:+                    raise KeyError(f"Missing {src_key!r}.")+                out[f"model.layers.{layer_idx}.self_attn.{target}.weight"] = tensor.contiguous()+            for src_name, target in (+                ("q_layernorm", "q_layernorm"),+                ("k_layernorm", "k_layernorm"),+            ):+                src_key = f"{mg_prefix}.attention.{src_name}.weight"+                tensor = mcore_state.get(src_key)+                if tensor is None:+                    raise KeyError(f"Missing {src_key!r}.")+                out[f"model.layers.{layer_idx}.self_attn.{target}.weight"] = tensor.contiguous()++        fc1 = mcore_state.get(f"{mg_prefix}.mlp.linear_fc1.weight")+        fc2 = mcore_state.get(f"{mg_prefix}.mlp.linear_fc2.weight")+        if fc1 is None or fc2 is None:+            raise KeyError(f"Missing mlp projections for layer {layer_idx}.")+        # ``linear_fc1`` stores ``[gate; up]`` along dim 0.+        ffn_hidden = fc1.shape[0] // 2+        out[f"model.layers.{layer_idx}.feed_forward.w1.weight"] = fc1[:ffn_hidden].contiguous()+        out[f"model.layers.{layer_idx}.feed_forward.w3.weight"] = fc1[ffn_hidden:].contiguous()+        out[f"model.layers.{layer_idx}.feed_forward.w2.weight"] = fc2.contiguous()++    return out+++# ---------------------------------------------------------------------------+# Megatron checkpoint IO. The conversion produces a MCore ``GPTModel``-friendly+# LEGACY torch checkpoint so ``pretrain_gpt --ckpt-format=torch --load`` can+# load it back without any custom logic. The on-disk layout mirrors+# ``megatron/training/checkpointing.get_checkpoint_name`` for ``TP=PP=EP=1``.+++CHECKPOINT_BASENAME = "model_optim_rng.pt"+++def _ensure_iter_dir(save_dir: Path) -> Path:+    save_dir.mkdir(parents=True, exist_ok=True)+    iter_dir = save_dir / "iter_0000001"+    iter_dir.mkdir(parents=True, exist_ok=True)+    return iter_dir+++def _build_legacy_state_dict(model_state: Dict[str, torch.Tensor]) -> Dict[str, object]:+    """Wrap the converted tensor dict in a LEGACY torch state-dict."""+    minimal_args = argparse.Namespace(+        no_save_rng=True,+        no_save_optim=True,+        tensor_model_parallel_size=1,+        pipeline_model_parallel_size=1,+        ckpt_format="torch",+    )+    return {+        "args": minimal_args,+        "checkpoint_version": 3.0,+        "iteration": 1,+        "model": model_state,+    }+++def _save_mcore_checkpoint(save_dir: Path, model_state: Dict[str, torch.Tensor]) -> None:+    """Persist the MCore state-dict in the LEGACY ``torch`` checkpoint layout.++    The output directory matches what ``megatron.training.checkpointing`` would+    produce for ``TP=PP=EP=1`` with ``--ckpt-format=torch``: a single+    ``model_optim_rng.pt`` file per rank directory plus a tracker file. Only+    rank 00 is materialised because the conversion runs on a single rank.+    """+    iter_dir = _ensure_iter_dir(save_dir)+    rank_dir = iter_dir / "mp_rank_00"+    rank_dir.mkdir(parents=True, exist_ok=True)+    state_dict = _build_legacy_state_dict(model_state)+    torch.save(state_dict, str(rank_dir / CHECKPOINT_BASENAME))+    (save_dir / "latest_checkpointed_iteration.txt").write_text("1")+++def _load_mcore_checkpoint(load_dir: Path) -> Dict[str, torch.Tensor]:+    """Read the previously-saved MCore state-dict from a conversion directory."""+    iter_file = load_dir / "latest_checkpointed_iteration.txt"+    if not iter_file.exists():+        raise FileNotFoundError(f"Missing tracker file in {load_dir}.")+    iter_name = iter_file.read_text().strip()+    iter_dir = load_dir / f"iter_{int(iter_name):07d}"+    rank_dirs = sorted(iter_dir.glob("mp_rank_*"))+    if not rank_dirs:+        raise FileNotFoundError(f"No ``mp_rank_*`` directory under {iter_dir}.")+    model_state: Dict[str, torch.Tensor] = {}+    for rank_dir in rank_dirs:+        checkpoint_path = rank_dir / CHECKPOINT_BASENAME+        if not checkpoint_path.exists():+            continue+        payload = torch.load(str(checkpoint_path), map_location="cpu", weights_only=False)+        if not isinstance(payload, dict) or "model" not in payload:+            raise RuntimeError(f"Invalid checkpoint layout at {checkpoint_path}.")+        model_state.update(payload["model"])+    if not model_state:+        raise RuntimeError(f"No tensors recovered from {load_dir}.")+    return model_state+++# ---------------------------------------------------------------------------+# Subcommand dispatch.+++def cmd_hf_to_mcore(args: argparse.Namespace) -> int:+    layer_types = _resolve_layer_types(args.layer_types, args.num_layers)+    load_dir = Path(args.load_dir)+    save_dir = Path(args.save_dir)++    LOGGER.info("Loading HF weights from %s", load_dir)+    hf_state = _load_hf_safetensors(load_dir)++    LOGGER.info("Converting HF -> MCore for %d layers (types=%s)", args.num_layers, layer_types)+    mcore_state = _convert_hf_to_mcore(hf_state, layer_types, args.num_layers)++    LOGGER.info("Writing MCore checkpoint to %s", save_dir)+    _save_mcore_checkpoint(save_dir, mcore_state)+    LOGGER.info("Conversion to MCore complete (saved %d tensors).", len(mcore_state))+    return 0+++def cmd_mcore_to_hf(args: argparse.Namespace) -> int:+    layer_types = _resolve_layer_types(args.layer_types, args.num_layers)+    load_dir = Path(args.load_dir)+    save_dir = Path(args.save_dir)+    save_dir.mkdir(parents=True, exist_ok=True)++    LOGGER.info("Loading MCore checkpoint from %s", load_dir)+    mcore_state = _load_mcore_checkpoint(load_dir)++    LOGGER.info("Converting MCore -> HF for %d layers", args.num_layers)+    hf_state = _convert_mcore_to_hf(mcore_state, layer_types, args.num_layers)++    # Persist the resulting tensors in safetensors format (HF-compatible).+    from safetensors.torch import save_file++    LOGGER.info("Writing HF tensors to %s/model.safetensors", save_dir)+    save_file(hf_state, str(save_dir / "model.safetensors"))+    LOGGER.info("Conversion to HF complete (saved %d tensors).", len(hf_state))+    return 0+++def main() -> int:+    args = parse_args()+    if args.op == "hf-to-mcore":+        return cmd_hf_to_mcore(args)+    if args.op == "mcore-to-hf":+        return cmd_mcore_to_hf(args)+    raise SystemExit(f"Unknown op: {args.op}")+++if __name__ == "__main__":+    raise SystemExit(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..23f86315365ae91225974b2e3f34a592cc35c601--- /dev/null+++ b/mindspeed_llm/tasks/models/spec/lfm2_spec.py@@ -0,0 +1,119 @@+# Copyright (c) 2026, HUAWEI CORPORATION.  All rights reserved.++"""Layer specification for the LFM2.5 hybrid transformer architecture.++The module exposes :data:`layer_spec`, a :class:`ModuleSpec` for an+:class:`Lfm2TransformerLayer` that handles both short convolution and full+attention blocks. The transformation between the two is driven by the+``lfm2_layer_types`` parameter carried by the 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 import ColumnParallelLinear, RowParallelLinear+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.training import get_args++from mindspeed_llm.core import PTNorm+from mindspeed_llm.core.models.lfm2.lfm2_attention import (+    Lfm2Attention,+    Lfm2AttentionSubmodules,+)+from mindspeed_llm.core.models.lfm2.lfm2_transformer_layer import (+    Lfm2TransformerLayer,+    Lfm2TransformerLayerSubmodules,+)+from mindspeed_llm.core.models.lfm2.short_conv import (+    Lfm2ShortConv,+    Lfm2ShortConvSubmodules,+)+++# Default layer-type manifest for the public ``LiquidAI/LFM2.5-1.2B-Base``+# model. Spec arguments (``args.lfm2_layer_types``) override it when supplied.+DEFAULT_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 _resolve_layer_types():+    """Resolve the LFM2 layer-type manifest.++    Falls back to :data:`DEFAULT_LFM2_LAYER_TYPES` for the fixed LFM2.5-1.2B+    architecture. ``args.lfm2_layer_types`` (list of strings) overrides the+    default when supplied.+    """+    try:+        args = get_args()+        candidate = getattr(args, "lfm2_layer_types", None)+        if candidate:+            return tuple(candidate)+    except Exception:+        # ``get_args()`` raises before ``pretrain_gpt`` initialises the args.+        # Spec modules are imported in that gap by ``args.spec`` resolution, so+        # we silently fall back to the built-in defaults.+        pass+    return DEFAULT_LFM2_LAYER_TYPES+++LFM2_LAYER_TYPES = _resolve_layer_types()+++# Build the LFM2 attention spec once at import so :data:`layer_spec` can stay a+# plain :class:`ModuleSpec` value.+args = None+try:+    args = get_args()+except Exception:+    args = None++qk_layernorm = getattr(args, "qk_layernorm", True) if args is not None else True++attention_spec = ModuleSpec(+    module=Lfm2Attention,+    params={"attn_mask_type": AttnMaskType.causal},+    submodules=Lfm2AttentionSubmodules(+        linear_q=ColumnParallelLinear,+        linear_k=ColumnParallelLinear,+        linear_v=ColumnParallelLinear,+        core_attention=DotProductAttention,+        linear_proj=RowParallelLinear,+        q_layernorm=PTNorm if qk_layernorm else IdentityOp,+        k_layernorm=PTNorm if qk_layernorm else IdentityOp,+    ),+)++short_conv_spec = ModuleSpec(+    module=Lfm2ShortConv,+    submodules=Lfm2ShortConvSubmodules(+        in_proj=ColumnParallelLinear,+        out_proj=RowParallelLinear,+    ),+)+++# ``pretrain_gpt.py`` does ``transformer_layer_spec = import_module(args.spec)``+# where ``args.spec`` resolves to the value of ``layer_spec`` in this module;+# the framework expects the value to be a :class:`ModuleSpec` so the+# ``TransformerBlock`` can fan it out across ``num_layers`` and pick up the+# ``submodules`` and ``params`` slots.+layer_spec = ModuleSpec(+    module=Lfm2TransformerLayer,+    params={"lfm2_layer_types": list(LFM2_LAYER_TYPES)},+    submodules=Lfm2TransformerLayerSubmodules(+        operator_norm=PTNorm,+        attention=attention_spec,+        short_conv=short_conv_spec,+        operator_bda=get_bias_dropout_add,+        ffn_norm=PTNorm,+        mlp=get_mlp_module_spec(use_te=False),+        mlp_bda=get_bias_dropout_add,+        sharded_state_dict_keys_map={},+    ),+)