Inspect · Source & workspace
Requested workspace inspection related to source & workspace.
1 call · #0001–#0001
echo <val>ls -l -a <val> <n> > <path>Claude Opus 5 · Training
Qwen3-8B system training 4dev · Joint Optimization
01 / PROCESS MAP
Each row shows one agent’s tool events in its own recorded order. Colors show broad activities; bar widths do not represent duration.
Main agentClaude Opus 5 · 192 visible calls
02 / EVENT SEQUENCE
Requests are grouped by agent, activity and topic. Delegations open into child branches. Summaries describe visible requests; tool errors and missing responses are flagged. A recorded response does not establish command success or a performance improvement.
Scroll within this panel to view all events. Command sketches retain familiar programs and options. Values become <val> or <n>; paths, addresses and script bodies are hidden as <path>, <url> and <script>.
Requested workspace inspection related to source & workspace.
1 call · #0001–#0001
echo <val>ls -l -a <val> <n> > <path>Requested file and log inspection and workspace inspection related to task requirements.
3 calls · #0002–#0004
Read <path>cd <path>ls -l -a <val> <val> <val> <val> <val> <path>Requested file and log inspection related to task requirements.
1 call · #0005–#0005
cd <path><command> <args>cat <val>Requested file and log inspection related to source & workspace.
2 calls · #0006–#0007
Read <path>Requested file and log inspection, environment setup or inspection and source searches related to device memory.
1 call · #0008–#0008
cd <path>cat <path>echo <val><command> <args>head <flag>envgrep -i <val>sortRequested file and log inspection and repository inspection related to source & workspace.
1 call · #0009–#0009
cat <path>echo <val>git log --oneline <flag>git status <flag>headcd <path>Requested workspace file updates and script or workload execution related to benchmark & validation setup.
1 call · #0010–#0010
cd <path>mkdir -p <path>rm -rf <path> <path> <n> > <path>bash <script> > <path> <n> > <path>echo <val>Requested workspace inspection and file and log inspection related to source & workspace.
3 calls · #0011–#0013
cd <path>lsecho <val>ls <path>head -n <n>ls -l -a <val> <n> > <path>echo <flag>tail -n <n> <path> <n> > <path>cat <path>wc -l <path> <path> <path>Requested source searches and file and log inspection related to checkpoints & weight state.
1 call · #0014–#0014
cd <path>grep -n <val> <path>head -n <n>Requested file and log inspection related to source & workspace.
1 call · #0015–#0015
Read <path>Requested workspace inspection, file and log inspection and source searches related to benchmark & validation setup.
1 call · #0016–#0016
ls -l -a <val>head -n <n>echo <flag>grep -c <val> <path> <n> > <path>grep <val> <path> <n> > <path>tail -n <n>Requested execution waits, file and log inspection and source searches related to source & workspace.
1 call · #0017–#0017
sleep <n>tail -n <n> <path>echo <flag>grep -c <val> <path>ls <val>Requested source searches and file and log inspection related to optimizer & gradients.
1 call · #0018–#0018
grep <val> <path>echo <val>grep -E <val> <path>headRequested execution waits, source searches and file and log inspection related to benchmark & validation setup.
1 call · #0019–#0019
sleep <n>grep <val> <path> <n> > <path>sed -E <path>echo <flag>tail -n <n> <path>Requested source searches and file and log inspection related to optimizer & gradients.
1 call · #0020–#0020
cd <val>grep -E <val> <val>head -n <n>Requested script or workload execution related to benchmark & validation setup.
1 call · #0021–#0021
cd <path>python3 -c <script>Requested source searches and file and log inspection related to source & workspace.
3 calls · #0022–#0024
cd <path>grep -n <val> <path> <path> <path> <path> <n> > <path>head -n <n>echo <val>grep -n <val> <path>sed -n <val> <path>grep -r -n <val> --include <path> <path>grep -r -n <val> --include <path> <path> <path>headRequested file and log inspection related to parallelism & communication.
1 call · #0025–#0025
cd <path>sed -n <val> <path>echo <val>cat <path>Requested file and log inspection and source searches related to source & workspace.
4 calls · #0026–#0029
cd <path>tail -n <n> <path>echo <val>grep -n <val> -A <n> <path>grep -n <val>head -n <n>echo <flag>cat <path>grep -n <val> <path>sed -n <path> <path><command> <args>cut <flag> <args>sed -n <val> <path>Requested source searches and file and log inspection related to checkpoints & weight state.
1 call · #0030–#0030
cd <path>grep -n <val> <path>sed -n <val>Requested file and log inspection related to source & workspace.
1 call · #0031–#0031
cd <path>sed -n <val> <path>Requested source searches and file and log inspection related to optimizer & gradients.
2 calls · #0032–#0033
grep -r -n <val> --include <path> <path>grep -v <val>head -n <n>echo <val>sed -n <val> <path>cd <path>headRequested source searches and file and log inspection related to parallelism & communication.
2 calls · #0034–#0035
grep -r -n <val> --include <path> <path> <path> <n> > <path>grep -v <val>head -n <n>sed -n <val> <path>echo <val>grep -n <val> <path>Requested script or workload execution and file and log inspection related to optimizer & gradients.
1 call · #0036–#0036
cd <path>python3 -c <script> <n> >& <path>tail -n <n>Requested source searches and file and log inspection related to source & workspace.
2 calls · #0037–#0038
cd <path>grep -r -n <val> --include <path> <path>wc -lecho <flag>grep -n <val> <path>tail -n <n>head -n <n>grep -n <val> <path> <path>Requested source searches and file and log inspection related to runtime processes.
1 call · #0039–#0039
cd <path>grep -n <val> <path>head -n <n>Requested file and log inspection related to source & workspace.
1 call · #0040–#0040
cd <path>sed -n <val> <path>Requested code edits related to source & workspace.
1 call · #0041–#0041
Write <path>Requested file and log inspection related to checkpoints & weight state.
1 call · #0042–#0042
cat >> <path> <script>echo <val>Requested file and log inspection and script or workload execution related to checkpoints & weight state.
1 call · #0043–#0043
cat >> <path> <script>python3 -c <script>echo <val>Requested code edits related to source & workspace.
1 call · #0044–#0044
Write <path>Requested workspace file updates and script or workload execution related to benchmark & validation setup.
1 call · #0045–#0045
cd <path>rm -rf <path>timeout <n> <val> <path> > <path> <n> > <path>echo <val>python3 -c <script>Requested runtime inspection, file and log inspection and source searches related to device memory.
1 call · #0046–#0046
pgrep <flag> <args>headecho <flag>npu-smi info <n> > <path>grep -E <val>head -n <n>ls -l -a <val>grep <val>tail -n <n> <path> <n> > <path>Requested workspace file updates, script or workload execution and file and log inspection related to benchmark & validation setup.
4 calls · #0047–#0050
cd <path>rm -rf <path>rm -f <path> <path>nohup <val> -c <path> > <path> <n> >& <path>echo <val><command> <args>cat <path> <n> > <path>python3 -c <script> <n> > <path>tail -n <n> <path>grep -c <val> <path>date -uecho <flag>awk <val> <path>grep <val>echo <path>Requested code edits related to source & workspace.
2 calls · #0051–#0052
Edit <path>Requested workspace file updates and script or workload execution related to benchmark & validation setup.
2 calls · #0053–#0054
cd <path>rm -rf <path> <path> <path>rm -f <path> <path> <path>mkdir -p <path>nohup <val> -c <path> > <path> <n> >& <path>echo <val>date -u<command> <args>cd <val>Requested source searches and file and log inspection related to source & workspace.
1 call · #0055–#0055
cd <path>grep -n <val> <path> <path>headecho <val>sed -n <val> <path> <n> > <path>head -n <n>Requested workspace inspection, file and log inspection and source searches related to benchmark & validation setup.
1 call · #0056–#0056
date -uls <val>headecho <flag>grep -c <val> <path> <n> > <path>cat <path> <n> > <path>Requested file and log inspection related to source & workspace.
1 call · #0057–#0057
date -utail -n <n> <path> <n> > <path>echo <flag>cat <path> <n> > <path>echo <val>Requested file and log inspection and source searches related to benchmark & validation setup.
2 calls · #0058–#0059
<command> <args>date -ucat <path> <n> > <path>echo <val>echo <flag>grep -c <val> <path> <n> > <path>Requested code edits related to source & workspace.
1 call · #0060–#0060
Write <path>Requested file and log inspection, source searches and script or workload execution related to benchmark & validation setup.
4 calls · #0061–#0064
date -ucat <path> <n> > <path>echo <val>echo <flag>grep <val> <path> <n> > <path>sed -E <path>tr <val> <val><command> <args>grep -c <val> <path> <n> > <path>python3 -c <script>Requested code edits related to source & workspace.
2 calls · #0065–#0066
Edit <path>Requested workspace inspection, workspace file updates and environment setup or inspection related to runtime processes.
1 call · #0067–#0067
<command> <args>echo <val>ls <val>mkdir -p <path>cd <path>env <vars> nohup <val> -c <path> > <path> <n> >& <path>date -uRequested workspace inspection, file and log inspection and source searches related to source & workspace.
2 calls · #0068–#0069
date -uls <path> <n> > <path>tail -n <n> <path> <n> > <path>cut <flag>grep -c <val> <path> <n> > <path>head -n <n> <path>echo <val>Requested code edits related to source & workspace.
1 call · #0070–#0070
Edit <path>Requested script or workload execution, file and log inspection and environment setup or inspection related to runtime processes.
1 call · #0071–#0071
<command> <args>python3 -c <script>awk <path> <path> <path> <n> > <path>echo <flag>env <vars>cd <path>rm -f <path>env <vars> nohup <val> -c <path> > <path> <n> >& <path>date -uRequested source searches related to source & workspace.
2 calls · #0072–#0073
<command> <args>date -ugrep -c <val> <path> <n> > <path>grep -c <val> <path>Requested file and log inspection related to source & workspace.
2 calls · #0074–#0075
Read <path>Requested code edits related to source & workspace.
3 calls · #0076–#0078
Edit <path>Requested environment setup or inspection and workspace file updates related to source & workspace.
1 call · #0079–#0079
<command> <args>cd <path>env <vars>rm -f <path>env <vars> nohup <val> -c <path> > <path> <n> >& <path>echo <val>date -uRequested source searches and file and log inspection related to source & workspace.
1 call · #0080–#0080
<command> <args>date -ugrep -c <val> <path> <n> > <path>tail -n <n> <path>cut <flag>Requested source searches related to source & workspace.
1 call · #0081–#0081
<command> <args>date -ugrep -c <val> <path>Requested code edits related to source & workspace.
2 calls · #0082–#0083
Edit <path>Requested source searches and file and log inspection related to source & workspace.
1 call · #0084–#0084
cd <path>grep -n <val> <path>head -n <n>Requested script or workload execution related to attention kernels.
1 call · #0085–#0085
cd <path>python3 -B -c <script>Requested workspace inspection, source searches and file and log inspection related to task requirements.
1 call · #0086–#0086
cd <val>lsecho <flag>grep -n -i <flag> <args>head -n <n>Requested workspace inspection and file and log inspection related to source & workspace.
1 call · #0087–#0087
cd <val>ls <path>echo <flag>head -n <n> <path> <n> > <path>head -n <n>Requested workspace file updates, script or workload execution and execution waits related to benchmark & validation setup.
8 calls · #0088–#0095
cd <val>rm -f <path>nohup <val> -c <path> > <path> <n> >& <path>sleep <n>echo <val>date -u <val><command> <args>echo <path>tail -n <n> <path>tail -n <n> <path> <n> > <path>ls -l -a <flag> <args>tail -n <n>echo <flag>tail -c <n> <val> <n> > <path>cat <val>echotail -n <n> <val>ls <flag> <args>grep <val>tail -c <n> <val>ps <flag> <args>grep -E <val>grep -v <val>headRequested source searches related to source & workspace.
1 call · #0096–#0096
cd <path>grep -n <flag> <args>Requested code edits related to source & workspace.
1 call · #0097–#0097
Edit <path>Requested script or workload execution, workspace inspection and source searches related to benchmark & validation setup.
1 call · #0098–#0098
echo <path>date -u <val>cd <path>python3 -B -c <script>cd <val>ls <flag> <args>grep <val>Requested environment setup or inspection, workspace inspection and file and log inspection related to checkpoints & weight state.
2 calls · #0099–#0100
env <vars>echo <val>find <val> -type <val> <flag> <args>tail -n <n>du <flag> <args>sleep <n>ps <flag> <args>grep <val>grep -v <val>awk <val>echo <path>date -u <val>free -gdf -h <path><command> <args>grep -E <val> <path> <n> > <path>tr <val> <val>echoRequested execution waits, source searches and file and log inspection related to checkpoints & weight state.
1 call · #0101–#0101
<command> <args>sleep <n>echo <path>date -u <val>du <flag> <args>grep <val> <path> <n> > <path>head -n <n>tail -c <n> <path>Requested execution waits, workspace inspection and source searches related to benchmark & validation setup.
5 calls · #0102–#0106
<command> <args>sleep <n>echo <path>date -u <val>cd <val>ls <flag> <args>grep -E <val>echo <val>tail -c <n> <val>echotail -n <n> <val>tail -c <n> <val> <n> > <path>grep -c <val> <val> <n> > <path>cat <val> <n> > <path>tail -n <n> <path>Requested runtime inspection, source searches and file and log inspection related to checkpoints & weight state.
1 call · #0107–#0107
echo <val>ps <flag> <args>grep -E <val>grep -v <val>wc -ldf -h <path>tail -n <n>du <flag> <args>cd <val>rm -f <path>nohup <val> -c <path> > <path> <n> >& <path>sleep <n>date -u <val>Requested execution waits, source searches and file and log inspection related to benchmark & validation setup.
2 calls · #0108–#0109
<command> <args>sleep <n>echo <path>date -u <val>cd <val>grep -c <val> <val> <n> > <path>tail -c <n> <val> <n> > <path>echo <val>cat <path>echocat <val> <n> > <path>Requested source searches, file and log inspection and workspace inspection related to source & workspace.
2 calls · #0110–#0111
cd <val>grep -n <val> <path>head -n <n>echo <val>ls -l -a <flag> <args>sed -n <val> <path>Requested workspace file updates, workspace inspection and script or workload execution related to benchmark & validation setup.
1 call · #0112–#0112
rm -rf <path> <path> <path> <path>ls <val>cd <val>rm -f <path>nohup <val> -c <path> > <path> <n> >& <path>sleep <n>echo <val>date -u <val>Requested execution waits, workspace inspection and source searches related to benchmark & validation setup.
5 calls · #0113–#0117
<command> <args>sleep <n>echo <path>date -u <val>cd <val>ls <flag> <args>grep -E <val>grep -c <val> <val> <n> > <path>tail -c <n> <val> <n> > <path>python3 -c <script>Requested workspace inspection, workspace file updates and script or workload execution related to benchmark & validation setup.
3 calls · #0118–#0120
ls -d <path> <path> <path> <n> > <path>rm -rf <path> <path> <path>cd <val>rm -f <path>nohup <val> -c <path> > <path> <n> >& <path>sleep <n>echo <val>date -u <val><command> <args>echo <path>cat <path> <n> > <path>head -c <n>tail -c <n> <val> <n> > <path>Requested workspace inspection and source searches related to source & workspace.
2 calls · #0121–#0122
ls -d <path> <n> > <path>echo <flag><command> <args>ls <val> <n> > <path>tr <val> <val>echols -l -a <path> <n> > <path>echo <val>date -u <val>cd <path>grep -n <flag> <args>Requested code edits related to source & workspace.
1 call · #0123–#0123
Edit <path>Requested file and log inspection, workspace inspection and source searches related to source & workspace.
2 calls · #0124–#0125
cd <path>sed -n <path> <path>echo <val>cat <path> <n> > <path>head -n <n>find <val> -name <val>headecho <flag>grep -n <val> <path>Requested script or workload execution related to checkpoints & weight state.
1 call · #0126–#0126
cd <path>python3 -B -c <script>Requested code edits related to source & workspace.
2 calls · #0127–#0128
Edit <path>Requested script or workload execution related to checkpoints & weight state.
2 calls · #0129–#0130
cd <path>python3 -B -c <script> <n> >& <path>echo <val>python3 -B -c <script>Requested script or workload execution, workspace file updates and execution waits related to benchmark & validation setup.
1 call · #0131–#0131
cd <path>python3 -B -c <script>rm -rf <path> <path> <path>cd <val>rm -f <path>nohup <val> -c <path> > <path> <n> >& <path>sleep <n>echo <val>date -u <val>Requested execution waits, workspace inspection and source searches related to benchmark & validation setup.
5 calls · #0132–#0136
<command> <args>sleep <n>echo <path>date -u <val>cd <val>ls <flag> <args>grep -E <val>grep -c <val> <val> <n> > <path>tail -c <n> <val> <n> > <path>python3 -c <script>Requested runtime inspection, source searches and file and log inspection related to runtime processes.
1 call · #0137–#0137
echo <val>ps <flag> <args>grep -E <val>grep -v <val>wc -lgit status <flag>cd <path>date -u <val>Requested file and log inspection and source searches related to source & workspace.
2 calls · #0138–#0139
cd <path>wc -l <path> <path>echo <val>grep <flag> <args>sort -ugrep -n -i <val> <path>headRead <path>Requested workspace inspection and file and log inspection related to checkpoints & weight state.
1 call · #0140–#0140
echo <val>ls -l -a <flag> <args>du <flag> <args>df -h <path>tail -n <n>Requested workspace file updates, workspace inspection and source searches related to benchmark & validation setup.
1 call · #0141–#0141
rm -rf <path> <path> <path> <path> <path>ls -l -a <flag> <args>grep -v <val>echo <val>cd <val>timeout <n> <path> <n> >& <path>head -c <n>echodate -u <val>Requested file and log inspection related to source & workspace.
6 calls · #0142–#0147
Read <path>Requested workspace inspection related to benchmark & validation setup.
1 call · #0148–#0148
cd <path>stat -c <val> <path> <path>echo <flag>stat -c <val> <path>Requested repository inspection, workspace inspection and file and log inspection related to dependencies & build setup.
1 call · #0149–#0149
echo <val>git status <flag> <args>cd <path>echo <path>find <path> <path> <path> <val> -name <val> -o -name <val> -o -name <val> <args>head -n <n>Requested environment setup or inspection, workspace inspection and file and log inspection related to device memory.
1 call · #0150–#0150
env <vars>ls -l -a <val> <n> > <path>echo <flag>cat <path> <n> > <path>echo <val>Requested code edits related to device memory.
2 calls · #0151–#0152
Write <path>Requested code edits related to checkpoints & weight state.
1 call · #0153–#0153
Write <path>Requested code edits related to device memory.
1 call · #0154–#0154
Write <path>Requested script or workload execution, repository inspection and runtime inspection related to benchmark & validation setup.
1 call · #0155–#0155
echo <val>cd <path>python3 -B -c <script>git status <flag>ps <flag> <args>grep -E <val>grep -v <val>wc -lcd <val><command> <args>python3 -c <script>Requested workspace inspection, repository inspection and file and log inspection related to source & workspace.
1 call · #0156–#0156
echo <path>pwdgit status <flag>catecho <val>cd <path>Requested workspace file updates, script or workload execution and execution waits related to benchmark & validation setup.
3 calls · #0157–#0159
rm -rf <path> <path> <path>cd <val>rm -f <path>nohup <val> -c <path> > <path> <n> >& <path>sleep <n>echo <val>date -u <val><command> <args>echo <path>tail -c <n> <val> <n> > <path>cat <path> <n> > <path>head -c <n>Requested workspace file updates and script or workload execution related to checkpoints & weight state.
1 call · #0160–#0160
rm -rf <path> <path> <path> <path> <path>cd <val>timeout <n> <path> <n> >& <path>python3 -c <script>echo <val>echo <path>cd <path>date -u <val>Requested script or workload execution related to runtime processes.
2 calls · #0161–#0162
cd <path>python3 -B -c <script>Requested code edits related to source & workspace.
2 calls · #0163–#0164
Edit <path>Requested source searches related to source & workspace.
1 call · #0165–#0165
cd <path>grep -n <flag> <args>Requested code edits related to source & workspace.
2 calls · #0166–#0167
Edit <path>Requested script or workload execution related to source & workspace.
1 call · #0168–#0168
date -u <val>echo <val>cd <path>python3 -B -c <script>Requested code edits related to source & workspace.
1 call · #0169–#0169
Write <path>Requested script or workload execution related to source & workspace.
1 call · #0170–#0170
cd <path>timeout <n> <val> -B <path>echo <val>date -u <val>Requested workspace file updates, script or workload execution and execution waits related to benchmark & validation setup.
1 call · #0171–#0171
rm -rf <path> <path> <path>cd <val>rm -f <path>nohup <val> -c <path> > <path> <n> >& <path>sleep <n>echo <val>date -u <val>Requested execution waits, workspace inspection and source searches related to benchmark & validation setup.
4 calls · #0172–#0175
<command> <args>sleep <n>echo <path>date -u <val>cd <val>ls <flag> <args>grep -E <val>grep -c <val> <val> <n> > <path>Requested script or workload execution related to optimizer & gradients.
1 call · #0176–#0176
cd <val>python3 -c <script>date -u <val>Requested workspace file updates and script or workload execution related to checkpoints & weight state.
1 call · #0177–#0177
rm -rf <path> <path> <path> <path> <path>cd <val>timeout <n> <path> <n> >& <path>python3 -c <script>echo <val>echo <path>echo <flag>cd <path>python3 -B -c <script>date -u <val>Requested file and log inspection and workspace inspection related to source & workspace.
1 call · #0178–#0178
echo <path>echo <flag>wc -l <path> <path>find <path> <path> <path> <val> -name <val> -o -name <val> -o -name <val> <args>wc -ldate -u <val>Requested code edits related to device memory.
3 calls · #0179–#0181
Edit <path>Write <path>Requested workspace file updates and script or workload execution related to checkpoints & weight state.
1 call · #0182–#0182
date -u <val>echo <val>rm -f <path> <path> <path> <path> <path> <path> <path> <n> > <path>echo <path>python3 -B -c <script>cd <val><command> <args>python3 -c <script> <n> > <path>Requested environment setup or inspection, source searches and script or workload execution related to source & workspace.
1 call · #0183–#0183
cd <path>env <vars>echo <val>grep -n <val> <val>python3 -B -c <script>Requested source searches related to runtime processes.
1 call · #0184–#0184
cd <path>grep -n <flag> <args>echo <val>grep -c <val> <path> <path>Requested code edits related to source & workspace.
1 call · #0185–#0185
Edit <path>Requested environment setup or inspection and script or workload execution related to source & workspace.
1 call · #0186–#0186
cd <path>env <vars>python3 -B -c <script>echo <val>date -u <val>Requested workspace file updates, script or workload execution and execution waits related to benchmark & validation setup.
1 call · #0187–#0187
rm -rf <path> <path> <path>cd <val>rm -f <path>nohup <val> -c <path> > <path> <n> >& <path>sleep <n>echo <val>date -u <val>Requested code edits related to source & workspace.
1 call · #0188–#0188
Write <path>Requested script or workload execution related to source & workspace.
1 call · #0189–#0189
cd <path>timeout <n> <val> -B <path>echo <val>date -u <val>Requested execution waits, file and log inspection and workspace file updates related to benchmark & validation setup.
3 calls · #0190–#0192
<command> <args>sleep <n>echo <path>date -u <val>cat <path> <n> > <path>head -c <n>rm -f <path> <path> <n> > <path>rm -rf <path> <path> <path>cd <val>timeout <n> <path> <n> >& <path>python3 -c <script>echo <val>03 / CANDIDATE ARTIFACT
Read code changes as Git diffs. Identifying strings are masked; binary files are listed by their full relative names.
Base commit: 72c49a6260c73669678b8f39b1ba41a4789bb555
@@ -0,0 +1,691 @@+# Copyright (c) 2025, HUAWEI CORPORATION. All rights reserved.+"""Foreground training supervisor for the four-device Qwen3-8B system.++The supervisor owns the child process graph directly instead of delegating to+``torch.distributed.run``. It stays in the foreground, forwards the training+observations of the logging rank to its own stdout, and guarantees that no+worker survives its own shutdown.++Only the standard library is imported at module scope so that starting the+supervisor never pays for the accelerator framework import.+"""++from __future__ import annotations++import argparse+import errno+import json+import os+import signal+import subprocess+import sys+import time+from pathlib import Path+from typing import Any+++WORKER_MODULE = "mindspeed_llm.training.qwen3_8b_4dev_worker"+REPOSITORY_ROOT = Path(__file__).resolve().parents[2]+STOP_TIMEOUT_S = 30.0+++def _knob(name: str, default: str) -> str:+ value = os.environ.get(name)+ if value is None or value == "":+ return default+ return value+++def _int_knob(name: str, default: int) -> int:+ return int(_knob(name, str(default)))+++def _flag_knob(name: str, default: bool) -> bool:+ return _knob(name, "1" if default else "0") not in ("0", "false", "False")+++def parse_args(argv: list[str] | None = None) -> argparse.Namespace:+ parser = argparse.ArgumentParser(+ prog="qwen3_8b_4dev",+ description="four-device Qwen3-8B training supervisor",+ )+ parser.add_argument("--run-spec", required=True)+ parser.add_argument("--device-ids", required=True)+ parser.add_argument("--master-addr", default="127.0.0.1")+ parser.add_argument("--master-port", required=True, type=int)+ parser.add_argument("--runtime-dir", required=True)+ parser.add_argument("--output-dir", required=True)+ parser.add_argument("--checkpoint-dir", default=None)+ parser.add_argument("--save-at", default=None, type=int)+ parser.add_argument("--resume", action="store_true")+ return parser.parse_args(argv)+++def load_run_spec(path: str) -> dict[str, Any]:+ value = json.loads(Path(path).read_text(encoding="utf-8"))+ if not isinstance(value, dict):+ raise ValueError("run specification must be a JSON object")+ for key in ("seed", "model", "optimizer", "work"):+ if key not in value:+ raise ValueError(f"run specification is missing {key}")+ return value+++def _devices(raw: str) -> list[int]:+ values = [int(item) for item in raw.split(",") if item != ""]+ if not values:+ raise ValueError("--device-ids must name at least one device")+ if len(values) != len(set(values)):+ raise ValueError("--device-ids contains duplicates")+ return values+++def _choose_pipeline(+ *,+ world_size: int,+ global_batch: int,+ micro_batch: int,+ tensor_parallel: int,+ context_parallel: int,+) -> int:+ """Pick a pipeline depth that fits the devices and the committed batch.++ Two stages is the measured best layout on four devices, so it is tried+ first, but it is only usable when the device count divides that way and the+ remaining data-parallel width still divides the global batch. The device+ count is supplied by the caller and is not guaranteed to be four, so the+ remaining divisors are tried in turn rather than assuming one.+ """+ candidates = [2, 1] + [+ size for size in range(3, world_size + 1) if size not in (1, 2)+ ]+ for pipeline_parallel in candidates:+ model_parallel = tensor_parallel * pipeline_parallel * context_parallel+ if model_parallel <= 0 or world_size % model_parallel != 0:+ continue+ data_parallel = world_size // model_parallel+ if global_batch % (micro_batch * data_parallel) != 0:+ continue+ return pipeline_parallel+ return 1+++def _layer_parameter_count(model: dict[str, Any]) -> int:+ """Parameters in one transformer layer of the public model."""+ hidden = int(model["model_width"])+ ffn = int(model["ffn_width"])+ kv_channels = int(model["kv_channels"])+ query_width = int(model["num_attention_heads"]) * kv_channels+ key_value_width = 2 * int(model["num_query_groups"]) * kv_channels+ attention = hidden * (query_width + key_value_width) + query_width * hidden+ mlp = 3 * hidden * ffn+ return attention + mlp+++def balanced_layer_list(model: dict[str, Any], pipeline_parallel: int) -> str:+ """Distribute the layers so every pipeline stage carries equal work.++ An even split is not a balanced split. The last stage also owns the output+ projection over the vocabulary, which is a dense matrix multiply worth+ several transformer layers, so an even split leaves the last stage on the+ critical path and every other stage waiting for it. The layers are handed+ out in proportion to the work each stage carries, expressed in units of one+ transformer layer, using largest-remainder rounding so the counts still sum+ to the public layer count.+ """+ num_layers = int(model["num_layers"])+ if pipeline_parallel <= 1 or num_layers < pipeline_parallel:+ return ""++ layer_cost = _layer_parameter_count(model)+ output_cost = int(model["vocab_size"]) * int(model["model_width"])+ # Work carried by each stage in addition to its transformer layers.+ extra = [0.0] * pipeline_parallel+ extra[-1] = output_cost / layer_cost++ per_stage = (num_layers + sum(extra)) / pipeline_parallel+ ideal = [per_stage - value for value in extra]+ counts = [max(1, int(value)) for value in ideal]++ remainder = num_layers - sum(counts)+ order = sorted(+ range(pipeline_parallel),+ key=lambda index: ideal[index] - int(ideal[index]),+ reverse=True,+ )+ position = 0+ while remainder > 0:+ counts[order[position % pipeline_parallel]] += 1+ remainder -= 1+ position += 1+ while remainder < 0:+ candidate = order[position % pipeline_parallel]+ if counts[candidate] > 1:+ counts[candidate] -= 1+ remainder += 1+ position += 1++ if sum(counts) != num_layers:+ return ""+ return ",".join(str(value) for value in counts)+++def build_worker_argv(+ spec: dict[str, Any],+ *,+ world_size: int,+ checkpoint: str | None,+ save_at: int | None,+ resume: bool,+) -> list[str]:+ """Translate the public run specification into worker arguments.++ The public work -- model, optimizer, samples, tokens and optimizer updates+ -- comes straight from the run specification. Only the execution strategy+ (parallel layout, microbatching, scheduling, overlap) is chosen here.+ """+ model = spec["model"]+ optimizer = spec["optimizer"]+ work = spec["work"]+ train_iters = int(work["optimizer_updates"])+ global_batch = int(work["global_batch_size"])++ tensor_parallel = _int_knob("Q3_TP", 1)+ context_parallel = _int_knob("Q3_CP", 1)+ micro_batch = _int_knob("Q3_MBS", 1)+ # The model does not fit on one device, so it is split across the pipeline.+ pipeline_parallel = _int_knob(+ "Q3_PP",+ _choose_pipeline(+ world_size=world_size,+ global_batch=global_batch,+ micro_batch=micro_batch,+ tensor_parallel=tensor_parallel,+ context_parallel=context_parallel,+ ),+ )++ model_parallel = tensor_parallel * pipeline_parallel * context_parallel+ if world_size % model_parallel != 0:+ raise ValueError("parallel layout does not divide the world size")+ data_parallel = world_size // model_parallel+ if global_batch % (micro_batch * data_parallel) != 0:+ raise ValueError("microbatching does not divide the global batch")++ argv = [+ "--use-mcore-models",+ "--spec",+ "mindspeed_llm.tasks.models.spec.qwen3_spec",+ "layer_spec",+ "--transformer-impl",+ "local",+ "--distributed-backend",+ "nccl",+ "--tensor-model-parallel-size",+ str(tensor_parallel),+ "--pipeline-model-parallel-size",+ str(pipeline_parallel),+ "--context-parallel-size",+ str(context_parallel),+ "--num-layers",+ str(model["num_layers"]),+ "--hidden-size",+ str(model["model_width"]),+ "--ffn-hidden-size",+ str(model["ffn_width"]),+ "--num-attention-heads",+ str(model["num_attention_heads"]),+ "--group-query-attention",+ "--num-query-groups",+ str(model["num_query_groups"]),+ "--kv-channels",+ str(model["kv_channels"]),+ "--qk-layernorm",+ "--seq-length",+ str(work["sequence_length"]),+ "--max-position-embeddings",+ str(work["sequence_length"]),+ "--micro-batch-size",+ str(micro_batch),+ "--global-batch-size",+ str(global_batch),+ "--train-iters",+ str(train_iters),+ "--lr",+ str(optimizer["learning_rate"]),+ "--min-lr",+ str(optimizer["minimum_learning_rate"]),+ "--lr-decay-style",+ str(optimizer["learning_rate_decay_style"]),+ "--weight-decay",+ str(optimizer["weight_decay"]),+ "--adam-beta1",+ str(optimizer["adam_beta1"]),+ "--adam-beta2",+ str(optimizer["adam_beta2"]),+ "--clip-grad",+ str(optimizer["clip_grad"]),+ "--attention-dropout",+ "0.0",+ "--hidden-dropout",+ "0.0",+ "--seed",+ str(spec["seed"]),+ "--bf16",+ "--mock-data",+ "--tokenizer-type",+ "NullTokenizer",+ "--vocab-size",+ str(model["vocab_size"]),+ "--make-vocab-size-divisible-by",+ "1",+ "--position-embedding-type",+ "rope",+ "--use-rotary-position-embeddings",+ "--rotary-base",+ str(model["rotary_base"]),+ "--disable-bias-linear",+ "--normalization",+ "RMSNorm",+ "--norm-epsilon",+ "1e-6",+ "--swiglu",+ "--attention-softmax-in-fp32",+ "--use-flash-attn",+ "--use-fused-rotary-pos-emb",+ "--use-fused-swiglu",+ "--use-fused-rmsnorm",+ "--no-masked-softmax-fusion",+ "--no-gradient-accumulation-fusion",+ "--use-distributed-optimizer",+ "--reuse-fp32-param",+ "--overlap-grad-reduce",+ "--overlap-param-gather",+ "--use-ascend-coc",+ "--log-interval",+ str(work["log_interval"]),+ "--eval-iters",+ "0",+ "--eval-interval",+ str(train_iters),+ ]++ virtual_stage = _int_knob("Q3_VPP_LAYERS", 0)++ layer_list = _knob("Q3_NUM_LAYER_LIST", "")+ if not layer_list and pipeline_parallel > 1 and virtual_stage <= 0:+ layer_list = balanced_layer_list(model, pipeline_parallel)+ if layer_list and pipeline_parallel > 1 and virtual_stage <= 0:+ argv.extend(("--num-layer-list", layer_list))++ if virtual_stage > 0 and pipeline_parallel > 1:+ argv.extend(("--num-layers-per-virtual-pipeline-stage", str(virtual_stage)))++ if _flag_knob("Q3_OVERLAP_P2P", False) and pipeline_parallel > 1:+ argv.append("--overlap-p2p-comm")++ recompute_granularity = _knob("Q3_RECOMPUTE_GRANULARITY", "")+ if recompute_granularity:+ argv.extend(("--recompute-granularity", recompute_granularity))+ recompute_method = _knob("Q3_RECOMPUTE_METHOD", "")+ if recompute_method:+ argv.extend(("--recompute-method", recompute_method))+ recompute_layers = _knob("Q3_RECOMPUTE_LAYERS", "")+ if recompute_layers:+ argv.extend(("--recompute-num-layers", recompute_layers))++ if _flag_knob("Q3_RECOMPUTE_ACTIVATION", False):+ argv.append("--recompute-activation-function")+ if _flag_knob("Q3_RECOMPUTE_NORM", False):+ argv.append("--recompute-norm")++ extra = _knob("Q3_EXTRA_ARGS", "")+ if extra:+ argv.extend(extra.split())++ if checkpoint is not None and resume:+ argv.extend(("--load", checkpoint))+ elif checkpoint is not None and save_at is not None:+ argv.extend(+ (+ "--save",+ checkpoint,+ "--save-interval",+ str(save_at),+ "--exit-interval",+ str(save_at),+ )+ )+ return argv+++def _await_port_release(port: int, timeout_s: float = 3.0) -> bool:+ """Confirm the task-owned service port is bindable again after shutdown.++ The workers release the rendezvous port without leaving TIME_WAIT state, so+ this normally returns on the first probe. It exists so the supervisor never+ reports a clean exit while the port it was given is still held.+ """+ import socket++ deadline = time.monotonic() + timeout_s+ while True:+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:+ try:+ probe.bind(("127.0.0.1", port))+ return True+ except OSError:+ pass+ if time.monotonic() >= deadline:+ return False+ time.sleep(0.02)+++def _process_table() -> dict[int, tuple[int, str]]:+ """Map each visible process to its parent and its start time.++ The start time is carried along because a pid alone does not identify a+ process over time: the pid can be recycled onto something unrelated between+ reading it and acting on it.+ """+ table: dict[int, tuple[int, str]] = {}+ for name in os.listdir("/proc"):+ if not name.isdigit():+ continue+ try:+ with open("/proc/" + name + "/stat", "rb") as handle:+ raw = handle.read().decode("utf-8", "replace")+ except OSError:+ continue+ # The command name is parenthesised and may itself contain spaces or+ # parentheses, so the fixed fields start after its final bracket.+ cut = raw.rfind(")")+ if cut < 0:+ continue+ fields = raw[cut + 2 :].split()+ if len(fields) < 20:+ continue+ try:+ table[int(name)] = (int(fields[1]), fields[19])+ except ValueError:+ continue+ return table+++def _descendants(roots: list[int]) -> list[tuple[int, str]]:+ """Every process below the given ones, with each start time for identity."""+ table = _process_table()+ offspring: dict[int, list[int]] = {}+ for pid, (parent, _) in table.items():+ offspring.setdefault(parent, []).append(pid)++ found: list[tuple[int, str]] = []+ seen = set(roots)+ stack = list(roots)+ while stack:+ for child in offspring.get(stack.pop(), ()):+ if child in seen:+ continue+ seen.add(child)+ found.append((child, table[child][1]))+ stack.append(child)+ return found+++def _still_running(pid: int, started: str) -> bool:+ """Report whether the pid is the same process that was recorded earlier."""+ try:+ with open("/proc/%d/stat" % pid, "rb") as handle:+ raw = handle.read().decode("utf-8", "replace")+ except OSError:+ return False+ cut = raw.rfind(")")+ if cut < 0:+ return False+ fields = raw[cut + 2 :].split()+ return len(fields) >= 20 and fields[19] == started+++def _signal_pid(pid: int, started: str, number: int) -> bool:+ """Signal a recorded process, refusing to touch a recycled pid."""+ if not _still_running(pid, started):+ return False+ try:+ os.kill(pid, number)+ except OSError as exc:+ return exc.errno != errno.ESRCH+ return True+++def _terminate(children: list[subprocess.Popen], timeout_s: float = STOP_TIMEOUT_S) -> None:+ """Terminate every surviving worker and everything it forked.++ A worker may have forked helpers of its own -- data loading workers, for+ one. Those helpers do not go away just because the worker did: they notice+ an exited parent only when they next poll for it, which can be seconds+ later, and until then they are processes this launcher left behind.++ They are recorded before anything is signalled, while the workers are still+ alive and the helpers are still reachable through them; once a worker exits+ its children are reparented away and that link is gone. On the ordinary+ path the workers have already finished and taken their helpers with them, so+ nothing is found and nothing is signalled.+ """+ try:+ helpers = _descendants([child.pid for child in children])+ except OSError:+ helpers = []++ alive = [child for child in children if child.poll() is None]+ for child in alive:+ try:+ child.send_signal(signal.SIGTERM)+ except (ProcessLookupError, OSError):+ pass+ deadline = time.monotonic() + timeout_s+ while time.monotonic() < deadline:+ if all(child.poll() is not None for child in children):+ break+ time.sleep(0.05)+ for child in children:+ if child.poll() is None:+ try:+ child.kill()+ except (ProcessLookupError, OSError):+ pass+ for child in children:+ try:+ child.wait(timeout=5.0)+ except subprocess.TimeoutExpired:+ pass++ # The workers are reaped, so anything still answering here is a helper that+ # outlived the worker that forked it.+ residual = [+ (pid, started)+ for pid, started in helpers+ if _signal_pid(pid, started, signal.SIGTERM)+ ]+ if not residual:+ return+ grace = time.monotonic() + 1.0+ while time.monotonic() < grace:+ residual = [+ (pid, started) for pid, started in residual if _still_running(pid, started)+ ]+ if not residual:+ return+ time.sleep(0.02)+ for pid, started in residual:+ _signal_pid(pid, started, signal.SIGKILL)+++def _worker_environment(+ *,+ rank: int,+ local_rank: int,+ world_size: int,+ master_addr: str,+ master_port: int,+ runtime_dir: Path,+) -> dict[str, str]:+ env = dict(os.environ)+ env.update(+ {+ "RANK": str(rank),+ "LOCAL_RANK": str(local_rank),+ "WORLD_SIZE": str(world_size),+ "LOCAL_WORLD_SIZE": str(world_size),+ "GROUP_RANK": "0",+ "MASTER_ADDR": master_addr,+ "MASTER_PORT": str(master_port),+ "TORCHELASTIC_RUN_ID": "qwen3-8b-4dev",+ "PYTHONUNBUFFERED": "1",+ }+ )+ source_path = str(REPOSITORY_ROOT)+ existing = env.get("PYTHONPATH", "")+ if source_path not in existing.split(os.pathsep):+ env["PYTHONPATH"] = (+ source_path + os.pathsep + existing if existing else source_path+ )+ env.setdefault("HOME", str(runtime_dir))+ return env+++def run(args: argparse.Namespace) -> int:+ spec = load_run_spec(args.run_spec)+ devices = _devices(args.device_ids)+ world_size = len(devices)+ runtime_dir = Path(args.runtime_dir)+ runtime_dir.mkdir(parents=True, exist_ok=True)+ output_dir = Path(args.output_dir)++ worker_argv = build_worker_argv(+ spec,+ world_size=world_size,+ checkpoint=args.checkpoint_dir,+ save_at=args.save_at,+ resume=args.resume,+ )++ # Only the pipeline tail rank prints the training observations, so its+ # stdout is the supervisor's stdout. Every other rank writes to its own+ # log file to keep the observation stream clean and ordered.+ log_rank = _int_knob("Q3_LOG_RANK", world_size - 1)+ worker_log_dir = runtime_dir / "worker-logs"+ worker_log_dir.mkdir(parents=True, exist_ok=True)++ fast_exit = _flag_knob("Q3_FAST_EXIT", True)++ children: list[subprocess.Popen] = []+ handles: list[Any] = []+ previous_handlers: dict[int, Any] = {}++ def _forward(signum: int, _frame: Any) -> None:+ _terminate(children)+ raise SystemExit(128 + signum)++ for signum in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP):+ try:+ previous_handlers[signum] = signal.signal(signum, _forward)+ except (OSError, ValueError):+ pass++ returncode = 0+ try:+ for rank, device in enumerate(devices):+ env = _worker_environment(+ rank=rank,+ local_rank=rank,+ world_size=world_size,+ master_addr=args.master_addr,+ master_port=args.master_port,+ runtime_dir=runtime_dir,+ )+ env["Q3_FAST_EXIT"] = "1" if fast_exit else "0"+ env["Q3_WORKER_RANK"] = str(rank)+ env["Q3_DEVICE_ID"] = str(device)+ if rank == log_rank:+ stdout: Any = None+ else:+ handle = (worker_log_dir / f"rank-{rank}.stdout.log").open("wb")+ handles.append(handle)+ stdout = handle+ children.append(+ subprocess.Popen(+ [sys.executable, "-B", "-m", WORKER_MODULE, *worker_argv],+ cwd=str(REPOSITORY_ROOT),+ env=env,+ stdin=subprocess.DEVNULL,+ stdout=stdout,+ stderr=None,+ )+ )++ # Wait for every worker. A single worker failure tears the whole+ # process graph down so nothing is left behind.+ pending = list(children)+ while pending:+ for child in list(pending):+ try:+ status = child.wait(timeout=0.2)+ except subprocess.TimeoutExpired:+ continue+ pending.remove(child)+ if status != 0:+ returncode = status if status > 0 else 128 - status+ _terminate(children)+ pending = []+ break+ except SystemExit:+ raise+ except BaseException:+ _terminate(children)+ raise+ finally:+ for signum, handler in previous_handlers.items():+ try:+ signal.signal(signum, handler)+ except (OSError, ValueError):+ pass+ _terminate(children, timeout_s=5.0)+ _await_port_release(args.master_port)+ for handle in handles:+ try:+ handle.close()+ except OSError:+ pass+ try:+ sys.stdout.flush()+ except (OSError, ValueError):+ pass+ if output_dir.is_dir():+ try:+ (output_dir / "framework-launch.json").write_text(+ json.dumps(+ {+ "schema_version": 1,+ "kind": "qwen3_8b_4dev_framework_launch",+ "world_size": world_size,+ "devices": devices,+ "worker_argv": worker_argv,+ "log_rank": log_rank,+ "fast_exit": fast_exit,+ },+ indent=2,+ )+ + "\n",+ encoding="utf-8",+ )+ except OSError:+ pass+ return returncode+++def main(argv: list[str] | None = None) -> int:+ return run(parse_args(argv))+++if __name__ == "__main__":+ raise SystemExit(main())@@ -0,0 +1,136 @@+# Copyright (c) 2025, HUAWEI CORPORATION. All rights reserved.+"""Training worker for the four-device Qwen3-8B supervisor.++The worker runs the ordinary GPT pretraining program. Once the training+program has finished all of its committed work -- including any checkpoint+save, which is blocking and already followed by a collective barrier -- the+worker releases its process image directly instead of unwinding the+accelerator runtime. Every rank reaches that point only after the barrier at+the end of training, so no rank can abandon a peer inside a collective.+"""++from __future__ import annotations++import os+import sys+import time+++def _fast_exit_enabled() -> bool:+ return os.environ.get("Q3_FAST_EXIT", "1") not in ("0", "false", "False")+++def _rendezvous_socket_inodes(port: int) -> set[str]:+ """Inodes of every local TCP socket that uses ``port`` on either end."""+ needle = f"{port:04X}"+ inodes: set[str] = set()+ for name in ("/proc/net/tcp", "/proc/net/tcp6"):+ try:+ with open(name, "r", encoding="ascii", errors="replace") as handle:+ next(handle, None)+ for line in handle:+ fields = line.split()+ if len(fields) < 10:+ continue+ if (+ fields[1].rsplit(":", 1)[-1] == needle+ or fields[2].rsplit(":", 1)[-1] == needle+ ):+ inodes.add(fields[9])+ except (OSError, StopIteration):+ continue+ return inodes+++def _reset_rendezvous_sockets() -> None:+ """Release the rendezvous port without leaving it in TIME_WAIT.++ Rank 0 hosts the rendezvous store on the task-owned service port and is+ also a client of its own store, so at shutdown it holds sockets whose local+ endpoint is that port. Closing them the ordinary way puts the service port+ into TIME_WAIT and the port stays unbindable for the kernel's linger+ interval, which breaks the resource contract. The rendezvous is no longer+ needed once training has finished -- every rank has already passed the+ final collective barrier -- so these sockets are closed with a zero linger+ interval. That sends a reset instead of a graceful shutdown and leaves no+ TIME_WAIT state behind, making the service port immediately reusable.+ """+ raw = os.environ.get("MASTER_PORT", "")+ if not raw.isdigit():+ return+ import socket+ import struct++ inodes = _rendezvous_socket_inodes(int(raw))+ if not inodes:+ return+ zero_linger = struct.pack("ii", 1, 0)+ try:+ descriptors = os.listdir("/proc/self/fd")+ except OSError:+ return+ for entry in descriptors:+ try:+ target = os.readlink(f"/proc/self/fd/{entry}")+ except OSError:+ continue+ if not target.startswith("socket:["):+ continue+ if target[8:-1] not in inodes:+ continue+ try:+ handle = socket.socket(fileno=int(entry))+ except (OSError, ValueError):+ continue+ try:+ handle.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, zero_linger)+ except OSError:+ pass+ finally:+ # Detach so the wrapper does not close a descriptor that the+ # process image still owns; the close happens at process exit.+ handle.detach()+++def _release(code: int) -> None:+ """Flush the observation streams and release the process image."""+ for stream in (sys.stdout, sys.stderr):+ try:+ stream.flush()+ except (OSError, ValueError):+ pass+ try:+ os.fsync(sys.stdout.fileno())+ except (OSError, ValueError, AttributeError):+ pass+ try:+ _reset_rendezvous_sockets()+ except Exception:+ pass+ os._exit(code)+++def main() -> int:+ # Imported here so that the module import graph of the supervisor stays+ # free of the accelerator framework.+ import pretrain_gpt++ code = 0+ try:+ pretrain_gpt.main()+ except SystemExit as exc:+ raw = exc.code+ if raw is None:+ code = 0+ elif isinstance(raw, int):+ code = raw+ else:+ print(raw, file=sys.stderr)+ code = 1+ if _fast_exit_enabled():+ _release(code)+ return code+++if __name__ == "__main__":+ raise SystemExit(main())