Kimi K3 · Training

T05 · Training adapt

Valid

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

1.29×PERFORMANCE RATIO
226TOOL EVENTS
1TEXT PATCHES
0BINARY NAMES

01 / PROCESS MAP

Agents over time

Compare agents on one time axis; overlapping spans line up vertically. Select an agent or bar to inspect its events.

Elapsed time · mm:ss

Agent / model
+08:46+08:54+09:01+09:09+09:16
Main agentKimi K3Main timeline · 226 calls
Subagent 1Model not recordedFrom Main agent · 0 calls
Delegation only · child timing not recorded

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.

InspectEditValidateExecuteBuildProfileRollbackOther
187Inspect
9Edit
1Build
12Validate
12Execute
5Other

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 timeline117 groups · 226 calls · 1 subagents

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.

Main agent

  1. 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>
  2. Inspect · Attention kernels

    1 tool error

    Requested source searches related to attention kernels.

    1 call · #0003–#0003

    Search <pattern> <path>
  3. Inspect · Source & workspace

    Requested workspace inspection related to source & workspace.

    2 calls · #0004–#0005

    Find <pattern>ls <path> <path>
  4. Inspect · Attention kernels

    Requested source searches related to attention kernels.

    2 calls · #0006–#0007

    Search <pattern> <path>
  5. Inspect · Source & workspace

    Requested workspace inspection related to source & workspace.

    1 call · #0008–#0008

    ls <path> <path> <path> <n> > <path>ls <path> <n> > <path>
  6. Inspect · Attention kernels

    Requested source searches related to attention kernels.

    1 call · #0009–#0009

    Search <pattern> <path>
  7. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    2 calls · #0010–#0011

    Read <path>
  8. Inspect · Attention kernels

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

    4 calls · #0012–#0015

    Read <path>Search <pattern> <path>
  9. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0016–#0016

    Read <path>
  10. Inspect · Attention kernels

    Requested source searches related to attention kernels.

    1 call · #0017–#0017

    Search <pattern> <path>
  11. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    2 calls · #0018–#0019

    Read <path>
  12. Inspect · Attention kernels

    Requested file and log inspection related to attention kernels.

    1 call · #0020–#0020

    Read <path>
  13. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0021–#0021

    Read <path>
  14. Inspect · Attention kernels

    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>
  15. Inspect · Source & workspace

    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>
  16. Inspect · Attention kernels

    Requested source searches related to attention kernels.

    1 call · #0027–#0027

    Search <pattern> <path>
  17. Inspect · Source & workspace

    1 tool error

    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>
  18. Inspect · Attention kernels

    Requested file and log inspection related to attention kernels.

    1 call · #0033–#0033

    Read <path>
  19. Inspect · Source & workspace

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

    2 calls · #0034–#0035

    Search <pattern> <path>Read <path>
  20. Inspect · Attention kernels

    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>
  21. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    3 calls · #0039–#0041

    Read <path>
  22. Inspect · Attention kernels

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

    4 calls · #0042–#0045

    Search <pattern> <path>Read <path>
  23. Inspect · Source & workspace

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

    4 calls · #0046–#0049

    Read <path>Search <pattern> <path>
  24. Inspect · Attention kernels

    Requested source searches related to attention kernels.

    1 call · #0050–#0050

    Search <pattern> <path>
  25. Inspect · Source & workspace

    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>
    1 more command sketches
    head -n <n>
  26. Inspect · Attention kernels

    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>
  27. Inspect · Source & workspace

    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>
    1 more command sketches
    head -n <n>
  28. Inspect · Attention kernels

    Requested source searches related to attention kernels.

    1 call · #0071–#0071

    Search <pattern> <path>
  29. Inspect · Source & workspace

    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>
  30. Inspect · Attention kernels

    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>
  31. Inspect · Source & workspace

    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>
    4 more command sketches
    head -n <n>grep -r -n <val> <path> <path>sed -n <val> <path>Read <path>
  32. Inspect · Attention kernels

    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>
  33. Inspect · Source & workspace

    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>
  34. Inspect · Attention kernels

    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>
  35. Inspect · Source & workspace

    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>
  36. Inspect · Attention kernels

    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>
  37. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0100–#0100

    Read <path>
  38. Inspect · Device memory

    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>
  39. Inspect · Source & workspace

    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>
    1 more command sketches
    true
  40. Inspect · Task requirements

    Requested file and log inspection related to task requirements.

    2 calls · #0104–#0105

    Read <path>
  41. Inspect · Source & workspace

    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>
  42. Inspect · Task requirements

    Requested file and log inspection related to task requirements.

    2 calls · #0108–#0109

    Read <path>
  43. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0110–#0110

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

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

    1 call · #0111–#0111

    Read <path>
  45. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    4 calls · #0112–#0115

    Read <path>
  46. Inspect · Task requirements

    Requested file and log inspection related to task requirements.

    2 calls · #0116–#0117

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

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

    1 call · #0118–#0118

    cat <path> <path> <path> <path> <path> <path>
  48. Inspect · Source & workspace

    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>
    3 more command sketches
    ls <path>ls <path> <n> > <path>Update task list <tasks>
  49. Inspect · Checkpoints & weight state

    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>
  50. Inspect · Source & workspace

    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>
  51. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    2 calls · #0126–#0127

    python3 -c <script>
  52. Inspect · Source & workspace

    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>
    1 more command sketches
    head -n <n>
  53. Execute · Source & workspace

    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>
  54. Inspect · Source & workspace

    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>
    9 more command sketches
    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>
  55. Build · Source & workspace

    Requested task coordination related to source & workspace.

    1 call · #0136–#0136

    Delegate <task>
    Subagent 1· Model not recorded · explore · 0 visible callsCompleted

    Delegated by Main agent at call #0136.

    Only the returned summary is retained; child tool events are not available.

  56. Inspect · Source & workspace

    2 tool errors

    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>
  57. Inspect · Attention kernels

    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>
  58. Inspect · Source & workspace

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

    2 calls · #0147–#0148

    Read <path>Update task list <tasks>
  59. Validate · Benchmark & validation setup

    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>
  60. Inspect · Checkpoints & weight state

    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>
  61. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0152–#0152

    cat <path>
  62. Inspect · Checkpoints & weight state

    1 tool error

    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>
    1 more command sketches
    grep -r -n <val> <path> <path> <n> > <path>
  63. Inspect · Parallelism & communication

    Requested file and log inspection related to parallelism & communication.

    1 call · #0157–#0157

    sed -n <val> <path>
  64. Inspect · Checkpoints & weight state

    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>head
    1 more command sketches
    head -n <n> <path>
  65. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0159–#0159

    sed -n <val> <path>echo <val> <val>
  66. Inspect · Checkpoints & weight state

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

    1 call · #0160–#0160

    sed -n <val> <path>echo <val>
  67. Inspect · Attention kernels

    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>
  68. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0162–#0162

    sed -n <val> <path>
  69. Edit · Convolution & sequence boundaries

    Requested code edits related to convolution & sequence boundaries.

    1 call · #0163–#0163

    Write <path>
  70. Edit · Source & workspace

    Requested code edits related to source & workspace.

    2 calls · #0164–#0165

    Write <path>
  71. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0166–#0166

    Read <path>
  72. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0167–#0167

    Write <path>
  73. Inspect · Source & workspace

    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>
  74. Edit · Checkpoints & weight state

    Requested code edits related to checkpoints & weight state.

    1 call · #0170–#0170

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

    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>
    2 more command sketches
    headcat <path>
  76. Inspect · Source & workspace

    Requested task coordination related to source & workspace.

    1 call · #0172–#0172

    Update task list <tasks>
  77. Validate · Benchmark & validation setup

    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>
    4 more command sketches
    ls <path> <n> > <path>grep -v -E <val>tail -n <n>grep -E <val> <path> <n> > <path>
  78. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0177–#0177

    Write <path>
  79. Validate · Benchmark & validation setup

    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>
    5 more command sketches
    grep <flag> <args><command> <args>echo <val> <val>tail -n <n> <path>python3 -c <script>
  80. Inspect · Source & workspace

    Requested task coordination related to source & workspace.

    1 call · #0181–#0181

    Update task list <tasks>
  81. Execute · Benchmark & validation setup

    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>
    6 more command sketches
    <command> <args>tail -n <n>echotail -n <n> <path> <n> > <path>python3 -c <script>head -n <n>
  82. Inspect · Benchmark & validation setup

    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>
  83. Inspect · Runtime processes

    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>
  84. Inspect · Source & workspace

    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>
  85. Inspect · Dependencies & build setup

    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>head
  86. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0189–#0189

    sed -n <val> <path>
  87. Other · Source & workspace

    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>
  88. Execute · Benchmark & validation setup

    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>
  89. Inspect · Source & workspace

    Requested task coordination related to source & workspace.

    1 call · #0192–#0192

    Update task list <tasks>
  90. Inspect · Checkpoints & weight state

    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>
  91. Inspect · Parallelism & communication

    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>
  92. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0195–#0195

    Write <path>
  93. Inspect · Source & workspace

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

    1 call · #0196–#0196

    grep <val> <path>tail -n <n> <path>
  94. Inspect · Parallelism & communication

    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>
  95. Execute · Benchmark & validation setup

    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>
  96. Inspect · Source & workspace

    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>
  97. Other · Source & workspace

    Requested script or workload execution and source searches related to source & workspace.

    1 call · #0200–#0200

    cd <path>python3 - <script>grep -n <val> <path>
  98. Inspect · Parallelism & communication

    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>
  99. Inspect · Source & workspace

    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>
  100. Other · Source & workspace

    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>
  101. Inspect · Source & workspace

    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 --stat
  102. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0206–#0206

    Edit <path>
  103. Inspect · Source & workspace

    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>
  104. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0208–#0208

    Edit <path>
  105. Execute · Benchmark & validation setup

    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>
  106. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0210–#0210

    Read <path>
  107. Execute · Benchmark & validation setup

    1 tool error

    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>
    5 more command sketches
    wc -lcd <path>bash <script> > <path> <n> >& <path>echo <val> >> <path>tail -n <n> <path>
  108. Inspect · Source & workspace

    Requested task coordination related to source & workspace.

    1 call · #0214–#0214

    Update task list <tasks>
  109. Inspect · Parallelism & communication

    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>
  110. Execute · Benchmark & validation setup

    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>
  111. Validate · Benchmark & validation setup

    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>
  112. Inspect · Source & workspace

    Requested repository inspection related to source & workspace.

    1 call · #0219–#0219

    cd <path>git status --shortgit diff --statecho <val>git diff <path>
  113. Validate · Checkpoints & weight state

    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>
  114. Inspect · Source & workspace

    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>
  115. Validate · Benchmark & validation setup

    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>
  116. Inspect · Device memory

    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>
    3 more command sketches
    wc -lnpu-smi info <n> > <path>head -n <n>
  117. Inspect · Source & workspace

    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

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..1db06563daf75f70d310952ac0a6b66885c35796--- /dev/null+++ b/mindspeed_llm/core/models/lfm2/__init__.py@@ -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",+]diff --git a/mindspeed_llm/core/models/lfm2/decoder_layer.py b/mindspeed_llm/core/models/lfm2/decoder_layer.pynew file mode 100644index 0000000000000000000000000000000000000000..c363cdf204898590a227d2c530b59f3c74c3749b--- /dev/null+++ b/mindspeed_llm/core/models/lfm2/decoder_layer.py@@ -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, contextdiff --git a/mindspeed_llm/core/models/lfm2/short_conv.py b/mindspeed_llm/core/models/lfm2/short_conv.pynew file mode 100644index 0000000000000000000000000000000000000000..106268e541169333bc6605d443bf92fb27ade78a--- /dev/null+++ b/mindspeed_llm/core/models/lfm2/short_conv.py@@ -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, biasdiff --git a/mindspeed_llm/tasks/checkpoint/lfm2_convert.py b/mindspeed_llm/tasks/checkpoint/lfm2_convert.pynew file mode 100644index 0000000000000000000000000000000000000000..28be842c658064aeb02da6f049700efea93bf542--- /dev/null+++ b/mindspeed_llm/tasks/checkpoint/lfm2_convert.py@@ -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())diff --git a/mindspeed_llm/tasks/models/spec/lfm2_spec.py b/mindspeed_llm/tasks/models/spec/lfm2_spec.pynew file mode 100644index 0000000000000000000000000000000000000000..fac47bc341a9e81c27c53cb93152cf6b3439666a--- /dev/null+++ b/mindspeed_llm/tasks/models/spec/lfm2_spec.py@@ -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()diff --git a/pretrain_gpt.py b/pretrain_gpt.pyindex 5a8506bb3f73e23ca5e1c1e2562d0a861c433cfb..961f5d6a72a5e106c6fb393588bd1a1dd1c2eeb7 100644--- a/pretrain_gpt.py+++ b/pretrain_gpt.py@@ -3,6 +3,7 @@ """Pretrain GPT."""  import os+import sys from functools import partial from typing import Union @@ -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)