MiniMax M3 · Serving

S13 · Serving build

Correctness rejected

OpenBuild Qwen3-8B serving 1dev · Open Build

—PERFORMANCE RATIO
293TOOL 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 · 293 visible calls

InspectEditValidateExecuteBuildProfileRollbackOther
190Inspect
18Edit
5Build
8Validate
42Execute
30Other

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 timeline147 groups · 293 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 · Source & workspace

    Requested workspace inspection related to source & workspace.

    1 call · #0001–#0001

    echo <val>ls -l -a <val> <n> > <path>ls -l -a <path>
  2. Inspect · Task requirements

    Requested file and log inspection related to task requirements.

    2 calls · #0002–#0003

    Read <path>
  3. Inspect · Source & workspace

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

    3 calls · #0004–#0006

    ls -l -a <path>echo <flag>ls -l -a <path> <n> > <path>echo <val>cat <path>
  4. Inspect · Task requirements

    Requested workspace inspection related to task requirements.

    1 call · #0007–#0007

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

    Requested file and log inspection related to source & workspace.

    1 call · #0008–#0008

    cat <path>echo <flag>
  6. Inspect · Benchmark & validation setup

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

    1 call · #0009–#0009

    cat <path>
  7. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    2 calls · #0010–#0011

    cat <path>
  8. Other · Task requirements

    Requested task coordination related to task requirements.

    1 call · #0012–#0012

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

    Requested task coordination related to source & workspace.

    1 call · #0013–#0013

    Create task <task>
  10. Other · Task requirements

    Requested task coordination related to task requirements.

    1 call · #0014–#0014

    Create task <task>
  11. Build · Batching & scheduling

    Requested task coordination related to batching & scheduling.

    1 call · #0015–#0015

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

    Requested task coordination related to benchmark & validation setup.

    1 call · #0016–#0016

    Create task <task>
  13. Execute · Dependencies & build setup

    Requested task coordination related to dependencies & build setup.

    1 call · #0017–#0017

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

    Requested task coordination related to source & workspace.

    1 call · #0018–#0018

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

    Requested file and log inspection, workspace inspection and script or workload execution related to source & workspace.

    2 calls · #0019–#0020

    Read <path>ls <path> <n> > <path>echo <flag>python3 -c <script> <n> >& <path>head -n <n>
  16. Inspect · Runtime processes

    Requested environment setup or inspection, source searches and file and log inspection related to runtime processes.

    1 call · #0021–#0021

    echo <val>envgrep -i <val> <n> > <path>head -n <n>
  17. Other · Source & workspace

    1 tool error

    Requested script or workload execution related to source & workspace.

    1 call · #0022–#0022

    python3 -c <script> <n> >& <path>echo <flag>
  18. Inspect · Source & workspace

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

    2 calls · #0023–#0024

    find <path> -maxdepth <n> -type <val> -name <val> <n> > <path>echo <flag>find <path> -maxdepth <n> -name <val> <n> > <path>head -n <n>ls -l -a <path>cat <path> <n> > <path>
  19. Inspect · Task requirements

    Requested file and log inspection and script or workload execution related to task requirements.

    2 calls · #0025–#0026

    cat <path>python3 -c <script>head -n <n>
  20. Inspect · Benchmark & validation setup

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

    2 calls · #0027–#0028

    cat <path>echo <flag>head -n <n>
  21. Inspect · Task requirements

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

    1 call · #0029–#0029

    ls <path>echo <flag>cat <path>head -n <n>
  22. Other · Source & workspace

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

    3 calls · #0030–#0032

    Update task <task>python3 -c <script>
  23. Inspect · Device memory

    Requested script or workload execution and file and log inspection related to device memory.

    2 calls · #0033–#0034

    python3 -c <script> <n> >& <path>tail -n <n>timeout <n> <val> -c <path> <n> >& <path>
  24. Inspect · Source & workspace

    Requested script or workload execution, file and log inspection and workspace inspection related to source & workspace.

    8 calls · #0035–#0042

    python3 -c <script> <n> >& <path>tail -n <n>python3 -c <script>ls <path>wc -l <path>grep -n <val> <path>
    2 more command sketches
    head -n <n>Read <path>
  25. Inspect · Attention kernels

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

    8 calls · #0043–#0050

    grep -n <val> <path> <path> <n> > <path>head -n <n>grep -r -n <val> <path> <n> > <path>sed -n <val> <path>echo <flag>ls <path>
    4 more command sketches
    grep -n <val> <path>cat <path>timeout <n> <val> -c <path> <n> >& <path>tail -n <n>
  26. Build · Attention kernels

    Requested script or workload execution and file and log inspection related to attention kernels.

    1 call · #0051–#0051

    timeout <n> <val> -c <path> <n> >& <path>tail -n <n>
  27. Other · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0052–#0052

    Read task output <task>
  28. Inspect · Source & workspace

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

    2 calls · #0053–#0054

    cat <path> <n> > <path>tail -n <n>ls -l -a <path> <n> > <path>
  29. Other · Source & workspace

    Requested task coordination related to source & workspace.

    3 calls · #0055–#0057

    Stop task <task>Update task <task>
  30. Edit · Task requirements

    Requested code edits related to task requirements.

    1 call · #0058–#0058

    Write <path>
  31. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0059–#0059

    Write <path>
  32. Build · Source & workspace

    Requested workspace file updates related to source & workspace.

    1 call · #0060–#0060

    chmod <val> <path>
  33. Edit · Runtime processes

    Requested code edits related to runtime processes.

    1 call · #0061–#0061

    Write <path>
  34. Build · Runtime processes

    Requested workspace file updates related to runtime processes.

    1 call · #0062–#0062

    chmod <val> <path>
  35. Other · Source & workspace

    Requested task coordination related to source & workspace.

    2 calls · #0063–#0064

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

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

    2 calls · #0065–#0066

    grep -r -n <val> <path> <n> > <path>head -n <n>ls <path> <n> > <path>
  37. Inspect · Attention kernels

    Requested file and log inspection related to attention kernels.

    1 call · #0067–#0067

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

    Requested file and log inspection related to source & workspace.

    1 call · #0068–#0068

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

    Requested code edits related to source & workspace.

    1 call · #0069–#0069

    Write <path>
  40. Other · Source & workspace

    1 tool error

    Requested script or workload execution related to source & workspace.

    2 calls · #0070–#0071

    python3 -c <script>cd <path>
  41. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0072–#0072

    Write <path>
  42. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0073–#0073

    python3 -c <script>
  43. Edit · Runtime processes

    Requested code edits related to runtime processes.

    1 call · #0074–#0074

    Write <path>
  44. Execute · Runtime processes

    Requested script or workload execution related to runtime processes.

    1 call · #0075–#0075

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

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

    2 calls · #0076–#0077

    cd <path>bash <script> <n> >& <path>tail -n <n>grep -r -n <val> <path>head -n <n>
  46. Inspect · Benchmark & validation setup

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

    1 call · #0078–#0078

    find <path> -type <val>headecho <flag>cat <path>find <path> -name <val> -type <val> <n> > <path>
  47. Inspect · Source & workspace

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

    8 calls · #0079–#0086

    find <path> -name <val> -o -name <path> <n> > <path>grep -v <val>grep -v <path>head -n <n>ls <path>ls <path> <n> > <path>
    10 more command sketches
    echo <flag>find <path> -type <val> <n> > <path>headcat <path> <n> > <path>cat <path>head -n <n> <path> <n> > <path>grep -n <val>find <path> -name <path> <n> > <path>find <path> -name <val> -type <val> <n> > <path>find <path> -type <val> -name <val> -o -name <val> <n> > <path>
  48. Inspect · Task requirements

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

    1 call · #0087–#0087

    ls -l -a <path>echo <flag>cat <path>
  49. Inspect · Device memory

    Requested environment setup or inspection and file and log inspection related to device memory.

    2 calls · #0088–#0089

    env <vars> timeout <n> <val> -c <path> <n> >& <path>tail -n <n>cd <path>
  50. Inspect · Batching & scheduling

    Requested source searches related to batching & scheduling.

    1 call · #0090–#0090

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

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

    3 calls · #0091–#0093

    Read <path>wc -l <path>grep -c <val> <path>
  52. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0094–#0094

    Edit <path>
  53. Execute · Runtime processes

    Requested script or workload execution related to runtime processes.

    1 call · #0095–#0095

    python3 -c <script>
  54. Inspect · Device memory

    Requested environment setup or inspection and file and log inspection related to device memory.

    1 call · #0096–#0096

    env <vars> timeout <n> <val> -c <path> <n> >& <path>tail -n <n>
  55. Inspect · Batching & scheduling

    Requested environment setup or inspection and file and log inspection related to batching & scheduling.

    1 call · #0097–#0097

    env <vars> timeout <n> <val> -c <path> <n> >& <path>tail -n <n>
  56. Inspect · Attention kernels

    Requested source searches, file and log inspection and script or workload execution related to attention kernels.

    7 calls · #0098–#0104

    grep -n <val> <path>head -n <n>sed -n <val> <path>python3 -c <script> <n> >& <path>tail -n <n>
  57. Inspect · Source & workspace

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

    2 calls · #0105–#0106

    grep -n <val> <path>head -n <n>echo <flag>sed -n <val> <path>
  58. Inspect · Attention kernels

    Requested script or workload execution and file and log inspection related to attention kernels.

    1 call · #0107–#0107

    python3 -c <script> <n> >& <path>tail -n <n>
  59. Validate · Attention kernels

    Requested script or workload execution and file and log inspection related to attention kernels.

    1 call · #0108–#0108

    python3 -c <script> <n> >& <path>tail -n <n>
  60. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0109–#0109

    Write <path>
  61. Execute · Runtime processes

    Requested script or workload execution related to runtime processes.

    1 call · #0110–#0110

    python3 -c <script>
  62. Inspect · Batching & scheduling

    Requested environment setup or inspection and file and log inspection related to batching & scheduling.

    1 call · #0111–#0111

    env <vars> timeout <n> <val> -c <path> <n> >& <path>tail -n <n>
  63. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0112–#0112

    Edit <path>
  64. Inspect · Batching & scheduling

    Requested environment setup or inspection and file and log inspection related to batching & scheduling.

    1 call · #0113–#0113

    env <vars> timeout <n> <val> -c <path> <n> >& <path>tail -n <n>
  65. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0114–#0114

    python3 -c <script>
  66. Inspect · Attention kernels

    Requested script or workload execution and file and log inspection related to attention kernels.

    4 calls · #0115–#0118

    python3 -c <script> <n> >& <path>tail -n <n>
  67. Inspect · Batching & scheduling

    Requested environment setup or inspection and file and log inspection related to batching & scheduling.

    2 calls · #0119–#0120

    env <vars> timeout <n> <val> -c <path> <n> >& <path>tail -n <n>
  68. Inspect · Attention kernels

    1 tool error

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

    40 calls · #0121–#0160

    grep -r -n <val> <path> <n> > <path>echo <flag>grep -r -n <val> <path>headls <path> <n> > <path>env <vars> timeout <n> <val> -c <path> <n> >& <path>
    7 more command sketches
    tail -n <n>grep -n <val> <path>head -n <n>sed -n <val> <path>python3 -c <script> <n> >& <path>grep -n <val> <path> -r <n> > <path>grep -i <val>
  69. Inspect · Source & workspace

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

    1 call · #0161–#0161

    grep -n <val> <path>head -n <n>
  70. Inspect · Attention kernels

    Requested source searches, file and log inspection and environment setup or inspection related to attention kernels.

    14 calls · #0162–#0175

    grep -n <val> <path>head -n <n>sed -n <val> <path>env <vars> timeout <n> <val> -c <path> <n> >& <path>tail -n <n>python3 -c <script> <n> >& <path>
  71. Other · Source & workspace

    Requested task coordination related to source & workspace.

    1 call · #0176–#0176

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

    Requested code edits related to source & workspace.

    1 call · #0177–#0177

    Write <path>
  73. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0178–#0178

    python3 -c <script>
  74. Inspect · Batching & scheduling

    Requested environment setup or inspection and file and log inspection related to batching & scheduling.

    1 call · #0179–#0179

    env <vars> timeout <n> <val> -c <path> <n> >& <path>tail -n <n>
  75. Execute · Runtime processes

    Requested script or workload execution, workspace file updates and environment setup or inspection related to runtime processes.

    3 calls · #0180–#0182

    python3 -c <script>cd <path>rm -f <path> <path>env <vars> nohup <val> <path> > <path> <n> >& <path>echo <val> > <path>echo <path>
    4 more command sketches
    sleep <n>echo <flag>tail -n <n> <path>curl -s -m <n> <url> <n> >& <path>
  76. Execute · Source & workspace

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

    4 calls · #0183–#0186

    curl -s -m <n> <url> <n> >& <path>curl -s -m <n> -X <val> <url> -H <path> -d <path> <n> <args>head -n <n>tail -n <n>
  77. Other · Source & workspace

    Requested task coordination related to source & workspace.

    2 calls · #0187–#0188

    Update task <task>
  78. Execute · Source & workspace

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

    1 call · #0189–#0189

    echo <val><command> <args>python3 -c <script>wait
  79. Execute · Runtime processes

    Requested process termination, execution waits and runtime inspection related to runtime processes.

    1 call · #0190–#0190

    kill <val> <path> <n> > <path>sleep <n>ps <flag>grep -i <path>grep -v <val>
  80. Inspect · Runtime processes

    Requested workspace file updates, environment setup or inspection and file and log inspection related to runtime processes.

    2 calls · #0191–#0192

    cd <path>rm -rf <path>env <vars> bash <script> <n> >& <path>tail -n <n>echo <flag>
  81. Inspect · Source & workspace

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

    3 calls · #0193–#0195

    cat <path> <n> > <path>head -n <n>echo <flag>headls <path>ls <path> <n> > <path>
    1 more command sketches
    cat <path>
  82. Validate · Benchmark & validation setup

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

    3 calls · #0196–#0198

    mkdir -p <path> <n> > <path>env <vars> bash <script> <n> >& <path>tail -n <n>
  83. Other · Source & workspace

    Requested task coordination related to source & workspace.

    2 calls · #0199–#0200

    Update task <task>
  84. Execute · Benchmark & validation setup

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

    1 call · #0201–#0201

    env <vars> timeout <n> <val> <path> <n> >& <path>tail -n <n>
  85. Inspect · Source & workspace

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

    1 call · #0202–#0202

    ls -l -a <path>tail -n <n>echo <flag>tail -n <n> <path> <n> > <path>head -n <n>cat <path> <n> > <path>
  86. Inspect · Batching & scheduling

    Requested file and log inspection related to batching & scheduling.

    2 calls · #0203–#0204

    cat <path>echo <flag>head -n <n> <path>cat <path> <n> > <path>head -n <n>
  87. Other · Source & workspace

    1 tool error

    Requested tool activity related to source & workspace.

    1 call · #0205–#0205

    shell <script>
  88. Execute · Runtime processes

    Requested workspace file updates, environment setup or inspection and execution waits related to runtime processes.

    1 call · #0206–#0206

    rm -rf <path> <path> <path>cd <path>env <vars> nohup <val> <path> > <path> <n> >& <path>echo <val> > <path>echo <path>sleep <n>
    1 more command sketches
    tail -n <n> <path>
  89. Execute · Source & workspace

    Requested execution waits and service requests related to source & workspace.

    1 call · #0207–#0207

    sleep <n>curl -s -m <n> <url>
  90. Execute · Benchmark & validation setup

    1 tool error

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

    1 call · #0208–#0208

    cat > <path> <script>
  91. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0209–#0209

    Write <path>
  92. Build · Dependencies & build setup

    Requested dependency and build commands, file and log inspection and script or workload execution related to dependencies & build setup.

    1 call · #0210–#0210

    pip install <val> <n> >& <path>tail -n <n>python3 <script>
  93. Inspect · Attention kernels

    Requested script or workload execution and file and log inspection related to attention kernels.

    5 calls · #0211–#0215

    timeout <n> <val> -c <path> <n> >& <path>tail -n <n>
  94. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0216–#0216

    Write <path>
  95. Other · Source & workspace

    1 tool error

    Requested script or workload execution related to source & workspace.

    1 call · #0217–#0217

    python3 -c <script>
  96. Execute · Runtime processes

    Requested process termination, execution waits and runtime inspection related to runtime processes.

    1 call · #0218–#0218

    kill <val> <path> <n> > <path>sleep <n>ps <flag>grep <path>grep -v <val>rm -rf <path> <path> <path>
    6 more command sketches
    cd <path>env <vars> nohup <val> <path> > <path> <n> >& <path>echo <val> > <path>echo <flag>tail -n <n> <path>curl -s -m <n> <url>
  97. Other · Source & workspace

    Requested service requests related to source & workspace.

    1 call · #0219–#0219

    curl -s -m <n> -X <val> <url> -H <path> -d <path> <n> <args>
  98. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0220–#0220

    tail -n <n> <path>
  99. Inspect · Runtime processes

    Requested file and log inspection related to runtime processes.

    1 call · #0221–#0221

    Read <path>
  100. Edit · Runtime processes

    Requested code edits related to runtime processes.

    1 call · #0222–#0222

    Edit <path>
  101. Execute · Runtime processes

    Requested process termination, execution waits and workspace file updates related to runtime processes.

    1 call · #0223–#0223

    kill <val> <path> <n> > <path>sleep <n>rm -rf <path> <path> <path>cd <path>env <vars> nohup <val> <path> > <path> <n> >& <path>echo <val> > <path>
    3 more command sketches
    echo <flag>curl -s -m <n> <url>tail -n <n> <path>
  102. Execute · Source & workspace

    Requested service requests related to source & workspace.

    1 call · #0224–#0224

    curl -s -m <n> -X <val> <url> -H <path> -d <path> <n> <args>
  103. Inspect · Source & workspace

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

    2 calls · #0225–#0226

    tail -n <n> <path>grep -E <val>head -n <n>grep -B <n> -A <n> <val>
  104. Edit · Runtime processes

    Requested code edits related to runtime processes.

    1 call · #0227–#0227

    Edit <path>
  105. Execute · Runtime processes

    Requested process termination, execution waits and workspace file updates related to runtime processes.

    1 call · #0228–#0228

    kill <val> <path> <n> > <path>sleep <n>rm -rf <path> <path> <path>cd <path>env <vars> nohup <val> <path> > <path> <n> >& <path>echo <val> > <path>
    1 more command sketches
    curl -s -m <n> -X <val> <url> -H <path> -d <path> <n> <args>
  106. Execute · Source & workspace

    Requested service requests related to source & workspace.

    1 call · #0229–#0229

    curl -s -m <n> -X <val> <url> -H <path> -d <path> <n> <args>
  107. Inspect · Runtime processes

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

    1 call · #0230–#0230

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

    1 tool error

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

    1 call · #0231–#0231

    cat > <path> <script>python3 <script>
  109. Inspect · Runtime processes

    Requested file and log inspection related to runtime processes.

    2 calls · #0232–#0233

    Read <path>
  110. Inspect · Source & workspace

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

    1 call · #0234–#0234

    curl -s -m <n> -X <val> <url> -H <path> -d <path> <n> <args>tail -n <n>
  111. Other · Source & workspace

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

    2 calls · #0235–#0236

    curl -s -m <n> -X <val> <url> -H <path> -d <path> <n> <args>wc -lgrep -c <val>
  112. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0237–#0237

    Edit <path>
  113. Execute · Runtime processes

    Requested process termination, execution waits and workspace file updates related to runtime processes.

    1 call · #0238–#0238

    kill <val> <path> <n> > <path>sleep <n>rm -rf <path> <path> <path>cd <path>env <vars> nohup <val> <path> > <path> <n> >& <path>echo <val> > <path>
    1 more command sketches
    curl -s -m <n> -X <val> <url> -H <path> -d <path> <n> <args>
  114. Validate · Benchmark & validation setup

    Requested process termination, execution waits and environment setup or inspection related to benchmark & validation setup.

    1 call · #0239–#0239

    kill <val> <path> <n> > <path>sleep <n>env <vars> bash <script> <n> >& <path>tail -n <n>
  115. Execute · Benchmark & validation setup

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

    2 calls · #0240–#0241

    timeout <n> <val> <path> <n> >& <path>tail -n <n>rm -rf <path>ls <path>
  116. Inspect · Batching & scheduling

    Requested file and log inspection related to batching & scheduling.

    1 call · #0242–#0242

    cat <path>tail -n <n>echo <flag>tail -n <n> <path>
  117. Execute · Runtime processes

    Requested workspace file updates, environment setup or inspection and execution waits related to runtime processes.

    1 call · #0243–#0243

    rm -rf <path>mkdir -p <path>rm -rf <path> <path> <path>cd <path>env <vars> nohup <val> <path> > <path> <n> >& <path>echo <val> > <path>
    2 more command sketches
    sleep <n>curl -s -m <n> <url>
  118. Execute · Benchmark & validation setup

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

    2 calls · #0244–#0245

    timeout <n> <val> <path> <n> >& <path>tail -n <n>kill <val> <path> <n> > <path>sleep <n>ps <flag>grep <path>
    4 more command sketches
    grep -v <val>echo <flag>rm -rf <path>env <vars> timeout <n> <val> <path> <n> >& <path>
  119. Inspect · Batching & scheduling

    Requested file and log inspection related to batching & scheduling.

    1 call · #0246–#0246

    cat <path>tail -n <n>echo <flag>tail -n <n> <path>
  120. Inspect · Source & workspace

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

    6 calls · #0247–#0252

    grep -n <val> <path>headecho <flag>sed -n <val> <path>head -n <n>
  121. Inspect · Runtime processes

    Requested source searches related to runtime processes.

    1 call · #0253–#0253

    grep -n <val> <path>
  122. Edit · Runtime processes

    Requested code edits related to runtime processes.

    1 call · #0254–#0254

    Edit <path>
  123. Execute · Runtime processes

    Requested process termination, execution waits and workspace file updates related to runtime processes.

    1 call · #0255–#0255

    kill <val> <path> <n> > <path>sleep <n>rm -rf <path> <path> <path> <path>cd <path>env <vars> nohup <val> <path> > <path> <n> >& <path>echo <val> > <path>
    1 more command sketches
    curl -s -m <n> <url>
  124. Execute · Benchmark & validation setup

    3 tool errors

    Requested process termination, execution waits and workspace file updates related to benchmark & validation setup.

    3 calls · #0256–#0258

    kill <val> <path> <n> > <path>sleep <n>rm -rf <path>env <vars> timeout <n> <val> <path> <n> >& <path>tail -n <n>echo <val>
    7 more command sketches
    waitenv <vars> bash <script> <n> >& <path> > <path>echo <val> > <path>echo <path><command> <args>tail -n <n> <path>cat <path>
  125. Inspect · Benchmark & validation setup

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

    1 call · #0259–#0259

    ps <flag>grep -E <val>grep -v <val>headecho <flag>ls <path>
    2 more command sketches
    head -n <n>wc -l
  126. Execute · Benchmark & validation setup

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

    2 calls · #0260–#0261

    cat <path> <n> > <path>tail -n <n>echo <flag>ls -l -a <path> <n> > <path>ps <flag>grep -i <val>
    3 more command sketches
    grep -v <val>head -n <n>grep <path>
  127. Inspect · Batching & scheduling

    Requested workspace inspection and file and log inspection related to batching & scheduling.

    2 calls · #0262–#0263

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

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

    1 call · #0264–#0264

    ps <flag>grep -E <path>grep -v <val>echo <flag>ls <path>wc -l
    1 more command sketches
    tail -n <n>
  129. Execute · Benchmark & validation setup

    1 tool error

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

    4 calls · #0265–#0268

    cat <path> <n> > <path>tail -n <n>echo <flag>ls -l -a <path> <n> > <path>dateps <flag>
    13 more command sketches
    grep <val>grep -v <val><command> <args>ps -p <val> <path> <n> > <path> <n> > <path>rm -rf <path>nohup <val> -c <path> > <path> <n> >& <path>echo <val> > <path>echo <path>sleep <n>tail -n <n> <path>ls <path>wc -lps -p <val> <path> <n> > <path>
  130. Inspect · Source & workspace

    1 tool error

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

    5 calls · #0269–#0273

    sleep <n>ls <path>wc -ltail -n <n>echo <flag>ps -p <val> <path> <n> > <path>
    5 more command sketches
    dategrep -v <val><command> <args>echo <val>tail -n <n> <val>
  131. Inspect · Batching & scheduling

    Requested file and log inspection related to batching & scheduling.

    1 call · #0274–#0274

    cat <path>head -n <n>echo <flag>
  132. Inspect · Source & workspace

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

    1 call · #0275–#0275

    sleep <n>ls <path>wc -ltail -n <n>echo <flag>ps -p <val> <path> <n> > <path>
    1 more command sketches
    date
  133. Inspect · Batching & scheduling

    Requested file and log inspection related to batching & scheduling.

    1 call · #0276–#0276

    cat <path>tail -n <n>
  134. Inspect · Source & workspace

    1 tool error

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

    2 calls · #0277–#0278

    sleep <n>ls <path>wc -ltail -n <n>echo <flag>ps -p <val> <path> <n> > <path>
    1 more command sketches
    date
  135. Inspect · Batching & scheduling

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

    3 calls · #0279–#0281

    ls <path>grep -E <val>headecho <flag>tail -n <n> <path>sleep <n>
    5 more command sketches
    wc -ltail -n <n>ps -p <val> <path> <n> > <path>datecat <path>
  136. Inspect · Source & workspace

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

    1 call · #0282–#0282

    sleep <n>ls <path>wc -ltail -n <n>echo <flag>ps -p <val> <path> <n> > <path>
    1 more command sketches
    date
  137. Execute · Benchmark & validation setup

    1 tool error

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

    1 call · #0283–#0283

    sleep <n>ls <path>wc -ltail -n <n>echo <flag>ps -p <val> <path> <n> > <path>
    1 more command sketches
    date
  138. Inspect · Source & workspace

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

    1 call · #0284–#0284

    ls <path>wc -ltail -n <n>echo <flag>ps -p <val> <path> <n> > <path>date
  139. Execute · Benchmark & validation setup

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

    1 call · #0285–#0285

    cat <path> <n> > <path>
  140. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0286–#0286

    Write <path>
  141. Other · Source & workspace

    1 tool error

    Requested script or workload execution related to source & workspace.

    1 call · #0287–#0287

    python3 -c <script>
  142. Validate · Benchmark & validation setup

    1 tool error

    Requested process termination, execution waits and workspace file updates related to benchmark & validation setup.

    1 call · #0288–#0288

    kill <val> <path> <n> > <path>sleep <n>rm -rf <path> <path> <path>cd <path>env <vars> nohup <val> <path> > <path> <n> >& <path>echo <val> > <path>
    2 more command sketches
    curl -s -m <n> -X <val> <url> -H <path> -d <path> <n> <args>python3 -c <script>
  143. Execute · Runtime processes

    Requested execution waits, service requests and file and log inspection related to runtime processes.

    1 call · #0289–#0289

    sleep <n>curl -s -m <n> <url>echo <flag>tail -n <n> <path>
  144. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0290–#0290

    Edit <path>
  145. Inspect · Runtime processes

    Requested process termination, execution waits and workspace file updates related to runtime processes.

    1 call · #0291–#0291

    kill <val> <path> <n> > <path>sleep <n>rm -rf <path> <path> <path>cd <path>env <vars> nohup <val> <path> > <path> <n> >& <path>echo <val> > <path>
    2 more command sketches
    curl -s -m <n> -X <val> <url> -H <path> -d <path> <n> <args>python3 -c <script>
  146. Inspect · Source & workspace

    Requested script or workload execution and file and log inspection related to source & workspace.

    1 call · #0292–#0292

    python3 <script> <n> >& <path>tail -n <n>
  147. Execute · Benchmark & validation setup

    1 tool error

    Requested process termination, execution waits and workspace file updates related to benchmark & validation setup.

    1 call · #0293–#0293

    kill <val> <path> <n> > <path>sleep <n>rm -rf <path>nohup <val> -c <path> > <path> <n> >& <path>echo <val> > <path>echo <val>
    3 more command sketches
    ls <path>wc -ltail -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.

openbuild_solution · 5 changed files

Base commit: 8f62ee8f410c38ae7cd90305300afd08f0fdb098

diff --git a/solution/bootstrap.sh b/solution/bootstrap.shnew file mode 100755index 0000000000000000000000000000000000000000..650670fe031b6f913b5dbf0c5ae1742f20f97cb9--- /dev/null+++ b/solution/bootstrap.sh@@ -0,0 +1,63 @@+#!/usr/bin/env bash+# Bootstrap for the Qwen3-8B OpenBuild serving system.+#+# The base runtime already supplies Python, PyTorch, torch_npu, the+# transformers stack, and the read-only Ascend runtime components.  This+# script performs only the offline-replayable preparation that the+# serving system needs: verify the runtime, materialize the runtime+# directory, and warm-load the model weights so the actual launch path+# can come up quickly.+set -euo pipefail++SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+SOLUTION_DIR="${OPENBUILD_SOLUTION_DIR:-${SCRIPT_DIR}}"+ENV_DIR="${OPENBUILD_ENV_DIR:-${TASK_HOME:-/tmp}/openbuild-runtime}"++mkdir -p "${ENV_DIR}"+mkdir -p "${ENV_DIR}/logs"++PYTHON_BIN="${PYTHON_BIN:-python3}"+if ! command -v "${PYTHON_BIN}" >/dev/null 2>&1; then+    echo "[bootstrap] python3 is unavailable" >&2+    exit 1+fi++# Probe the runtime once so we fail fast on a misconfigured host.+"${PYTHON_BIN}" - <<'PY'+import sys, json+try:+    import torch+    import torch_npu+except ImportError as exc:+    print(f"[bootstrap] missing torch/torch_npu: {exc}", file=sys.stderr)+    sys.exit(1)+if not torch.npu.is_available():+    print("[bootstrap] torch.npu.is_available() returned False", file=sys.stderr)+    sys.exit(1)+if torch.npu.device_count() < 1:+    print("[bootstrap] no Ascend devices visible", file=sys.stderr)+    sys.exit(1)+import transformers  # noqa: F401+PY++# Validate the model and tokenizer paths.+MODEL_PATH="${OPENBUILD_MODEL_PATH:-}"+TOKENIZER_PATH="${OPENBUILD_TOKENIZER_PATH:-${MODEL_PATH}}"+if [[ -z "${MODEL_PATH}" || ! -d "${MODEL_PATH}" ]]; then+    echo "[bootstrap] OPENBUILD_MODEL_PATH is missing or not a directory" >&2+    exit 1+fi+if [[ ! -f "${MODEL_PATH}/config.json" || ! -f "${MODEL_PATH}/tokenizer.json" ]]; then+    echo "[bootstrap] model projection is missing config.json or tokenizer.json" >&2+    exit 1+fi+if [[ ! -d "${TOKENIZER_PATH}" ]]; then+    echo "[bootstrap] tokenizer projection is not a directory" >&2+    exit 1+fi++echo "[bootstrap] solution_dir=${SOLUTION_DIR}"+echo "[bootstrap] env_dir=${ENV_DIR}"+echo "[bootstrap] model_path=${MODEL_PATH}"+echo "[bootstrap] tokenizer_path=${TOKENIZER_PATH}"+echo "[bootstrap] done"\ No newline at end of filediff --git a/solution/engine.py b/solution/engine.pynew file mode 100644index 0000000000000000000000000000000000000000..c7740b2eac9d3ec5908c883a091bd4272c1cbfbd--- /dev/null+++ b/solution/engine.py@@ -0,0 +1,382 @@+"""Continuous-batched inference engine for Qwen3-8B on Ascend NPU.++The engine loads the reference transformers Qwen3 model once and then+manages a pool of per-group ``DynamicCache`` instances.  Prefill and+decode are both batched across requests sharing identical cache+length, amortising per-token cost.+"""+from __future__ import annotations++import asyncio+import os+import threading+import time+from dataclasses import dataclass, field+from typing import Any, List, Optional++import torch++import torch_npu  # noqa: F401+from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer+from transformers.cache_utils import DynamicCache+++class _Sink:+    """Async queue used to deliver decoded tokens to a request."""++    def __init__(self) -> None:+        self.queue: asyncio.Queue = asyncio.Queue(maxsize=8192)++    def push(self, item: Any) -> None:+        try:+            self.queue.put_nowait(item)+        except asyncio.QueueFull:+            pass++    def push_blocking(self, item: Any) -> None:+        try:+            self.queue.put_nowait(item)+        except asyncio.QueueFull:+            pass+++@dataclass+class _Group:+    cache: DynamicCache+    slots: list[Optional[str]]+    prompt_len: int+    length: int = 0++    def alloc(self, request_id: str) -> int:+        for idx, slot in enumerate(self.slots):+            if slot is None:+                self.slots[idx] = request_id+                return idx+        raise RuntimeError("group full")++    def free(self, slot: int) -> None:+        self.slots[slot] = None++    def active_slots(self) -> list[int]:+        return [idx for idx, slot in enumerate(self.slots) if slot is not None]+++@dataclass+class RequestState:+    request_id: str+    group_id: int+    slot: int = -1+    prompt_ids: list[int] = field(default_factory=list)+    prompt_len: int = 0+    last_token: int = 0+    emitted: list[int] = field(default_factory=list)+    max_new_tokens: int = 0+    ignore_eos: bool = False+    eos_token_id: int = 0+    sink: _Sink | None = None+    done: bool = False+    finish_reason: str | None = None+    arrival_time: float = 0.0+    first_token_time: float | None = None+    last_token_time: float | None = None+    error: str | None = None+++class Qwen3Engine:+    """Reference-model backed inference engine."""++    def __init__(self, model_path: str, device: torch.device,+                 max_batch: int, max_seq_len: int) -> None:+        self.device = device+        self.max_batch = max_batch+        self.max_seq_len = max_seq_len++        torch.npu.set_device(device)++        self.config = AutoConfig.from_pretrained(model_path, local_files_only=True)+        self.tokenizer = AutoTokenizer.from_pretrained(model_path, local_files_only=True)++        self.model = AutoModelForCausalLM.from_pretrained(+            model_path,+            dtype=torch.bfloat16,+            low_cpu_mem_usage=True,+            local_files_only=True,+            attn_implementation="flash_attention_2",+        ).to(device)+        self.model.eval()+        for p in self.model.parameters():+            p.requires_grad_(False)++        self.num_layers = len(self.model.model.layers)+        self.eos_token_id = self.config.eos_token_id if isinstance(+            self.config.eos_token_id, int+        ) else int(self.tokenizer.eos_token_id)++    def encode_messages(self, messages):+        encoded = self.tokenizer.apply_chat_template(+            messages, tokenize=True, add_generation_prompt=True,+        )+        if hasattr(encoded, "input_ids"):+            encoded = encoded["input_ids"]+        if isinstance(encoded, list) and encoded and isinstance(encoded[0], list):+            encoded = encoded[0]+        return list(encoded)+++class AsyncScheduler:+    """Continuous-batched scheduler using one DynamicCache per group."""++    def __init__(self, engine: Qwen3Engine) -> None:+        self.engine = engine+        self._lock = threading.Lock()+        self._active: dict[str, RequestState] = {}+        self._pending: list[RequestState] = []+        self._groups: dict[int, _Group] = {}+        self._next_group_id = 0+        self._wake = threading.Event()+        self._stop = False++    def submit(self, state: RequestState) -> None:+        with self._lock:+            self._pending.append(state)+            self._wake.set()++    def shutdown(self) -> None:+        self._stop = True+        self._wake.set()++    def run(self) -> None:+        torch.npu.set_device(self.engine.device)+        while not self._stop:+            progressed = self._admit_pending()+            progressed |= self._step()+            if not progressed:+                self._wake.wait(timeout=0.002)+                self._wake.clear()+        torch.npu.synchronize()++    # ------------------------------------------------------------------+    def _find_or_make_group(self, prompt_len: int) -> _Group:+        for gid, group in self._groups.items():+            if group.length == prompt_len and len(group.active_slots()) < self.engine.max_batch:+                return group+        gid = self._next_group_id+        self._next_group_id += 1+        cache = DynamicCache()+        slots: list[Optional[str]] = [None] * self.engine.max_batch+        group = _Group(cache=cache, slots=slots, prompt_len=prompt_len,+                       length=prompt_len)+        self._groups[gid] = group+        return group++    def _admit_pending(self) -> bool:+        """Batch-admit pending requests with the same prompt length."""+        with self._lock:+            pending = list(self._pending)+        if not pending:+            return False+        # Group by prompt_len.+        by_len: dict[int, list[RequestState]] = {}+        for state in pending:+            by_len.setdefault(state.prompt_len, []).append(state)+        progressed = False+        for prompt_len, group_states in by_len.items():+            if not self._admit_group(prompt_len, group_states):+                continue+            progressed = True+        return progressed++    def _admit_group(self, prompt_len: int,+                     states: list[RequestState]) -> bool:+        """Admit up to one batch of same-length requests."""+        # Find or create a group with room.+        group = None+        for gid, g in self._groups.items():+            if g.length == prompt_len and len(g.active_slots()) < self.engine.max_batch:+                group = g+                state_group_id = gid+                break+        if group is None:+            gid = self._next_group_id+            self._next_group_id += 1+            cache = DynamicCache()+            slots: list[Optional[str]] = [None] * self.engine.max_batch+            group = _Group(cache=cache, slots=slots,+                           prompt_len=prompt_len, length=prompt_len)+            self._groups[gid] = group+            state_group_id = gid+        # Allocate slots for as many requests as fit.+        active = group.active_slots()+        free = self.engine.max_batch - len(active)+        if free <= 0:+            return False+        chosen = states[:free]+        # Prepare batched prefill input.+        device = self.engine.device+        prompt_lens = {len(s.prompt_ids) for s in chosen}+        if len(prompt_lens) != 1:+            # If for some reason prompts differ in length, fall back to+            # serial single-row prefill.+            for s in chosen:+                self._admit_single(s, group, state_group_id)+            return True+        # All chosen requests share the same prompt length.+        B = len(chosen)+        input_ids = torch.tensor(+            [s.prompt_ids for s in chosen], dtype=torch.long, device=device,+        )+        try:+            with torch.no_grad():+                out = self.engine.model(+                    input_ids,+                    past_key_values=group.cache,+                    use_cache=True,+                    num_logits_to_keep=1,+                )+            torch.npu.synchronize()+            next_tokens = out.logits[:, -1, :].argmax(dim=-1).tolist()+        except Exception as exc:  # noqa: BLE001+            for s in chosen:+                s.error = str(exc)+                s.done = True+                s.finish_reason = "error"+                if s.sink is not None:+                    s.sink.push_blocking({"error": str(exc)})+                    s.sink.push_blocking({"done": True})+            with self._lock:+                for s in chosen:+                    if s in self._pending:+                        self._pending.remove(s)+            return True+        # Allocate slots and notify.+        now = time.monotonic()+        with self._lock:+            for s, token in zip(chosen, next_tokens):+                slot = group.alloc(s.request_id)+                s.slot = slot+                s.group_id = state_group_id+                s.last_token = token+                s.first_token_time = now+                self._active[s.request_id] = s+                if s in self._pending:+                    self._pending.remove(s)+            # Push first token to each client outside the lock.+        for s, token in zip(chosen, next_tokens):+            self._push_token(s, token)+        return True++    def _admit_single(self, state: RequestState, group: _Group,+                      gid: int) -> None:+        """Fallback path: serial single-row prefill for one request."""+        device = self.engine.device+        slot = group.alloc(state.request_id)+        state.slot = slot+        state.group_id = gid+        try:+            input_ids = torch.tensor(+                [state.prompt_ids], dtype=torch.long, device=device,+            )+            with torch.no_grad():+                out = self.engine.model(+                    input_ids,+                    past_key_values=group.cache,+                    use_cache=True,+                    num_logits_to_keep=1,+                )+            torch.npu.synchronize()+            state.last_token = int(out.logits[0, -1, :].argmax(dim=-1).item())+            state.first_token_time = time.monotonic()+            with self._lock:+                self._active[state.request_id] = state+                if state in self._pending:+                    self._pending.remove(state)+            self._push_token(state, state.last_token)+        except Exception as exc:  # noqa: BLE001+            state.error = str(exc)+            state.done = True+            state.finish_reason = "error"+            if state.sink is not None:+                state.sink.push_blocking({"error": str(exc)})+                state.sink.push_blocking({"done": True})+            with self._lock:+                if state in self._pending:+                    self._pending.remove(state)++    # ------------------------------------------------------------------+    def _step(self) -> bool:+        with self._lock:+            active = dict(self._active)+        if not active:+            return False+        by_group: dict[int, list[RequestState]] = {}+        for state in active.values():+            if state.done:+                continue+            by_group.setdefault(state.group_id, []).append(state)+        progressed = False+        for gid, states in by_group.items():+            if self._step_group(self._groups[gid], states):+                progressed = True+        return progressed++    def _step_group(self, group: _Group, states: list[RequestState]) -> bool:+        if not states:+            return False+        cache = group.cache+        active_slots = group.active_slots()+        if not active_slots:+            return False+        slot_to_state = {s.slot: s for s in states}+        rows = [slot_to_state[slot] for slot in active_slots]+        device = self.engine.device+        input_ids = torch.tensor(+            [[s.last_token] for s in rows], dtype=torch.long, device=device,+        )+        try:+            with torch.no_grad():+                out = self.engine.model(+                    input_ids,+                    past_key_values=cache,+                    use_cache=True,+                    num_logits_to_keep=1,+                )+            torch.npu.synchronize()+            next_tokens = out.logits[:, -1, :].argmax(dim=-1).tolist()+        except Exception as exc:  # noqa: BLE001+            for s in rows:+                s.error = str(exc)+                s.done = True+                s.finish_reason = "error"+                if s.sink is not None:+                    s.sink.push_blocking({"error": str(exc)})+                    s.sink.push_blocking({"done": True})+            return False+        group.length += 1+        completed: list[tuple[RequestState, int]] = []+        for state, token in zip(rows, next_tokens):+            state.last_token = token+            state.last_token_time = time.monotonic()+            reason = None+            if token == state.eos_token_id and not state.ignore_eos:+                reason = "stop"+            elif len(state.emitted) + 1 >= state.max_new_tokens:+                reason = "length"+            elif group.length >= self.engine.max_seq_len:+                reason = "length"+            self._push_token(state, token)+            if reason is not None:+                state.done = True+                state.finish_reason = reason+                if state.sink is not None:+                    state.sink.push_blocking({"done": True})+                completed.append((state, state.slot))+        for state, slot in completed:+            group.free(slot)+            with self._lock:+                self._active.pop(state.request_id, None)+        return True++    def _push_token(self, state: RequestState, token: int) -> None:+        state.emitted.append(token)+        if state.sink is not None:+            state.sink.push({"token": token})\ No newline at end of filediff --git a/solution/launch.sh b/solution/launch.shnew file mode 100755index 0000000000000000000000000000000000000000..9e0073c22c8959b8ee5703a59f78ddfeeabf02f8--- /dev/null+++ b/solution/launch.sh@@ -0,0 +1,64 @@+#!/usr/bin/env bash+# Launch the Qwen3-8B OpenBuild serving system in the foreground.+#+# The launch script owns every child process in its process group and+# binds a single HTTP service to ${OPENBUILD_HOST}:${OPENBUILD_PORT}.+set -euo pipefail++SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+SOLUTION_DIR="${OPENBUILD_SOLUTION_DIR:-${SCRIPT_DIR}}"+ENV_DIR="${OPENBUILD_ENV_DIR:-${TASK_HOME:-/tmp}/openbuild-runtime}"+mkdir -p "${ENV_DIR}/logs"++HOST="${OPENBUILD_HOST:-127.0.0.1}"+PORT="${OPENBUILD_PORT:-8080}"+DEVICE_ID="${ASCEND_RT_VISIBLE_DEVICES:-${OPENBUILD_DEVICE_IDS:-0}}"+MODEL_PATH="${OPENBUILD_MODEL_PATH:-}"+TOKENIZER_PATH="${OPENBUILD_TOKENIZER_PATH:-${MODEL_PATH}}"+SERVED_MODEL="${OPENBUILD_SERVED_MODEL:-Qwen/Qwen3-8B}"++if [[ -z "${MODEL_PATH}" ]]; then+    echo "[launch] OPENBUILD_MODEL_PATH is empty" >&2+    exit 1+fi+if [[ -z "${TOKENIZER_PATH}" ]]; then+    echo "[launch] OPENBUILD_TOKENIZER_PATH is empty" >&2+    exit 1+fi++export OPENBUILD_SOLUTION_DIR="${SOLUTION_DIR}"+export OPENBUILD_ENV_DIR="${ENV_DIR}"+export OPENBUILD_MODEL_PATH="${MODEL_PATH}"+export OPENBUILD_TOKENIZER_PATH="${TOKENIZER_PATH}"+export OPENBUILD_SERVED_MODEL="${SERVED_MODEL}"+export OPENBUILD_HOST="${HOST}"+export OPENBUILD_PORT="${PORT}"+export OPENBUILD_DEVICE_IDS="${DEVICE_ID}"+export ASCEND_RT_VISIBLE_DEVICES="${DEVICE_ID}"+export PYTHONPATH="${SOLUTION_DIR}:${PYTHONPATH:-}"+export PYTHONNOUSERSITE=1+export PYTHONSAFEPATH=1+export PYTHONDONTWRITEBYTECODE=1+export PYTHONUNBUFFERED=1+export HF_HUB_OFFLINE=1+export TRANSFORMERS_OFFLINE=1+export TOKENIZERS_PARALLELISM=false+export OMP_NUM_THREADS="${OMP_NUM_THREADS:-4}"+export TASK_MODE="${TASK_MODE:-normal}"++# Trap signals to ensure the child server is torn down cleanly.+SERVER_PID=""+cleanup() {+    local signal="$1"+    if [[ -n "${SERVER_PID}" ]] && kill -0 "${SERVER_PID}" 2>/dev/null; then+        kill -"${signal}" "${SERVER_PID}" 2>/dev/null || true+    fi+}+trap 'cleanup TERM; wait 2>/dev/null || true' TERM+trap 'cleanup INT; wait 2>/dev/null || true' INT+trap 'cleanup HUP; wait 2>/dev/null || true' HUP++PYTHON_BIN="${PYTHON_BIN:-python3}"+exec "${PYTHON_BIN}" -u "${SOLUTION_DIR}/server.py" &+SERVER_PID=$!+wait "${SERVER_PID}"\ No newline at end of filediff --git a/solution/manifest.json b/solution/manifest.jsonnew file mode 100644index 0000000000000000000000000000000000000000..2c6a4ba48f679cc1eb7d500b6f78a92ae676c45e--- /dev/null+++ b/solution/manifest.json@@ -0,0 +1,10 @@+{+  "schema_version": 1,+  "kind": "openbuild_solution",+  "task_id": "openbuild_serving_qwen3_8b_1dev_v1",+  "model": "Qwen/Qwen3-8B",+  "framework": "openbuild-npu-engine",+  "bootstrap": "bootstrap.sh",+  "launch": "launch.sh",+  "offline_replay": true+}\ No newline at end of filediff --git a/solution/server.py b/solution/server.pynew file mode 100644index 0000000000000000000000000000000000000000..05bfc20de4dc6f6f79e19700e43e2ea9fee44bea--- /dev/null+++ b/solution/server.py@@ -0,0 +1,373 @@+#!/usr/bin/env python3+"""HTTP entrypoint for the OpenBuild Qwen3-8B serving system.++The server wraps the continuous-batching ``AsyncScheduler`` behind an+OpenAI-compatible HTTP surface implemented with FastAPI + uvicorn.  The+inference engine runs on a dedicated background thread that owns the+NPU; the FastAPI loop merely translates HTTP requests into scheduler+submissions and streams tokens back as Server-Sent Events.+"""+from __future__ import annotations++import argparse+import asyncio+import json+import logging+import os+import signal+import sys+import threading+import time+import uuid+from typing import Any, AsyncIterator++import torch+import torch_npu  # noqa: F401  (registers NPU as a torch device)+import uvicorn+from fastapi import FastAPI, HTTPException, Request+from fastapi.responses import JSONResponse, StreamingResponse++from engine import AsyncScheduler, Qwen3Engine, RequestState, _Sink+++LOG = logging.getLogger("openbuild.serving")+logging.basicConfig(+    level=logging.INFO,+    format="%(asctime)s %(levelname)s %(name)s %(message)s",+)+++SERVED_MODEL = os.environ.get("OPENBUILD_SERVED_MODEL", "Qwen/Qwen3-8B")+HOST = os.environ.get("OPENBUILD_HOST", "127.0.0.1")+PORT = int(os.environ.get("OPENBUILD_PORT", "8080"))+DEVICE_IDS = os.environ.get("OPENBUILD_DEVICE_IDS", "0")+MODEL_PATH = os.environ.get("OPENBUILD_MODEL_PATH", "")+TOKENIZER_PATH = os.environ.get("OPENBUILD_TOKENIZER_PATH", MODEL_PATH)+ENV_DIR = os.environ.get("OPENBUILD_ENV_DIR", "/tmp/openbuild-runtime")+MAX_BATCH = int(os.environ.get("OPENBUILD_MAX_BATCH", "64"))+MAX_SEQ_LEN = int(os.environ.get("OPENBUILD_MAX_SEQ_LEN", "4096"))+++# Engine + scheduler are populated at startup so the worker thread can+# pick them up after the model is loaded on the NPU.+ENGINE: Qwen3Engine | None = None+SCHEDULER: AsyncScheduler | None = None+SCHEDULER_THREAD: threading.Thread | None = None+++def _create_ids() -> str:+    return uuid.uuid4().hex+++# ---------------------------------------------------------------------------+# Token / message helpers+# ---------------------------------------------------------------------------+++def _coerce_message(message: Any) -> dict[str, str]:+    if not isinstance(message, dict):+        raise HTTPException(400, "messages entries must be objects")+    role = message.get("role")+    content = message.get("content")+    if role not in {"system", "user", "assistant"}:+        raise HTTPException(400, "unsupported message role")+    if not isinstance(content, str):+        raise HTTPException(400, "message content must be a string")+    return {"role": role, "content": content}+++def _validate_chat_body(body: dict[str, Any]) -> dict[str, Any]:+    if body.get("model") != SERVED_MODEL:+        raise HTTPException(400, f"unknown model '{body.get('model')}'")+    messages = body.get("messages")+    if not isinstance(messages, list) or not messages:+        raise HTTPException(400, "messages must be a non-empty list")+    coerced = [_coerce_message(m) for m in messages]+    temperature = body.get("temperature", 0.0)+    if temperature != 0:+        # Strictly greedy per the contract.+        temperature = 0.0+    max_tokens = body.get("max_tokens")+    if max_tokens is None:+        max_tokens = body.get("max_completion_tokens")+    if not isinstance(max_tokens, int) or not 1 <= max_tokens <= MAX_SEQ_LEN:+        raise HTTPException(400, "max_tokens out of range")+    stream = bool(body.get("stream", False))+    seed = body.get("seed", 0)+    ignore_eos = bool(body.get("ignore_eos", False))+    stream_options = body.get("stream_options") or {}+    include_usage = bool(stream_options.get("include_usage", False))+    return {+        "messages": coerced,+        "temperature": 0.0,+        "max_tokens": max_tokens,+        "stream": stream,+        "seed": seed,+        "ignore_eos": ignore_eos,+        "include_usage": include_usage,+    }+++# ---------------------------------------------------------------------------+# Streaming helpers+# ---------------------------------------------------------------------------+++async def _drain_sink(sink: _Sink) -> AsyncIterator[dict[str, Any]]:+    """Yield everything currently queued, then wait for the next item."""+    while True:+        item = await sink.queue.get()+        yield item+++async def _stream_response(state: RequestState,+                           completion_id: str,+                           created_ts: int,+                           include_usage: bool) -> AsyncIterator[bytes]:+    first_token_emitted = False+    while True:+        item = await state.sink.queue.get()+        if "error" in item:+            err_payload = {+                "id": completion_id,+                "object": "chat.completion.chunk",+                "created": created_ts,+                "model": SERVED_MODEL,+                "choices": [+                    {"index": 0, "delta": {}, "finish_reason": "error"}+                ],+            }+            yield _sse_line(err_payload)+            yield _sse_done()+            return+        if "done" in item:+            break+        token = item["token"]+        text = ENGINE.tokenizer.decode(+            [token], skip_special_tokens=True,+        )+        if not first_token_emitted:+            chunk = {+                "id": completion_id,+                "object": "chat.completion.chunk",+                "created": created_ts,+                "model": SERVED_MODEL,+                "choices": [+                    {"index": 0, "delta": {"role": "assistant", "content": text},+                     "finish_reason": None}+                ],+            }+            first_token_emitted = True+        else:+            chunk = {+                "id": completion_id,+                "object": "chat.completion.chunk",+                "created": created_ts,+                "model": SERVED_MODEL,+                "choices": [+                    {"index": 0, "delta": {"content": text},+                     "finish_reason": None}+                ],+            }+        yield _sse_line(chunk)++    # Final chunk with finish_reason; always include usage when requested.+    final_chunk: dict[str, Any] = {+        "id": completion_id,+        "object": "chat.completion.chunk",+        "created": created_ts,+        "model": SERVED_MODEL,+        "choices": [+            {"index": 0, "delta": {}, "finish_reason": state.finish_reason or "stop"}+        ],+    }+    if include_usage:+        final_chunk["usage"] = {+            "prompt_tokens": state.prompt_len,+            "completion_tokens": len(state.emitted),+            "total_tokens": state.prompt_len + len(state.emitted),+        }+    yield _sse_line(final_chunk)+    yield _sse_done()+++def _sse_line(payload: dict[str, Any]) -> bytes:+    return ("data: " + json.dumps(payload, ensure_ascii=False) + "\n\n").encode("utf-8")+++def _sse_done() -> bytes:+    return b"data: [DONE]\n\n"+++# ---------------------------------------------------------------------------+# FastAPI application+# ---------------------------------------------------------------------------+++app = FastAPI()+++@app.get("/v1/models")+async def list_models() -> JSONResponse:+    return JSONResponse({+        "object": "list",+        "data": [+            {+                "id": SERVED_MODEL,+                "object": "model",+                "created": int(time.time()),+                "owned_by": "openbuild",+            }+        ],+    })+++@app.get("/health")+async def health() -> JSONResponse:+    return JSONResponse({"status": "ok"})+++async def _handle_chat(request: Request) -> JSONResponse | StreamingResponse:+    raw = await request.json()+    if not isinstance(raw, dict):+        raise HTTPException(400, "body must be a JSON object")+    params = _validate_chat_body(raw)+    completion_id = "chatcmpl-" + _create_ids()+    created_ts = int(time.time())++    prompt_ids = ENGINE.encode_messages(params["messages"])+    if len(prompt_ids) >= MAX_SEQ_LEN - 1:+        raise HTTPException(400, "prompt exceeds maximum context length")++    sink = _Sink()+    state = RequestState(+        request_id=completion_id,+        group_id=-1,+        prompt_ids=prompt_ids,+        prompt_len=len(prompt_ids),+        last_token=0,+        max_new_tokens=params["max_tokens"],+        ignore_eos=params["ignore_eos"],+        eos_token_id=ENGINE.eos_token_id,+        sink=sink,+        arrival_time=time.monotonic(),+    )+    SCHEDULER.submit(state)++    if not params["stream"]:+        # Non-streaming: collect all emitted tokens before returning.+        emitted: list[int] = []+        finish_reason: str | None = None+        while True:+            item = await sink.queue.get()+            if "error" in item:+                raise HTTPException(500, item["error"])+            if "done" in item:+                finish_reason = state.finish_reason or "stop"+                break+            emitted.append(item["token"])+        text = ENGINE.tokenizer.decode(emitted, skip_special_tokens=True)+        response = {+            "id": completion_id,+            "object": "chat.completion",+            "created": created_ts,+            "model": SERVED_MODEL,+            "choices": [+                {+                    "index": 0,+                    "message": {"role": "assistant", "content": text},+                    "finish_reason": finish_reason,+                }+            ],+            "usage": {+                "prompt_tokens": state.prompt_len,+                "completion_tokens": len(emitted),+                "total_tokens": state.prompt_len + len(emitted),+            },+        }+        return JSONResponse(response)++    # Streaming: hand control to a generator that pumps the sink.+    generator = _stream_response(+        state, completion_id, created_ts, params["include_usage"]+    )+    return StreamingResponse(generator, media_type="text/event-stream")+++@app.post("/v1/chat/completions")+async def chat_completions(request: Request):+    return await _handle_chat(request)+++# ---------------------------------------------------------------------------+# Startup+# ---------------------------------------------------------------------------+++def _initialise_engine() -> None:+    global ENGINE, SCHEDULER, SCHEDULER_THREAD+    if ENGINE is not None:+        return+    LOG.info("Initialising Qwen3 engine on %s", DEVICE_IDS)+    device = torch.device(f"npu:{DEVICE_IDS}")+    ENGINE = Qwen3Engine(+        model_path=MODEL_PATH,+        device=device,+        max_batch=MAX_BATCH,+        max_seq_len=MAX_SEQ_LEN,+    )+    LOG.info("Engine ready: %d layers, max_batch=%d, max_seq=%d",+             ENGINE.num_layers, MAX_BATCH, MAX_SEQ_LEN)+    SCHEDULER = AsyncScheduler(ENGINE)+    SCHEDULER_THREAD = threading.Thread(+        target=SCHEDULER.run, name="scheduler", daemon=True+    )+    SCHEDULER_THREAD.start()+    LOG.info("Scheduler started")+++@app.on_event("startup")+async def _on_startup() -> None:+    _initialise_engine()+++@app.on_event("shutdown")+async def _on_shutdown() -> None:+    if SCHEDULER is not None:+        SCHEDULER.shutdown()+++def _install_signal_handlers(loop: asyncio.AbstractEventLoop) -> None:+    def _stop(*_args: Any) -> None:+        LOG.info("Received termination signal")+        if SCHEDULER is not None:+            SCHEDULER.shutdown()+        for task in asyncio.all_tasks(loop):+            task.cancel()+        loop.stop()++    for sig in (signal.SIGTERM, signal.SIGINT):+        try:+            loop.add_signal_handler(sig, _stop)+        except (NotImplementedError, RuntimeError):+            pass+++def main() -> None:+    if not MODEL_PATH:+        print("OPENBUILD_MODEL_PATH is empty", file=sys.stderr)+        sys.exit(1)+    config = uvicorn.Config(+        app,+        host=HOST,+        port=PORT,+        log_level="warning",+        access_log=False,+        loop="asyncio",+    )+    server = uvicorn.Server(config)+    server.run()+++if __name__ == "__main__":+    main()\ No newline at end of file