rsm_rise code snapshot (HF_PUSH_ALL) (part 9)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- rsm_rise/scripts/real/patchexport_checkenv_capdiff.shAdded+102
- rsm_rise/scripts/real/patchexport_cibaseline_verify.shAdded+221
- rsm_rise/scripts/real/patchexport_clean_checks.pyAdded+171
- rsm_rise/scripts/real/patchexport_clean_inference_env.shAdded+91
- rsm_rise/scripts/real/patchexport_deploy_checks.shAdded+50
- rsm_rise/scripts/real/patchexport_deploy_nosplit.pyAdded+41
- rsm_rise/scripts/real/patchexport_deployment_yml_union.pyAdded+170
- rsm_rise/scripts/real/patchexport_dotted_selector.shAdded+139
- rsm_rise/scripts/real/patchexport_dp_pin.pyAdded+198
- rsm_rise/scripts/real/patchexport_dp_pin_push.shAdded+220
- rsm_rise/scripts/real/patchexport_dp_pin_readers.pyAdded+58
- rsm_rise/scripts/real/patchexport_envc_probe.shAdded+55
- rsm_rise/scripts/real/patchexport_genq_sparse.shAdded+98
- rsm_rise/scripts/real/patchexport_guard_controls_merged.shAdded+128
- rsm_rise/scripts/real/patchexport_import_winner.pyAdded+73
- rsm_rise/scripts/real/patchexport_item1.shAdded+253
- rsm_rise/scripts/real/patchexport_item2_checks.pyAdded+135
- rsm_rise/scripts/real/patchexport_item2_export.shAdded+165
- rsm_rise/scripts/real/patchexport_item2_probe.pyAdded+175
- rsm_rise/scripts/real/patchexport_item2_probe.shAdded+43
- rsm_rise/scripts/real/patchexport_item2_validate.shAdded+96
- rsm_rise/scripts/real/patchexport_item3_apply_fix.pyAdded+91
- rsm_rise/scripts/real/patchexport_item3_checks.pyAdded+157
- rsm_rise/scripts/real/patchexport_item3_genq_pack.pyAdded+75
- rsm_rise/scripts/real/patchexport_item3_probe.pyAdded+90
- rsm_rise/scripts/real/patchexport_item3_probe.shAdded+94
- rsm_rise/scripts/real/patchexport_item3_provenance.shAdded+37
- rsm_rise/scripts/real/patchexport_item3_repatch.shAdded+81
- rsm_rise/scripts/real/patchexport_item3_validate.shAdded+124
- rsm_rise/scripts/real/patchexport_item4_mimicgen.shAdded+145
- rsm_rise/scripts/real/patchexport_livemark.patchAdded+117
- rsm_rise/scripts/real/patchexport_livemark.pyAdded+132
- rsm_rise/scripts/real/patchexport_livemark.shAdded+230
- rsm_rise/scripts/real/patchexport_livemark_ci.shAdded+74
- rsm_rise/scripts/real/patchexport_merge_gate.shAdded+141
- rsm_rise/scripts/real/patchexport_merge_order_probe.shAdded+125
- rsm_rise/scripts/real/patchexport_merged_tests.shAdded+181
- rsm_rise/scripts/real/patchexport_merged_tests_detail.shAdded+176
- rsm_rise/scripts/real/patchexport_models_conflict_probe.shAdded+82
- rsm_rise/scripts/real/patchexport_models_union.pyAdded+186
- rsm_rise/scripts/real/patchexport_openpi_numbers.pyAdded+92
- rsm_rise/scripts/real/patchexport_openpi_readme_fix.pyAdded+87
- rsm_rise/scripts/real/patchexport_openpi_readme_push.shAdded+134
- rsm_rise/scripts/real/patchexport_order_cost.shAdded+159
- rsm_rise/scripts/real/patchexport_owner_handoff.shAdded+190
- rsm_rise/scripts/real/patchexport_pi05_infer.pyAdded+120
- rsm_rise/scripts/real/patchexport_pins_doc_fix_push.shAdded+147
- rsm_rise/scripts/real/patchexport_pipprobe.shAdded+6
- rsm_rise/scripts/real/patchexport_quickstart_weight.shAdded+110
- rsm_rise/scripts/real/patchexport_readme_decide.shAdded+76
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102#!/usr/bin/env bash# rsm_real#5 -- the add/add resolution for scripts/check_env.py, measured as CAPABILITIES, not lines.## Run 21 established that the 4 "hand-merge" files are two independently written versions, and that# every gate I have run resolves them by taking the #6-#10 side whole. A line diff cannot say whether# that loses anything that MATTERS: ours generalised the patch-completeness check to every repo, so a# line present only on #11's side may be the same check in different words. The unit that matters is# the capability the report prints. So RUN both implementations on the same tree and diff the report.## check_env.py is by design a report that always exits 0, so both sides run anywhere; the MISSING lines# are as informative as the PASS lines because the question is which capabilities are NAMED at all.set -uo pipefailsource /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_resolve.shSCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run38}PRS=${PRS:-"6 7 8 9 10"}SC_PR=${SC_PR:-11}export GIT_TERMINAL_PROMPT=0scrub(){ sed 's#https://[^@]*@#https://<redacted>@#g'; }hdr(){ echo; echo "=================== $* ==================="; }mkdir -p "${SCRATCH:?}" || exit 1M=$SCRATCH/capdiff
hdr "0 context"echo "host=$(hostname) job=${LSB_JOBID:-none} scratch=$SCRATCH python=$(python3 -V 2>&1)"
hdr "1 order-A merge, then the PUBLISHED resolution (take the #6-#10 side of the 4 add/add files)"TOK=$(grep -m1 'https://richardrl:' ~/.git-credentials | sed -E 's|https://richardrl:([^@]*)@.*|\1|')[ -n "$TOK" ] || { echo "NO TOKEN"; exit 1; }rm -rf "${M:?}"; git init --quiet "$M" || exit 1printf '[remote "origin"]\n\turl = https://richardrl:%s@github.com/jmarangola/rsm_real.git\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n' "$TOK" >> "$M/.git/config"unset TOKgit -C "$M" fetch --quiet origin main 2>&1 | scrubgit -C "$M" checkout --quiet -b main FETCH_HEAD 2>&1 | scrub[ -f "$M/README.md" ] || { echo "CLONE FAILED"; exit 1; }git -C "$M" config user.email noreply@anthropic.com; git -C "$M" config user.name "capdiff gate"for n in $PRS $SC_PR; do git -C "$M" fetch --quiet origin "pull/$n/head:pr-$n" 2>&1 | scrub || exit 1; doneSC_SHA=$(git -C "$M" rev-parse "pr-$SC_PR")LIVE=$(git -C "$M" ls-remote origin "refs/pull/$SC_PR/head" 2>/dev/null | awk '{print $1}')[ -n "$LIVE" ] && [ "$LIVE" = "$SC_SHA" ] || { echo "STALENESS GUARD FAILED: sc=$(echo "$SC_SHA"|cut -c1-7) live=$(echo "${LIVE:-none}"|cut -c1-7)"; exit 2; }echo "staleness guard: OK -- sc == live head of PR #$SC_PR ($(echo "$LIVE"|cut -c1-7))"for n in $PRS; do git -C "$M" merge --no-ff -m "Merge PR #$n" "pr-$n" >/dev/null 2>&1 || { echo "#$n UNEXPECTED CONFLICT"; exit 2; }; doneFIVE=$(git -C "$M" rev-parse HEAD)git -C "$M" merge --no-ff -m "Merge PR #$SC_PR" "pr-$SC_PR" >/dev/null 2>&1# keep BOTH sides of check_env.py before resolving, so each can be executed against the same treegit -C "$M" show ":2:scripts/check_env.py" > "$SCRATCH/ours.py" || exit 2git -C "$M" show ":3:scripts/check_env.py" > "$SCRATCH/theirs.py" || exit 2pe_resolve "$M" "$FIVE" scripts/setup_env.sh SETUP.md rise_stack/openpi/README.md scripts/check_env.py[ -z "$(git -C "$M" diff --name-only --diff-filter=U)" ] || { echo "RESOLUTION INCOMPLETE"; exit 2; }git -C "$M" commit --quiet -m "scratch: order-A merge + take-ours resolution" || trueecho "resolved tree = $(git -C "$M" rev-parse --short HEAD^{tree})"echo "shipped scripts/check_env.py == ours side: $(cmp -s "$M/scripts/check_env.py" "$SCRATCH/ours.py" && echo YES || echo NO)"
hdr "2 run BOTH implementations on the SAME resolved tree"cp "$SCRATCH/ours.py" "$M/scripts/_ce_ours.py"cp "$SCRATCH/theirs.py" "$M/scripts/_ce_theirs.py"for s in ours theirs; do echo "--- $s: python3 scripts/_ce_$s.py ---" ( cd "$M" && python3 "scripts/_ce_$s.py" > "$SCRATCH/report_$s.txt" 2> "$SCRATCH/report_$s.err" ) rc=$? echo " rc=$rc stdout=$(wc -l < "$SCRATCH/report_$s.txt") lines stderr=$(wc -l < "$SCRATCH/report_$s.err") lines" if [ "$rc" -ne 0 ]; then echo " !! did not exit 0 -- check_env.py is documented to always exit 0"; sed -n '1,20p' "$SCRATCH/report_$s.err" | sed 's/^/ /'; fidone
hdr "3 the reports, verbatim"for s in ours theirs; do echo; echo "----- $s -----"; cat "$SCRATCH/report_$s.txt"; done
hdr "4 CAPABILITY-NAME diff -- what the published resolution stops REPORTING"python3 - "$SCRATCH/report_ours.txt" "$SCRATCH/report_theirs.txt" <<'PY'import re, sysdef caps(p): out=[] for l in open(p,encoding='utf-8',errors='replace'): m=re.match(r"^ (PASS|MISSING|n/a|INFO|)\s{2,}(\S.*?)\s{2,}", l) if m and m.group(2).strip(): out.append((m.group(1).strip() or '-', m.group(2).strip())) return outo,t=caps(sys.argv[1]),caps(sys.argv[2])def norm(n): return re.sub(r"\s+"," ",n.lstrip('^ ').strip()).lower()no={norm(n) for _,n in o}; nt={norm(n) for _,n in t}print(f"capability lines: ours={len(o)} theirs={len(t)}")print(f"\nREPORTED ONLY BY #11's SIDE -- lost when the resolution takes ours ({len(nt-no)}):")for st,n in t: if norm(n) in nt-no: print(f" [{st}] {n}")print(f"\nREPORTED ONLY BY THE #6-#10 SIDE -- gained ({len(no-nt)}):")for st,n in o: if norm(n) in no-nt: print(f" [{st}] {n}")print(f"\nin both ({len(no&nt)}): {sorted(no&nt)}")print("\nVERDICT:", "take-ours loses NO named capability" if not (nt-no) else f"take-ours stops reporting {len(nt-no)} capability name(s) listed above")PY
hdr "5 structural diff of the two docs (headings, not lines)"for f in SETUP.md rise_stack/openpi/README.md; do s=$(echo "$f" | tr '/' '_') git -C "$M" show ":2:$f" > "$SCRATCH/$s.ours" 2>/dev/null || git -C "$M" show "$FIVE:$f" > "$SCRATCH/$s.ours" git -C "$M" show "$SC_SHA:$f" > "$SCRATCH/$s.theirs" echo; echo "--- $f headings ---" echo " ours:"; grep -nE '^#+ ' "$SCRATCH/$s.ours" | sed 's/^/ /' echo " theirs:"; grep -nE '^#+ ' "$SCRATCH/$s.theirs" | sed 's/^/ /'done
hdr "OVERALL rc=0"exit 0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221#!/usr/bin/env bash# rsm_real#5 run 30 -- (a) prove the CI-baseline differ extraction is BEHAVIOUR-PRESERVING, and# (b) re-measure the six-way merged tree now that #11's head moved to fdfa758f, which VENDORS four# rsm_libero modules under rise_stack/rsm/ -- the directory #8 deletes and pe_trial_merge asserts# gone. If #11's two new rsm_libero tests are in the merged workflow but their subject is deleted# by #8, the merged tree fails tests neither side fails alone. That is a cross-PR interaction# nobody has measured yet, and it is exactly what this differ exists to catch.## The extraction is only worth doing if it cannot change what the gates saw, so the OLD inline block# (copied verbatim out of run 28's setup_md gate) and the NEW pe_ci_baseline run against the SAME two# trees and must agree on all four derived sets AND on the verdict -- not "both printed OK".set -uo pipefailsource /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_resolve.shSCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run96}VENV=${VENV:-/proj/dmfexp/zwhong/scratch_patchexport/run29/venv_ci}export GIT_TERMINAL_PROMPT=0 PYTHONDONTWRITEBYTECODE=1 OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1scrub(){ sed 's#https://[^@]*@#https://<redacted>@#g'; }hdr(){ echo; echo "=================== $* ==================="; date -u; }die(){ echo "VERIFY FAILED: $*"; exit 7; }PY=$VENV/bin/python; [ -x "$PY" ] || die "no venv at $VENV"export PE_PY=$PYmkdir -p "${SCRATCH:?}" || exit 1
hdr "0 context"echo "host=$(hostname) job=${LSB_JOBID:-none} scratch=$SCRATCH py=$("$PY" -V 2>&1)"
clone(){ local W=$1 TOK TOK=$(grep -m1 'https://richardrl:' ~/.git-credentials | sed -E 's|https://richardrl:([^@]*)@.*|\1|') [ -n "$TOK" ] || die "no token" rm -rf "${W:?}"; git init --quiet "$W" || exit 1 printf '[remote "origin"]\n\turl = https://richardrl:%s@github.com/jmarangola/rsm_real.git\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n' "$TOK" >> "$W/.git/config" unset TOK git -C "$W" fetch --quiet origin 2>&1 | scrub || die "fetch failed" git -C "$W" config user.email noreply@anthropic.com git -C "$W" config user.name "richardrl"}
hdr "1 live heads"W=$SCRATCH/mergedclone "$W"MAIN=$(git -C "$W" rev-parse origin/main)echo " main = ${MAIN:0:8} $(git -C "$W" log -1 --format='%ad %an | %s' --date=iso origin/main)"for n in 6 7 8 9 10 11; do echo " #$n head = $(git -C "$W" ls-remote origin "refs/pull/$n/head" | cut -c1-8)"doneSC_HEAD=$(git -C "$W" ls-remote origin "refs/pull/11/head" | awk '{print $1}')
hdr "2 the full six-way trial merge (shared pe_trial_merge)"pe_trial_merge "$W" origin/main || die "trial merge refused/failed"echo " shape:"; printf '%s' "$PE_TRIAL_SHAPE" | sed 's/^/ /'echo " merged head = ${PE_TRIAL_HEAD:0:12} tree = $(git -C "$W" rev-parse --short 'HEAD^{tree}')"printf '%s' "$PE_TRIAL_SHAPE" | grep -q "^11 conflicted" || die "shape changed: #11 no longer conflicts -- re-derive the runbook"for n in 6 7 8 9 10; do printf '%s' "$PE_TRIAL_SHAPE" | grep -q "^$n clean" || echo " NOTE #$n is no longer clean"; done
hdr "3 what #11's new head brought, and what the merge does with it"echo " #11 head = ${SC_HEAD:0:8}"git -C "$W" fetch --quiet --force origin "pull/11/head:pr-11" 2>&1 | scrubecho " files #11 adds under rise_stack/rsm/ :"git -C "$W" ls-tree -r --name-only pr-11 -- rise_stack/rsm | sed 's/^/ /'echo " the SAME paths on the merged tree (#8 deletes the directory):"got=$(git -C "$W" ls-tree -r --name-only HEAD -- rise_stack/rsm)echo "${got:- (absent -- as pe_trial_merge asserts)}" | sed 's/^/ /'echo " #11's rsm_libero tests, present on the merged tree?"for t in tests/test_rise_stack_rsm_libero_closure.py tests/test_rise_stack_rsm_libero_live.py; do if git -C "$W" cat-file -e "HEAD:$t" 2>/dev/null; then echo " PRESENT $t"; else echo " absent $t"; fidoneecho " named by the merged workflow?"pe_ci_set "$W" | tr ' ' '\n' | grep -E 'rsm_libero' | sed 's/^/ /' || echo " (not named)"
hdr "3b the models.py / test_deployment_models.py UNION on the merged tree"# #11's new head rewrote the same dependency_report RSM branch that #8 did, so the runbook grew a# semantic union (patchexport_models_union.py). Assert the merged file carries BOTH sides, not one.for need in "which_scorer import resolve" "_available(\"rsm_libero\")" "has_dir or _available" "rise_stack/rsm_libero/UPSTREAM_COMMIT.txt"; do grep -qF "$need" "$W/real/deployment/models.py" || die "the merged models.py lost: $need" echo " OK merged models.py carries: $need"done[ "$(grep -cF '_available("rsm_libero")' "$W/real/deployment/models.py")" = 2 ] \ || die "ours' installed-package test is not in BOTH branches of the merged models.py""$PY" -c "import ast,sys; ast.parse(open(sys.argv[1]).read())" "$W/real/deployment/models.py" || die "merged models.py does not parse""$PY" -c "import ast,sys; ast.parse(open(sys.argv[1]).read())" "$W/tests/test_deployment_models.py" || die "merged test file does not parse"NT=$("$PY" - "$W/tests/test_deployment_models.py" <<'PYX'import ast,syst=ast.parse(open(sys.argv[1]).read())names=[n.name for n in t.body if isinstance(n,ast.FunctionDef)]assert len(names)==len(set(names)), "duplicate test definitions: %s"%namesprint(len(names))PYX) || die "the merged test file has duplicate definitions"echo " merged test_deployment_models.py defines $NT unique tests"for t in test_installed_rsm_libero_satisfies_the_scorer_source_requirement test_rsm_dependencies_are_satisfied_by_the_vendored_scorer; do grep -q "def $t(" "$W/tests/test_deployment_models.py" || die "the merged test file lost $t" echo " OK merged test file keeps $t"done
hdr "4 baseline worktree: main alone"MW=$SCRATCH/mainonlyrm -rf "${MW:?}"git -C "$W" worktree add --quiet --detach "$MW" origin/main 2>&1 | scrub || die "cannot check out main alone"echo " main alone at $(git -C "$W" rev-parse --short origin/main) in $MW"
hdr "5 sync the gate venv to the MERGED tree's requirements-deployment.txt (shared pe_ci_venv_sync)"pe_ci_venv_sync "$W" || die "venv sync failed"
# ---- the OLD inline block, copied verbatim from run 28's setup_md gate --------------------------# Only difference: `die` becomes a recorded verdict, so the two implementations can be compared on# their outputs instead of one of them exiting the harness.legacy_ci(){ local W=$1 MW=$2 L_RC=0; L_FILES=""; L_BASE=""; L_FAILED=""; L_NEW="" ci_set(){ sed -n 's#^ *\(tests/test_[a-z_]*\.py\) *$#\1#p' "$1/.github/workflows/deployment.yml" | sort -u | tr '\n' ' '; } run_ci(){ ( cd "$1" && PYTHONPATH= "$PY" -m pytest -q -p no:cacheprovider $2 2>&1 ); } newfailures(){ comm -23 <(printf '%s\n' "$1" | sed '/^$/d' | sort -u) <(printf '%s\n' "$2" | sed '/^$/d' | sort -u); } L_FILES=$(ci_set "$W"); [ -n "$L_FILES" ] || { L_RC=1; return; } local f; for f in $L_FILES; do [ -e "$W/$f" ] || { L_RC=1; return; }; done local MFILES BOUT OUT CTRL_NEW MFILES=$(ci_set "$MW") BOUT=$(run_ci "$MW" "$MFILES") L_BASE=$(echo "$BOUT" | grep -E "^(FAILED|ERROR)" | awk '{print $2}' | sort -u) OUT=$(run_ci "$W" "$L_FILES") L_FAILED=$(echo "$OUT" | grep -E "^(FAILED|ERROR)" | awk '{print $2}' | sort -u) CTRL_NEW=$(newfailures "$L_FAILEDtests/test_FABRICATED.py::nope" "$L_BASE") echo "$CTRL_NEW" | grep -q FABRICATED || { L_RC=1; return; } [ -z "$L_BASE" ] || { echo "$CTRL_NEW" | grep -qF "$(echo "$L_BASE" | head -1)" && { L_RC=1; return; }; } L_NEW=$(newfailures "$L_FAILED" "$L_BASE") [ -z "$L_NEW" ] || L_RC=1}
hdr "6 the OLD inline block"legacy_ci "$W" "$MW"echo " legacy rc=$L_RC"echo " legacy CI set : $L_FILES"echo " legacy baseline: $(echo $L_BASE)"echo " legacy merged : $(echo $L_FAILED)"echo " legacy NEW : $(echo $L_NEW)"
hdr "7 the NEW pe_ci_baseline, same two trees"pe_ci_baseline "$W" "$MW"; N_RC=$?echo " new rc=$N_RC"
hdr "8 equivalence: all four derived sets and the verdict must match"eq(){ [ "$(echo $2)" = "$(echo $3)" ] && echo " OK $1 identical" || die "$1 DIFFERS: legacy=[$(echo $2)] new=[$(echo $3)]"; }eq "CI set" "$L_FILES" "$PE_CI_FILES"eq "baseline" "$L_BASE" "$PE_CI_BASE"eq "merged" "$L_FAILED" "$PE_CI_FAILED"eq "NEW" "$L_NEW" "$PE_CI_NEW"[ "$L_RC" = "$N_RC" ] || die "verdict differs: legacy rc=$L_RC new rc=$N_RC"echo " OK verdict identical (rc=$N_RC)"
hdr "9 controls on the NEW function -- it must not be inert"# 9a a fabricated failing test, named by the workflow, must come back as a NEW failure.CW=$SCRATCH/ctrl; rm -rf "${CW:?}"cp -a "$W" "$CW" 2>/dev/null || die "cannot copy the merged tree"rm -rf "$CW/.git/worktrees" 2>/dev/nullcat > "$CW/tests/test_pe_ctrl_planted.py" <<'PY'def test_planted_must_be_reported_as_new(): assert False, "planted by patchexport_cibaseline_verify.sh step 9a"PY"$PY" - "$CW/.github/workflows/deployment.yml" <<'PY'import sys,rep=sys.argv[1]; s=open(p).read()m=re.search(r'^([ \t]+)tests/test_[a-z_]*\.py *$', s, re.M)assert m, "no CI test line to anchor to"s=s[:m.end()]+"\n"+m.group(1)+"tests/test_pe_ctrl_planted.py"+s[m.end():]open(p,'w').write(s)print(" anchored the planted test after", m.group(0).strip())PYpe_ci_set "$CW" | tr ' ' '\n' | grep -q test_pe_ctrl_planted || die "control 9a did not land in the CI set"if pe_ci_baseline "$CW" "$MW" >"$SCRATCH/ctrl9a.log" 2>&1; then sed 's/^/ /' "$SCRATCH/ctrl9a.log" | tail -20; die "control 9a: a planted failing test was NOT reported"figrep -q test_pe_ctrl_planted <<<"$PE_CI_NEW" || { sed 's/^/ /' "$SCRATCH/ctrl9a.log" | tail -20; die "control 9a: refused, but not for the planted test"; }echo " OK 9a planted failure reported as NEW: $(echo $PE_CI_NEW)"# 9b a workflow naming a test file that does not exist must be a refusal, not a silent empty set.rm -f "$CW/tests/test_pe_ctrl_planted.py"pe_ci_baseline "$CW" "$MW" >"$SCRATCH/ctrl9b.log" 2>&1 && die "control 9b: a missing named test file passed"grep -q "which does not exist" "$SCRATCH/ctrl9b.log" || { tail -5 "$SCRATCH/ctrl9b.log" | sed 's/^/ /'; die "control 9b refused for the wrong reason"; }echo " OK 9b workflow naming a missing test file is refused"# 9c an empty/absent workflow must refuse rather than measure nothing.: > "$CW/.github/workflows/deployment.yml"pe_ci_baseline "$CW" "$MW" >"$SCRATCH/ctrl9c.log" 2>&1 && die "control 9c: an empty workflow passed"grep -q "no CI test set in the merged workflow" "$SCRATCH/ctrl9c.log" || { tail -5 "$SCRATCH/ctrl9c.log" | sed 's/^/ /'; die "control 9c refused for the wrong reason"; }echo " OK 9c empty workflow is refused"# 9d the union builder must refuse to run twice (its output carries the marker).U=$SCRATCH/union; rm -rf "$U"; mkdir -p "$U"git -C "$W" show "origin/main:real/deployment/models.py" > "$U/base"git -C "$W" show "pr-11:real/deployment/models.py" > "$U/theirs"git -C "$W" show "pr-8:real/deployment/models.py" > "$U/ours" 2>/dev/null || \ git -C "$W" fetch --quiet --force origin pull/8/head:pr-8 2>&1 | scrub && git -C "$W" show "pr-8:real/deployment/models.py" > "$U/ours""$PY" scripts/real/patchexport_models_union.py models "$U/base" "$U/ours" "$U/theirs" -o "$U/once" || die "control 9d: the union does not build from the live sides""$PY" scripts/real/patchexport_models_union.py models "$U/base" "$U/ours" "$U/once" -o "$U/twice" 2>"$U/e9d" && die "control 9d: the union ran twice"grep -q "does not run twice" "$U/e9d" || { cat "$U/e9d" | sed 's/^/ /'; die "control 9d refused for the wrong reason"; }echo " OK 9d the union refuses to run on its own output"# 9e a side missing its own contribution must be refused, not silently half-applied.sed 's/from rise_stack.which_scorer import resolve as _resolve_scorer/pass # stripped by control 9e/' "$U/theirs" > "$U/theirs_stripped""$PY" scripts/real/patchexport_models_union.py models "$U/base" "$U/ours" "$U/theirs_stripped" -o "$U/bad" 2>"$U/e9e" && die "control 9e: a stripped theirs was accepted"grep -q "not the side this union was written for" "$U/e9e" || { cat "$U/e9e" | sed 's/^/ /'; die "control 9e refused for the wrong reason"; }echo " OK 9e a side without its own contribution is refused"# 9f a moved anchor must refuse rather than write a file that lost one side.sed 's/"vendored", "env", "env-invalid"/"vendored", "env"/' "$U/theirs" > "$U/theirs_moved""$PY" scripts/real/patchexport_models_union.py models "$U/base" "$U/ours" "$U/theirs_moved" -o "$U/bad2" 2>"$U/e9f" && die "control 9f: a moved anchor was accepted"grep -q "anchor occurs 0 times" "$U/e9f" || { cat "$U/e9f" | sed 's/^/ /'; die "control 9f refused for the wrong reason"; }echo " OK 9f a moved anchor is refused"rm -rf "$CW"
hdr "10 #11's negative-control ledger on the merged tree"if [ -x "$W/tests/controls/run_guard_controls.sh" ]; then ( cd "$W" && PYTHONPATH= PY=$PY bash tests/controls/run_guard_controls.sh 2>&1 ) | tail -25 echo " controls ledger rc=${PIPESTATUS[0]}"else echo " no tests/controls/run_guard_controls.sh on the merged tree"fi
hdr "11 re-poll: did anything move while this ran?"git -C "$W" fetch --quiet origin 2>&1 | scrubecho " main now = $(git -C "$W" rev-parse --short origin/main) (was ${MAIN:0:7})"echo " #11 now = $(git -C "$W" ls-remote origin refs/pull/11/head | cut -c1-8) (was ${SC_HEAD:0:8})"git -C "$W" worktree remove --force "$MW" >/dev/null 2>&1 || true
hdr "VERIFY OK"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171#!/usr/bin/env python"""rsm_real#5 item 1 acceptance checks, run INSIDE the freshly built pinned openpi env.
C1 provenance: what was actually imported, and from where (a hidden research checkout must not be able to satisfy the test silently).C2 get_config("pi05_cooking_stock") + data.create() with the training split file ABSENT.C3 the real stock BC checkpoint through the deployment adapter (rise_stack.policies), on a real replay observation, with the split file still absent -> candidates [1, 10, 10], finite."""import argparse, dataclasses, hashlib, json, os, sys, timefrom pathlib import Path
import numpy as np
RESEARCH = "/proj/dmfexp/zwhong/rsm_rise"DATA = f"{RESEARCH}/data/real/rsm_cooking_v5"PROMPT = "Follow the displayed cooking state sequence"
def md5(path, limit=None): h = hashlib.md5() with open(path, "rb") as fh: while True: b = fh.read(1 << 20) if not b: break h.update(b) if limit and fh.tell() > limit: break return h.hexdigest()
def real_frame(ep=0, i=0): """One logged observation: both cameras + the 10-d absolute EE state, and the logged action.""" import av, pyarrow.parquet as pq tab = pq.read_table(f"{DATA}/data/chunk-000/episode_{ep:06d}.parquet").to_pandas() state = np.stack(tab["observation.state"].values).astype(np.float32)[i] action = np.stack(tab["action"].values).astype(np.float32)[i: i + 10] imgs = {} for cam, key in (("global", "observation.images.global"), ("wrist", "observation.images.wrist")): with av.open(f"{DATA}/videos/chunk-000/{key}/episode_{ep:06d}.mp4") as c: st = c.streams.video[0]; st.thread_type = "AUTO" for k, fr in enumerate(c.decode(st)): if k == i: imgs[cam] = fr.to_ndarray(format="rgb24") break return {"images": imgs, "state": state}, action
def main(): ap = argparse.ArgumentParser() ap.add_argument("--repo", required=True) ap.add_argument("--ckpt", required=True) ap.add_argument("--missing-split", required=True) ap.add_argument("--out", required=True) ap.add_argument("--config", default="pi05_cooking_stock") args = ap.parse_args() rep = {"argv": sys.argv, "when": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())}
print("=== C1 provenance ===") print("sys.executable =", sys.executable) print("sys.prefix =", sys.prefix) for v in ("RISE_ROOT", "RSM_LIBERO_DIR", "PYTHONPATH", "HF_HUB_OFFLINE"): print(f"env {v:16s}= {os.environ.get(v, '<unset>')!r}") sys.path.insert(0, args.repo) mods = {} import openpi, jax, numpy import openpi.training.config as C for m in (openpi, jax, numpy): mods[m.__name__] = {"file": str(Path(m.__file__).resolve()), "version": getattr(m, "__version__", None)} import rise_stack mods["rise_stack"] = {"file": str(Path(rise_stack.__file__).resolve()), "version": None} for k, v in mods.items(): print(f"{k:12s} {v['version'] or '':10s} {v['file']}") if v["file"].startswith(RESEARCH + "/third_party") or "/rsm_rise/env/" in v["file"]: raise SystemExit(f"FATAL: {k} was imported from the research checkout: {v['file']}") print("jax devices =", jax.devices()) rep["modules"] = mods rep["jax_devices"] = [str(d) for d in jax.devices()]
print("\n=== C2 config + inference transforms with NO training split file ===") missing = args.missing_split print("missing split path:", missing, "exists =", Path(missing).exists()) orig_get = C.get_config
def split_free(name): cfg = orig_get(name) if hasattr(cfg.data, "split_json"): cfg = dataclasses.replace(cfg, data=dataclasses.replace(cfg.data, split_json=missing)) return cfg
C.get_config = split_free # every consumer, incl. the deployment adapter, now gets it cfg = C.get_config(args.config) print("data factory =", type(cfg.data).__name__, "split_json =", cfg.data.split_json) t0 = time.time() dc = cfg.data.create(cfg.assets_dirs, cfg.model) print(f"data.create() OK in {time.time()-t0:.2f}s") print(" episodes =", dc.episodes) print(" episodes_required_from =", getattr(dc, "episodes_required_from", "<field absent>")) print(" norm_stats from config =", None if dc.norm_stats is None else sorted(dc.norm_stats), f"(loaded from assets_base_dir={cfg.assets_base_dir!r}, which exists on THIS machine; on a " "deployment machine it does not and _load_norm_stats logs 'skipping' -- either way " "create_trained_policy takes the norm stats from <checkpoint>/assets)") print(" data_transforms.inputs =", [type(t).__name__ for t in dc.data_transforms.inputs]) print(" data_transforms.outputs=", [type(t).__name__ for t in dc.data_transforms.outputs]) print(" model_transforms.inputs=", [type(t).__name__ for t in dc.model_transforms.inputs]) print(" action_sequence_keys =", dc.action_sequence_keys, "asset_id =", dc.asset_id) rep["C2"] = {"episodes": dc.episodes, "episodes_required_from": getattr(dc, "episodes_required_from", None), "data_inputs": [type(t).__name__ for t in dc.data_transforms.inputs], "data_outputs": [type(t).__name__ for t in dc.data_transforms.outputs], "model_inputs": [type(t).__name__ for t in dc.model_transforms.inputs], "asset_id": dc.asset_id}
print("\n=== C3 real stock BC checkpoint through the deployment adapter ===") ck = Path(args.ckpt) ident = {"path": str(ck), "metadata_md5": md5(ck / "_CHECKPOINT_METADATA") if (ck / "_CHECKPOINT_METADATA").is_file() else None, "norm_stats": None} ns = list(ck.glob("assets/*/*/norm_stats.json")) if ns: ident["norm_stats"] = {"path": str(ns[0].relative_to(ck)), "md5": md5(ns[0]), "bytes": ns[0].stat().st_size} print("checkpoint identity:", json.dumps(ident, indent=1)) rep["checkpoint"] = ident
from rise_stack.policies import build # the deployment factory used by real/deployment/models.py t0 = time.time() # openpi owns its normalisation inside the checkpoint, so action_norm is None for this kind pol = build(f"openpi:{args.config}:{args.ckpt}", None, seed=0, device="cpu", openpi_batch=0) print(f"policy built in {time.time()-t0:.1f}s: kind={pol.kind} H={pol.H} D={pol.D} " f"jax_device={getattr(pol, 'jax_device', None)} batch={pol.batch}") print("loaded openpi module (after construction) =", sys.modules['openpi'].__file__)
try: obs, logged = real_frame() src = "logged replay frame: episode 0, frame 0" except Exception as e: print("replay frame unavailable (%s: %s) -- falling back to a synthetic observation" % (type(e).__name__, e)) obs = {"images": {"global": np.zeros((224, 224, 3), np.uint8), "wrist": np.zeros((224, 224, 3), np.uint8)}, "state": np.zeros(10, np.float32)} logged, src = None, "synthetic zero observation" print("observation:", src, {k: v.shape for k, v in obs["images"].items()}, "state", obs["state"].shape)
t0 = time.time() cand = pol.candidates(obs, 1, 10) dt = time.time() - t0 cand = np.asarray(cand) print(f"candidates shape={cand.shape} dtype={cand.dtype} finite={bool(np.isfinite(cand).all())} " f"in {dt:.1f}s ({dt*1000:.0f} ms, CPU)") print("first action =", np.array2string(cand[0, 0], precision=6)) if logged is not None: print("logged action =", np.array2string(logged[0], precision=6)) print("xyz L2 first action vs logged = %.3f cm" % (100 * float(np.linalg.norm(cand[0, 0, :3] - logged[0, :3])))) print("per-dim min/max over the chunk:", np.array2string(cand[0].min(0), precision=4), np.array2string(cand[0].max(0), precision=4)) ok = cand.shape == (1, 10, 10) and bool(np.isfinite(cand).all()) rep["C3"] = {"shape": list(cand.shape), "dtype": str(cand.dtype), "finite": bool(np.isfinite(cand).all()), "latency_s": dt, "obs_source": src, "first_action": cand[0, 0].tolist(), "logged_first_action": None if logged is None else logged[0].tolist(), "xyz_l2_first_cm": None if logged is None else 100 * float(np.linalg.norm(cand[0, 0, :3] - logged[0, :3]))} print("C3 VERDICT:", "PASS -- finite absolute actions [1, 10, 10]" if ok else "FAIL") rep["ok"] = ok Path(args.out).write_text(json.dumps(rep, indent=1, default=str)) print("wrote", args.out) sys.exit(0 if ok else 1)
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091#!/usr/bin/env bash# rsm_real#5 item 1, validation half: build the pinned openpi INFERENCE environment from scratch# (uv venv, openpi's own uv.lock, network) with RISE_ROOT / RSM_LIBERO_DIR / PYTHONPATH scrubbed, then# C1 report the actually loaded module paths and revisions# C2 get_config("pi05_cooking_stock") + data.create() with NO training split file# C3 the real stock BC checkpoint through the deployment adapter -> candidates [1,10,10], finite# C4/C5 python -m real.deploy proposer=openpi real.algorithm=vanilla_bc real.simulate=true real.dry_run=true# Nothing is written inside the rsm_rise tree or the rsm_real checkout.set -uo pipefailROOT=/proj/dmfexp/zwhong/rsm_riseSCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run2}SRC=${SRC:-/proj/dmfexp/zwhong/scratch_patchexport/wt_main} # the PR worktree (or a github clone)PIN=215abfb217dbac7d5f1273282331b9b1866c0479CKPT=${CKPT:-$ROOT/hf_ckpt_root/pi05_bc_rsm_real_stock_s1_29999}PATCHED=${PATCHED:-} # optional: an already-patched openpi tree to copy instead of re-patchingUV=${UV:-/u/zwhong/.local/bin/uv}
# ---- the scrub the issue asks for ---------------------------------------------------------------unset RISE_ROOT RSM_LIBERO_DIR PYTHONPATH HF_TOKEN HF_HUB_OFFLINE OPENPI_DATA_HOME HF_LEROBOT_HOMEexport PYTHONNOUSERSITE=1 PYTHONUNBUFFERED=1 TOKENIZERS_PARALLELISM=falseexport UV_CACHE_DIR=$SCRATCH/uv_cacheexport OPENPI_DATA_HOME=$SCRATCH/openpi_assetsexport HF_HOME=$SCRATCH/hf_homeexport JAX_PLATFORMS=${JAX_PLATFORMS:-cpu}
hdr(){ echo; echo "=================== $* ==================="; date -u; }rc_all=0chk(){ if [ "$1" -ne 0 ]; then echo "STEP FAILED rc=$1: $2"; rc_all=1; fi; }
hdr "0 context + env scrub"echo "host=$(hostname) job=${LSB_JOBID:-none} scratch=$SCRATCH src=$SRC ckpt=$CKPT"for v in RISE_ROOT RSM_LIBERO_DIR PYTHONPATH HF_HUB_OFFLINE; do echo " $v='${!v:-<unset>}'"; donemkdir -p "${SCRATCH:?}" || exit 1cd "${SCRATCH:?}" || exit 1
hdr "1 the repo under test"rm -rf "${SCRATCH:?}/rsm_real"git clone --quiet "$SRC" "${SCRATCH:?}/rsm_real" || exit 1REPO=$SCRATCH/rsm_realecho "rsm_real HEAD: $(git -C "$REPO" rev-parse HEAD) $(git -C "$REPO" log -1 --pretty=%s)"ls "$REPO/rise_stack/openpi/" && md5sum "$REPO/rise_stack/openpi/rise_on_pi05.patch"
hdr "2 upstream openpi at the recorded pin, then the repo's patch"rm -rf "${SCRATCH:?}/openpi"if git clone --quiet https://github.com/Physical-Intelligence/openpi.git "${SCRATCH:?}/openpi"; then echo "cloned openpi from GitHub"else echo "GitHub clone failed; falling back to the local mirror $ROOT/third_party/openpi (shallow at the pin)" git clone --quiet --no-local "$ROOT/third_party/openpi" "${SCRATCH:?}/openpi" \ || git clone --quiet "$ROOT/third_party/openpi" "${SCRATCH:?}/openpi" || exit 1figit -C "$SCRATCH/openpi" checkout --quiet "$(cat "$REPO/rise_stack/openpi/UPSTREAM_COMMIT.txt" | head -1)" || exit 1echo "openpi HEAD: $(git -C "$SCRATCH/openpi" rev-parse HEAD)"( cd "$SCRATCH/openpi" && git apply "$REPO/rise_stack/openpi/rise_on_pi05.patch" && echo "git apply: OK" \ && git status --porcelain | sed -n '1,20p' )chk $? "apply the committed patch"
hdr "3 the pinned inference environment (uv sync from openpi's own lock, then the deployment deps)"( cd "$SCRATCH/openpi" && "$UV" sync --frozen 2>&1 | tail -6 )chk $? "uv sync"VENV=$SCRATCH/openpi/.venvPY=$VENV/bin/python# rsm_real/requirements-deployment.txt pins numpy==2.2.6 but openpi caps numpy<2.0.0 -> install the# deployment deps WITHOUT that pin (reported in the PR as a genuine incompatibility)."$UV" pip install --python "$PY" hydra-core==1.3.2 omegaconf==2.3.0 PyYAML==6.0.2 h5py av pyarrow 2>&1 | tail -4chk $? "deployment deps""$PY" -c "import numpy;print('numpy',numpy.__version__)""$UV" pip freeze --python "$PY" > "$SCRATCH/pip_freeze.txt"; wc -l "$SCRATCH/pip_freeze.txt"grep -E "^(jax|jaxlib|jax-cuda|flax|orbax|numpy|torch|transformers|lerobot|hydra-core|omegaconf|opencv|openpi)" "$SCRATCH/pip_freeze.txt"
hdr "4 C1/C2/C3: provenance, split-free config construction, real checkpoint forward pass"MISSING=$SCRATCH/no_such_dir/cooking_v5_split.json"$PY" "$ROOT/scripts/real/patchexport_clean_checks.py" --repo "$REPO" --ckpt "$CKPT" \ --missing-split "$MISSING" --out "$SCRATCH/clean_checks.json"chk $? "clean checks"
hdr "5 C4: real.deploy --print-config (openpi proposer, vanilla_bc, hardware-free)"( cd "$REPO" && "$PY" -m real.deploy --print-config proposer=openpi real.algorithm=vanilla_bc \ real.simulate=true real.dry_run=true real.device=cpu "real.proposer.checkpoint=$CKPT" 2>&1 | sed -n '1,60p' )chk $? "real.deploy --print-config"
hdr "6 C5: real.deploy run, hardware-free (SyntheticEnvironment), 1 episode"( cd "$REPO" && timeout 3000 "$PY" -m real.deploy proposer=openpi real.algorithm=vanilla_bc \ real.simulate=true real.dry_run=true real.device=cpu "real.proposer.checkpoint=$CKPT" \ real.proposer.batch_size=0 real.evaluation.episodes=1 real.evaluation.max_episode_seconds=20 \ real.evaluation.auto_start=true 2>&1 | tail -60 )chk $? "real.deploy simulate+dry_run"
hdr "done"echo "OVERALL rc=$rc_all"exit $rc_all1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950#!/usr/bin/env bash# rsm_real#5 item 1, deployment-entrypoint half. Reuses the clean env built by# patchexport_clean_inference_env.sh (default: run2b) -- no rebuild, no network.# C5b real.deploy with proposer=openpi, vanilla_bc, simulate+dry_run, split file forced ABSENT# C6 the same with dry_run=false, so recording + latency accounting actually runset -uo pipefailROOT=/proj/dmfexp/zwhong/rsm_riseSCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run2b}CKPT=${CKPT:-$ROOT/hf_ckpt_root/pi05_bc_rsm_real_stock_s1_29999}SECS=${SECS:-90}PY=$SCRATCH/openpi/.venv/bin/pythonREPO=$SCRATCH/rsm_realunset RISE_ROOT RSM_LIBERO_DIR PYTHONPATH HF_TOKEN HF_HUB_OFFLINEexport PYTHONNOUSERSITE=1 PYTHONUNBUFFERED=1 TOKENIZERS_PARALLELISM=falseexport OPENPI_DATA_HOME=$SCRATCH/openpi_assets HF_HOME=$SCRATCH/hf_homeexport UV_CACHE_DIR=$SCRATCH/uv_cache JAX_PLATFORMS=${JAX_PLATFORMS:-cpu}hdr(){ echo; echo "=================== $* ==================="; date -u; }rc_all=0chk(){ if [ "$1" -ne 0 ]; then echo "STEP FAILED rc=$1: $2"; rc_all=1; fi; }
hdr "0 context (reusing the prebuilt env; nothing is installed here)"echo "host=$(hostname) job=${LSB_JOBID:-none} py=$PY repo=$REPO"test -x "$PY" || { echo "no prebuilt env at $PY -- run patchexport_clean_inference_env.sh first"; exit 2; }git -C "$REPO" pull --quiet 2>&1 | tail -2echo "repo HEAD: $(git -C "$REPO" rev-parse --short HEAD) $(git -C "$REPO" log -1 --pretty=%s)""$PY" -c "import sys,openpi,jax;print('python',sys.executable);print('openpi',openpi.__file__);print('jax',jax.__version__,jax.devices())"
hdr "1 C5b real.deploy, openpi proposer, vanilla_bc, simulate+dry_run, SPLIT FILE ABSENT"( cd "$REPO" && timeout 1200 "$PY" "$ROOT/scripts/real/patchexport_deploy_nosplit.py" \ proposer=openpi real.algorithm=vanilla_bc real.simulate=true real.dry_run=true real.device=cpu \ "real.proposer.checkpoint=$CKPT" real.proposer.batch_size=0 real.evaluation.episodes=1 \ "real.evaluation.max_episode_seconds=$SECS" real.evaluation.auto_start=true 2>&1 | tail -40 )chk $? "C5b deploy dry_run"
hdr "2 C6 the same with dry_run=false: recording, provenance and latency accounting"( cd "$REPO" && timeout 1800 "$PY" "$ROOT/scripts/real/patchexport_deploy_nosplit.py" \ proposer=openpi real.algorithm=vanilla_bc real.simulate=true real.dry_run=false real.device=cpu \ "real.proposer.checkpoint=$CKPT" real.proposer.batch_size=0 real.evaluation.episodes=1 \ "real.evaluation.max_episode_seconds=$SECS" real.evaluation.auto_start=true \ real.evaluation.run_name=pxclean_openpi_smoke 2>&1 | tail -50 )chk $? "C6 deploy with recording"
hdr "3 what C6 wrote"find "$REPO/outputs" -maxdepth 4 -newermt "-40 minutes" | head -30for f in $(find "$REPO/outputs" -name "*.json" -newermt "-40 minutes" | head -4); do echo "--- $f ---"; head -c 3000 "$f"; echo; done
hdr "done"echo "OVERALL rc=$rc_all"exit $rc_all1234567891011121314151617181920212223242526272829303132333435363738394041#!/usr/bin/env python"""Run `python -m real.deploy` with the openpi cooking config's training split file forced ABSENT.
`real.deploy` builds the proposer through openpi's `create_trained_policy`, which builds the dataconfig; this wrapper points `split_json` at a path that does not exist before that happens, so thedeployment entry point is exercised exactly as it would be on a machine that has no training split.Usage: patchexport_deploy_nosplit.py <hydra overrides...> (run with cwd = the repo root)"""import dataclassesimport osimport sysfrom pathlib import Path
# this script lives outside the repo, so sys.path[0] is its own directory; the repo root is the cwdsys.path.insert(0, os.getcwd())
MISSING = "/nonexistent-deployment-machine/cooking_v5_split.json"
def main() -> int: assert not Path(MISSING).exists(), MISSING import openpi.training.config as C
original = C.get_config
def split_free(name): cfg = original(name) if hasattr(cfg.data, "split_json"): cfg = dataclasses.replace(cfg, data=dataclasses.replace(cfg.data, split_json=MISSING)) return cfg
C.get_config = split_free print(f"[nosplit] openpi.training.config.get_config patched: split_json -> {MISSING} " f"(exists={Path(MISSING).exists()})", flush=True) from real.deploy import main as deploy_main deploy_main(sys.argv[1:]) return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170#!/usr/bin/env python3"""rsm_real#5 run 26 -- the SEVENTH entry in the merge runbook: .github/workflows/deployment.yml.
It appeared the moment the owner pushed `dc2d40d`/`54c054e` to main (2026-09-24 19:03-19:11Z). Untilthen the workflow was one-sided and merged silently. Now BOTH sides edit it:
main (owner) +'requirements/**', +'pyproject.toml' in both path filters; +`pip install --no-deps -e .`; +test_deployment_actions.py, +test_deployment_startup.py #11 (scaffold) +'tests/controls/**', +'tests/test_rise_stack_*.py', +'QUICKSTART.md', +'SETUP.md'; +5 rise_stack test files; +a whole `guard-negative-controls` job
The two sets are DISJOINT -- nobody changed a line the other also changed; they appended at the sameanchors, which is all git needs to refuse. So the resolution is a UNION, and unlike the other sixrunbook entries it is NOT take-ours: dropping either side silently switches CI checks off. Thisbuilds that union deterministically and refuses to emit one it cannot verify.
patchexport_deployment_yml_union.py <base.yml> <ours.yml> <theirs.yml> [-o out.yml]
`ours` is the five-way side (which carries main's edits); `theirs` is #11."""from __future__ import annotations
import argparseimport reimport sysfrom pathlib import Path
PATH_ITEM = re.compile(r"^(\s*)- '([^']+)'\s*$")TEST_ITEM = re.compile(r"^(\s*)(tests/\S+\.py)\s*$")
def path_filter_items(text: str) -> list[str]: return [m.group(2) for m in (PATH_ITEM.match(l) for l in text.splitlines()) if m]
def test_items(text: str) -> list[str]: return [m.group(2) for m in (TEST_ITEM.match(l) for l in text.splitlines()) if m]
def jobs(text: str) -> list[str]: out, in_jobs = [], False for line in text.splitlines(): if line.rstrip() == "jobs:": in_jobs = True continue if in_jobs: m = re.match(r"^ ([A-Za-z0-9_-]+):\s*$", line) if m: out.append(m.group(1)) elif line and not line.startswith(" "): in_jobs = False return out
def build_union(base: str, ours: str, theirs: str) -> str: """Start from THEIRS (it is the superset in structure -- it adds a whole job) and re-apply the additions main made that theirs does not have. Each insertion is anchored on a line that must occur an exact number of times, so a drifted input fails instead of producing a plausible file.""" # dedupe, ORDER-PRESERVING. main's workflow repeats each new path in BOTH of its path filters, so # the raw difference lists every addition twice; the block is then inserted at each of the two # anchors, which multiplied it to four. Caught in run 27 by diffing this builder's output against # #11's own independent resolution (9fefc57): 93 lines vs 89, exactly the four duplicates. def uniq(xs): return list(dict.fromkeys(xs)) add_paths = uniq(p for p in path_filter_items(ours) if p not in path_filter_items(base)) add_tests = uniq(t for t in test_items(ours) if t not in test_items(base)) add_steps = [l for l in ours.splitlines() if l.strip().startswith("python -m pip install") and l not in base.splitlines()] out = theirs # 1. path filters: main's new entries go just before the workflow's own path, in BOTH triggers. anchor = " - '.github/workflows/deployment.yml'" n = out.count(anchor) if n != 2: raise SystemExit(f"anchor {anchor!r} occurs {n} times, expected 2") missing = [p for p in add_paths if p not in path_filter_items(theirs)] if missing: block = "".join(f" - '{p}'\n" for p in missing) out = out.replace(anchor + "\n", block + anchor + "\n") # 2. the editable install, before the torch line it must precede. torch = [l for l in out.splitlines() if "download.pytorch.org" in l] if len(torch) != 1: raise SystemExit(f"expected exactly 1 torch install line, found {len(torch)}") for step in add_steps: if step not in out: out = out.replace(torch[0] + "\n", step + "\n" + torch[0] + "\n") # 3. main's new deployment tests, appended to the deployment pytest invocation. They must land # in the SAME list as the other test_deployment_*.py entries, not in the rise_stack list. anchor_t = [l for l in out.splitlines() if l.strip() == "tests/test_deployment_runtime.py"] if len(anchor_t) != 1: raise SystemExit("expected exactly 1 tests/test_deployment_runtime.py line") add_t = [t for t in add_tests if t not in test_items(theirs)] if add_t: block = "".join(f"{anchor_t[0][:len(anchor_t[0]) - len(anchor_t[0].lstrip())]}{t}\n" for t in add_t) out = out.replace(anchor_t[0] + "\n", anchor_t[0] + "\n" + block) return out
def verify(base: str, ours: str, theirs: str, union: str) -> int: bad = 0
def check(label, ok, detail=""): nonlocal bad print(f" {'OK ' if ok else 'FAIL'} {label}{(' -- ' + detail) if detail else ''}") bad += 0 if ok else 1
up, tp, op = set(path_filter_items(union)), set(path_filter_items(theirs)), set(path_filter_items(ours)) check("path filters are a superset of #11's", tp <= up, f"missing {sorted(tp - up)}") check("path filters are a superset of main's", op <= up, f"missing {sorted(op - up)}") ut, tt, ot = set(test_items(union)), set(test_items(theirs)), set(test_items(ours)) check("every test file #11 runs still runs", tt <= ut, f"lost {sorted(tt - ut)}") check("every test file main runs still runs", ot <= ut, f"lost {sorted(ot - ut)}") check("no test file invented", ut <= (tt | ot), f"extra {sorted(ut - tt - ot)}") uj, tj, oj = set(jobs(union)), set(jobs(theirs)), set(jobs(ours)) check("every job from both sides is present", (tj | oj) <= uj, f"missing {sorted((tj | oj) - uj)}") check("no conflict markers", not re.search(r"^(<<<<<<<|=======|>>>>>>>)", union, re.M)) # Every check above is a SET comparison, which is exactly why the duplicate-entry defect this # builder had survived a run that printed UNION OK. A repeated glob is harmless to GitHub and # invisible to a subset test, so it needs its own check, per filter block and not globally (the # same path legitimately appears in both the pull_request and the push filter). dups = [] for block in re.split(r"^\s*(?:pull_request|push|workflow_dispatch):\s*$", union, flags=re.M)[1:]: items = path_filter_items(block) dups += [i for i in set(items) if items.count(i) > 1] check("no path filter entry repeats within one filter", not dups, f"repeated {sorted(set(dups))}") try: import yaml # noqa d = yaml.safe_load(union) check("parses as YAML", isinstance(d, dict) and "jobs" in d) check("every job has steps", all("steps" in v for v in d["jobs"].values())) except ImportError: print(" SKIP yaml not importable -- structural checks only") # nothing may be LOST relative to either side: every non-blank line of each side survives for label, side in (("main", ours), ("#11", theirs)): lost = [l for l in side.splitlines() if l.strip() and l not in union.splitlines()] check(f"no line of {label}'s workflow dropped", not lost, f"{len(lost)} line(s): {lost[:3]}") return bad
def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("base"); ap.add_argument("ours"); ap.add_argument("theirs") ap.add_argument("-o", "--out") # run 27: #11 resolved this conflict on its own branch (merge 9fefc57), so the question stopped # being "what union would I build" and became "does THEIR file satisfy the same invariants". # Same checks, a candidate supplied instead of constructed -- otherwise a resolution that quietly # took one side is indistinguishable from a real union in any log. ap.add_argument("--verify-only", metavar="CANDIDATE", help="verify an existing resolved workflow instead of building the union") a = ap.parse_args() base, ours, theirs = (Path(p).read_text() for p in (a.base, a.ours, a.theirs)) if a.verify_only: union = Path(a.verify_only).read_text() print(f"candidate = {a.verify_only}, {len(union.splitlines())} lines " f"(base {len(base.splitlines())}, main {len(ours.splitlines())}, #11 {len(theirs.splitlines())})") bad = verify(base, ours, theirs, union) print("CANDIDATE OK" if not bad else f"CANDIDATE REFUSED: {bad} check(s) failed") return 0 if not bad else 3 union = build_union(base, ours, theirs) print(f"union = {len(union.splitlines())} lines " f"(base {len(base.splitlines())}, main {len(ours.splitlines())}, #11 {len(theirs.splitlines())})") bad = verify(base, ours, theirs, union) if a.out and not bad: Path(a.out).write_text(union) print(f"wrote {a.out}") print("UNION OK" if not bad else f"UNION REFUSED: {bad} check(s) failed") return 0 if not bad else 3
if __name__ == "__main__": sys.exit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139#!/usr/bin/env bash# rsm_real#5 -- run 27. ATTRIBUTE THE ONE FAILING TEST ON THE MERGED TREE.## 1904471 (citest2, the first merged-tree pytest run on the owner's new main dc2d40d/54c054e) reported# H0 #11 head 163 PASSED 2 SKIPPED 0 failed# R0 resolved 1 FAILED 197 PASSED 4 SKIPPED# and named the one that moved:# tests/test_deployment_config.py::test_dotted_selector_loads_algorithm_components[rsm-rsm-128]# PASSED -> FAILED# That is a RED merged CI, and the outcome table does not say why: the detail script records verdicts,# not tracebacks. Two questions, and neither may be answered by reading a diff:# (a) WHAT is the assertion? -> run the single node with --tb=long and print it verbatim.# (b) WHOSE change causes it? -> run that same node on main alone, on #11's live head alone, and on# main + each of #6..#11 INDIVIDUALLY, then on the full resolved six-way. A test that fails on# main alone is the owner's and I must tell him; one that fails only in combination is ours.# Both suspects are measured, not assumed: #8 rewrites real/deployment/models.py's rsm branch, and the# published resolution runs `git rm -rf rise_stack/rsm` -- deleting the vendored scorer that main's# own tests may still name by dotted path. If the single-PR sweep is clean and only the resolved tree# fails, the resolution itself is the cause, so the tree is re-tested with the deletion put back.# Read-only w.r.t. every real repo: fetches from GitHub, works only inside SCRATCH, pushes nothing.set -uo pipefailsource /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_resolve.shSCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run89}VENV=${VENV:-/proj/dmfexp/zwhong/scratch_patchexport/run29/venv_ci}NODE='tests/test_deployment_config.py::test_dotted_selector_loads_algorithm_components'PRS="6 7 8 9 10"SC_PR=11export GIT_TERMINAL_PROMPT=0 PYTHONDONTWRITEBYTECODE=1 OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1scrub(){ sed 's#https://[^@]*@#https://<redacted>@#g'; }hdr(){ echo; echo "=================== $* ==================="; date -u; }rc_all=0PY=$VENV/bin/python[ -x "$PY" ] || { echo "no venv at $VENV"; exit 2; }mkdir -p "${SCRATCH:?}" || exit 1M=$SCRATCH/mt
hdr "0 context"echo "host=$(hostname) job=${LSB_JOBID:-none} scratch=$SCRATCH venv=$VENV"echo "node=$NODE"
hdr "1 clone + fetch every side"TOK=$(grep -m1 'https://richardrl:' ~/.git-credentials | sed -E 's|https://richardrl:([^@]*)@.*|\1|')[ -n "$TOK" ] || { echo "NO TOKEN"; exit 1; }rm -rf "${M:?}"; git init --quiet "$M" || exit 1printf '[remote "origin"]\n\turl = https://richardrl:%s@github.com/jmarangola/rsm_real.git\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n' "$TOK" >> "$M/.git/config"unset TOKgit -C "$M" fetch --quiet origin main 2>&1 | scrubgit -C "$M" checkout --quiet -b main FETCH_HEAD 2>&1 | scrubgit -C "$M" config user.email noreply@anthropic.com; git -C "$M" config user.name "dotted-selector attribution"for n in $PRS $SC_PR; do git -C "$M" fetch --quiet origin "pull/$n/head:pr-$n" 2>&1 | scrub; doneMAIN=$(git -C "$M" rev-parse main)echo " main = $(echo "$MAIN" | cut -c1-7) $(git -C "$M" log -1 --format=%s main)"for n in $PRS $SC_PR; do L=$(git -C "$M" ls-remote origin "refs/pull/$n/head" 2>/dev/null | awk '{print $1}') H=$(git -C "$M" rev-parse "pr-$n") S=same; [ "$L" = "$H" ] || S="STALE(live=$(echo "$L"|cut -c1-7))" echo " #$n = $(echo "$H" | cut -c1-7) $S"done
# run1 <label> <treeish-or-CURRENT> -- run the node, print verdict and, when it fails, the traceback.run1(){ local label=$1 out rc # cwd on sys.path is how the repo's own CI imports `real` (see patchexport_merged_tests_detail.sh:168): # PYTHONPATH is emptied on purpose so nothing leaks in from this login environment. out=$(cd "$M" && PYTHONPATH= "$PY" -m pytest "$NODE" -p no:cacheprovider --tb=long -q -rf 2>&1) rc=$? local line line=$(printf '%s\n' "$out" | grep -E '^[0-9]+ (passed|failed)|passed|failed' | tail -1) printf ' %-34s rc=%s %s\n' "$label" "$rc" "$line" if [ "$rc" -ne 0 ]; then printf '%s\n' "$out" | sed -n '/=\+ FAILURES/,/short test summary/p' | sed 's/^/ | /' fi return $rc}
hdr "2 the node on MAIN alone -- is this failure already on the owner's main?"git -C "$M" checkout --quiet mainrun1 "main $(echo "$MAIN"|cut -c1-7)"MAIN_RC=$?
hdr "3 the node on #11's LIVE head alone (it merged main in as 9fefc57 this evening)"git -C "$M" checkout --quiet "pr-$SC_PR"run1 "#11 head"
hdr "4 the node on main + EACH PR individually"for n in $PRS $SC_PR; do git -C "$M" checkout --quiet -B probe main >/dev/null 2>&1 if ! git -C "$M" merge --no-ff -m "probe #$n" "pr-$n" >/dev/null 2>&1; then echo " main+#$n CONFLICTS -- resolving with the runbook helper" FIVE=$(git -C "$M" rev-parse main) pe_resolve "$M" "$FIVE" scripts/setup_env.sh SETUP.md rise_stack/openpi/README.md scripts/check_env.py rise_stack/scorers.py pe_resolve_check "$M" || { echo " main+#$n UNRESOLVED -- skipped"; continue; } git -C "$M" commit --quiet -m "probe #$n resolved" || true fi run1 "main+#$n"done
hdr "5 the full resolved six-way, exactly as the runbook builds it"git -C "$M" checkout --quiet -B sixway main >/dev/null 2>&1for n in $PRS; do git -C "$M" merge --no-ff -m "Merge PR #$n" "pr-$n" >/dev/null 2>&1 || { echo " #$n UNEXPECTED CONFLICT"; exit 2; }; doneFIVE=$(git -C "$M" rev-parse HEAD)git -C "$M" merge --no-ff -m "Merge PR #$SC_PR" "pr-$SC_PR" >/dev/null 2>&1pe_resolve "$M" "$FIVE" scripts/setup_env.sh SETUP.md rise_stack/openpi/README.md scripts/check_env.py rise_stack/scorers.pype_resolve_check "$M" || { echo " RESOLUTION INCOMPLETE -- stopping"; exit 2; }HAD_RSM=noif [ -d "$M/rise_stack/rsm" ]; then HAD_RSM=yes; git -C "$M" rm -rf -f --quiet rise_stack/rsm || exit 2; figit -C "$M" commit --quiet -m "scratch: six-way + published resolution" || trueecho " resolved = $(git -C "$M" rev-parse --short HEAD) vendored rise_stack/rsm was present and deleted: $HAD_RSM"run1 "resolved six-way"SIX_RC=$?
hdr "6 if only the resolved tree fails: is the CAUSE the rise_stack/rsm deletion?"if [ "$SIX_RC" -ne 0 ] && [ "$HAD_RSM" = yes ]; then git -C "$M" checkout --quiet HEAD~0 >/dev/null 2>&1 git -C "$M" checkout --quiet "$FIVE" -- rise_stack/rsm 2>/dev/null \ || git -C "$M" checkout --quiet "pr-$SC_PR" -- rise_stack/rsm 2>/dev/null if [ -d "$M/rise_stack/rsm" ]; then echo " put rise_stack/rsm back ($(ls "$M/rise_stack/rsm" | tr '\n' ' '))" run1 "resolved + rsm/ restored" [ $? -eq 0 ] && echo " => the DELETION of the vendored scorer is the cause" \ || echo " => the deletion is NOT the cause; look at the traceback above" else echo " could not restore rise_stack/rsm -- inconclusive" fi # And the other suspect, independent of the deletion: #8's models.py rsm branch. git -C "$M" checkout --quiet -B m8probe "$FIVE" >/dev/null 2>&1 git -C "$M" checkout --quiet main -- real/deployment/models.py echo " reverted real/deployment/models.py to main's copy on the five-way" run1 "five-way + main's models.py"else echo " not applicable (six-way rc=$SIX_RC, vendored dir present=$HAD_RSM)"fi
hdr "7 cleanup"rm -rf "${M:?}"echo "removed $M"
hdr "OVERALL rc=$rc_all (main alone rc=$MAIN_RC, resolved rc=$SIX_RC)"exit $rc_all123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198#!/usr/bin/env python3"""rsm_real#5 -- move the LAST hardcoded upstream pins out of our two scripts and into pin files.
Two pins were still written as literals after run 23 replaced the two DINOv2 shas in``setup_env.sh`` with ``dino_pin()``:
* ``diffusion_policy`` -- the short sha ``078ce1e``, three times in two files (``scripts/setup_env.sh`` twice, once per --env branch, and ``scripts/check_env.py`` once), with **no** ``rise_stack/diffusion_policy/UPSTREAM_COMMIT.txt`` at all. Nothing compared the three, and ``check_tree`` compares ``HEAD.startswith(pin[:12])`` -- so a 7-character pin silently degraded the check it exists to perform to a 7-character compare. * ``dinov2`` -- the full 40-hex sha, in ``scripts/check_env.py``, while the same commit is recorded as ``dino_commit`` in ``rise_stack/rsm_libero/UPSTREAM_COMMIT.txt`` and read from there by ``setup_env.sh``. A *checker* carrying its own copy of the value it checks fails in the direction that wastes the most time: edit the pin, clone the new commit correctly, and the checker reports the correct tree as wrong. #11's ``tests/test_rise_stack_openpi_patch_numbers.py`` guards ``setup_env.sh`` against hardcoded shas and does not look at ``check_env.py``, so this copy was unguarded.
Every edit is anchored on text that must appear EXACTLY the expected number of times; anything elseexits 3 rather than guessing, and the caller does not push. Run against a clean checkout of``patchexport/env-setup``; ``--check`` verifies an already-transformed tree instead of writing.
usage: patchexport_dp_pin.py <worktree> <dp_full_sha> [--check]"""from __future__ import annotations
import pathlibimport reimport sys
DP_SHORT = "078ce1e"DINO_FULL = "7764ea0f912e53c92e82eb78a2a1631e92725fc8"
CLONE_OLD = ("clone_at diffusion_policy https://github.com/UWRobotLearning/diffusion_policy.git " + DP_SHORT)CLONE_NEW = ('clone_at diffusion_policy https://github.com/UWRobotLearning/diffusion_policy.git ' '"$(pin_of diffusion_policy)"')COMMENT_OLD = " # diffusion_policy: upstream is UNCHANGED by us, so it is a pin with no patch.\n"COMMENT_NEW = ( " # diffusion_policy: upstream is UNCHANGED by us, so it is a pin with no patch -- and the pin\n" " # therefore lives in rise_stack/diffusion_policy/UPSTREAM_COMMIT.txt, not in this script.\n")
TREES_OLD = (f'dp_tree = check_tree("diffusion_policy", "diffusion_policy", "{DP_SHORT}")\n' f'dino_tree = check_tree("dinov2", "dinov2", "{DINO_FULL}")\n')TREES_NEW = ('dp_tree = check_tree("diffusion_policy", "diffusion_policy", pin_of("diffusion_policy"))\n' 'dino_tree = check_tree("dinov2", "dinov2", dino_pin())\n')
PIN_OF_TAIL = ''' if re.fullmatch(r"[0-9a-fA-F]{7,40}", line): return line return ""'''
DINO_FN = PIN_OF_TAIL + '''
def dino_pin() -> str: """The DINOv2 backbone commit, read from the ONE place it is recorded.
It is `dino_commit` in rise_stack/rsm_libero/UPSTREAM_COMMIT.txt, because DINOv2 is the featuriser that library's checkpoints were built against. This function exists because the sha was ALSO written out in full here, so a checker whose whole job is to catch drift carried its own copy of the thing that drifts: change the pin and this file would have reported the correctly-cloned tree as wrong. scripts/setup_env.sh reads the same key the same way. """ f = REPO / "rise_stack" / "rsm_libero" / "UPSTREAM_COMMIT.txt" if not f.is_file(): return "" m = re.search(r"^dino_commit\\s*=\\s*([0-9a-fA-F]{7,40})\\b", f.read_text(), re.M) return m.group(1) if m else ""'''
PINS_DP_OLD = ("| `code/diffusion_policy` | `UWRobotLearning/diffusion_policy` | `078ce1e` | **none** " "| pin only; needed for `LowdimMaskGenerator`. Cannot be pip-installed -- see the " "robomimic README |")PINS_DP_NEW = ("| `code/diffusion_policy` | `UWRobotLearning/diffusion_policy` | `078ce1e` " "([full sha](diffusion_policy/UPSTREAM_COMMIT.txt)) | **none** | pin only; needed for " "`LowdimMaskGenerator`. Cannot be pip-installed -- see the robomimic README. The pin is " "recorded in [`rise_stack/diffusion_policy/UPSTREAM_COMMIT.txt`]" "(diffusion_policy/UPSTREAM_COMMIT.txt) and read from there by `scripts/setup_env.sh` " "and `scripts/check_env.py`; neither hardcodes it |")PINS_DINO_OLD = "Weights: the published `dinov2_vits14_pretrain.pth`, sha256 `b938bf1b…` |"PINS_DINO_NEW = ("Weights: the published `dinov2_vits14_pretrain.pth`, sha256 `b938bf1b…`. The commit is " "recorded ONCE, as `dino_commit` in [`rise_stack/rsm_libero/UPSTREAM_COMMIT.txt`]" "(rsm_libero/UPSTREAM_COMMIT.txt) (DINOv2 is the featuriser those checkpoints were built " "against); `setup_env.sh` and `check_env.py` both read it from there |")
PIN_FILE = """# diffusion_policy -- pin only, no patch. Our checkout has ZERO diff against upstream (measured# 2026-09-23: 0 modified, 0 untracked source files), so there is no .patch beside this file: the# pin IS the whole story, which is exactly why the pin has to be recorded somewhere a reader can# find and a script can parse.## It is recorded HERE, once, because the sha used to be written down three times in two files --# scripts/setup_env.sh twice (--env a and --env b) and scripts/check_env.py once -- and nothing# compared any two of them. That is the duplication class that already cost this repo a pin:# see `dino_commit` in rise_stack/rsm_libero/UPSTREAM_COMMIT.txt.## Only the short form `{short}` was ever written down before. check_env.py's tree check compares# HEAD against `pin[:12]`, so a 7-character pin silently degraded that to a 7-character compare.repo = https://github.com/UWRobotLearning/diffusion_policy.gitcommit = {full}date = 2025-01-27T12:42:52Zpatch = none -- upstream is used unmodifiedneeded_for = diffusion_policy.model.diffusion.mask_generator.LowdimMaskGenerator, imported by the robomimic fork's diffusion-policy algos (environment B). Cannot be pip-installed: its setup.py installs no package and fails silently -- see scripts/setup_env.sh."""
def refuse(msg: str) -> None: print(f"REFUSING: {msg}") raise SystemExit(3)
def main() -> int: if len(sys.argv) < 3: print(__doc__) return 2 w = pathlib.Path(sys.argv[1]) full = sys.argv[2].strip().lower() check_only = "--check" in sys.argv[3:] if not re.fullmatch(r"[0-9a-f]{40}", full): refuse(f"{full!r} is not a 40-character sha") if not full.startswith(DP_SHORT): refuse(f"{full[:12]} does not start with the pin {DP_SHORT} every document quotes")
se = w / "scripts" / "setup_env.sh" ce = w / "scripts" / "check_env.py" pins = w / "rise_stack" / "UPSTREAM_PINS.md" pinf = w / "rise_stack" / "diffusion_policy" / "UPSTREAM_COMMIT.txt" for f in (se, ce, pins): if not f.is_file(): refuse(f"{f} is missing -- wrong branch?")
if check_only: s, c, p = se.read_text(), ce.read_text(), pins.read_text() bare = re.compile(r"(?<![0-9a-f])[0-9a-f]{40}(?![0-9a-f])") problems = [] if DP_SHORT in s or DP_SHORT in c: problems.append("a literal 078ce1e survives in a script") if DINO_FULL in c: problems.append("the dinov2 literal survives in check_env.py") for f, body in ((se, s), (ce, c)): if bare.findall(body): problems.append(f"{f.name} carries a bare 40-hex sha {bare.findall(body)}") if 'pin_of diffusion_policy' not in s: problems.append("setup_env.sh does not call pin_of diffusion_policy") if s.count(CLONE_NEW) != 2: problems.append(f"setup_env.sh has {s.count(CLONE_NEW)} pin_of clone sites, expected 2") if "def dino_pin(" not in c: problems.append("check_env.py has no dino_pin()") if not pinf.is_file(): problems.append("the pin file was not written") elif not re.search(rf"^commit\s*=\s*{full}$", pinf.read_text(), re.M): problems.append("the pin file does not record the full sha as `commit = ...`") if PINS_DP_NEW not in p or PINS_DINO_NEW not in p: problems.append("UPSTREAM_PINS.md does not name where the pins live") for x in problems: print(f" !! {x}") print("CHECK " + ("FAILED" if problems else "OK")) return 4 if problems else 0
s = se.read_text() if s.count(CLONE_OLD) != 2: refuse(f"expected 2 inline diffusion_policy pins in setup_env.sh, found {s.count(CLONE_OLD)}") if s.count(COMMENT_OLD) != 1: refuse("the 'pin with no patch' comment is not present exactly once") s = s.replace(CLONE_OLD, CLONE_NEW).replace(COMMENT_OLD, COMMENT_NEW) if DP_SHORT in s: refuse("a literal 078ce1e survives in setup_env.sh after the rewrite")
c = ce.read_text() if c.count(TREES_OLD) != 1: refuse("the diffusion_policy/dinov2 check_tree pair is not present verbatim exactly once") if c.count(PIN_OF_TAIL) != 1: refuse("pin_of()'s tail is not present exactly once -- cannot place dino_pin() safely") c = c.replace(TREES_OLD, TREES_NEW).replace(PIN_OF_TAIL, DINO_FN) if DINO_FULL in c or DP_SHORT in c: refuse("a literal sha survives in check_env.py after the rewrite")
p = pins.read_text() if p.count(PINS_DP_OLD) != 1 or p.count(PINS_DINO_OLD) != 1: refuse("UPSTREAM_PINS.md rows are not present verbatim exactly once each") p = p.replace(PINS_DP_OLD, PINS_DP_NEW).replace(PINS_DINO_OLD, PINS_DINO_NEW)
se.write_text(s) ce.write_text(c) pins.write_text(p) pinf.parent.mkdir(parents=True, exist_ok=True) pinf.write_text(PIN_FILE.format(short=DP_SHORT, full=full)) print(f" setup_env.sh : 2 inline pins -> $(pin_of diffusion_policy), comment updated") print(f" check_env.py : dp -> pin_of(), dinov2 -> dino_pin() (new, reads dino_commit)") print(f" pin file : {pinf.relative_to(w)} commit = {full}") print(f" UPSTREAM_PINS.md: both rows now name where the pin lives") return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220#!/usr/bin/env bash# SUPERSEDED 2026-09-24 (run 28): this gate trial-merges a SUBSET, not main + #6..#10 + #11.# That hole is a measured failure of this stream -- LSF 1902702 caught a conflict AFTER a push whose# gate merged only `main -> #6 -> #10`. Do not reuse this script for a new push. Copy# scripts/real/patchexport_readme_dedupe_push.sh instead: it does the full merge with pe_resolve, runs# #11's control ledger on the merged tree, and diffs pytest against a baseline MEASURED on main alone# rather than against a hardcoded expectation.# rsm_real#5 run 24 -- the last two hardcoded upstream pins leave our scripts, gated and pushed.## What it changes (via scripts/real/patchexport_dp_pin.py, which refuses to guess):# * new rise_stack/diffusion_policy/UPSTREAM_COMMIT.txt with the FULL sha; setup_env.sh's two# inline `078ce1e` literals become $(pin_of diffusion_policy) and check_env.py's one becomes# pin_of("diffusion_policy").# * check_env.py's full-length dinov2 sha becomes dino_pin(), reading the `dino_commit` already# recorded in rise_stack/rsm_libero/UPSTREAM_COMMIT.txt -- the same key setup_env.sh reads# since run 23. #11's tests/test_rise_stack_openpi_patch_numbers.py guards setup_env.sh# against hardcoded shas and never looks at check_env.py, so this copy was unguarded.## Only PR #10 (patchexport/env-setup) carries these files. Measured, not assumed: #6's tree has no# scripts/ directory at all (GitHub trees API on 49d68ec), so this is a one-branch change and the# "identical blob on both branches" guard the openpi-README push needed does not apply here.## The gate refuses to push unless, in order: the branch is in sync with origin, the transform# reproduces from a CLEAN tree, --check passes, the pinned commit EXISTS upstream and `078ce1e` is# its prefix, `bash -n` + `py_compile` pass, all four --print-pin answers are right with the three# pre-existing ones BYTE-IDENTICAL to the pushed head, check_env.py actually prints both resolved# pins when executed, no bare 40-hex survives in either script, and the five-way merge is clean.set -uo pipefailS=${S:-/proj/dmfexp/zwhong/scratch_patchexport/run69}WT=${WT:-/proj/dmfexp/zwhong/scratch_patchexport/wt_setup} # #10, patchexport/env-setupBR=${BR:-patchexport/env-setup}WT_MAIN=${WT_MAIN:-/proj/dmfexp/zwhong/scratch_patchexport/wt_main} # #6, merge trial onlyDP_FULL=${DP_FULL:-078ce1ee2064cde28074db239ff0af2f9254069b}DINO_FULL=7764ea0f912e53c92e82eb78a2a1631e92725fc8DO_PUSH=${DO_PUSH:-0}D=/proj/dmfexp/zwhong/rsm_rise/scripts/realexport GIT_TERMINAL_PROMPT=0scrub(){ sed 's#https://[^@]*@#https://<redacted>@#g'; }hdr(){ echo; echo "=================== $* ==================="; date -u; }mkdir -p "$S"; rc=0FILES="scripts/setup_env.sh scripts/check_env.py rise_stack/UPSTREAM_PINS.md"
hdr "0 context and the in-sync guard"echo "host=$(hostname) job=${LSB_JOBID:-none} do_push=$DO_PUSH wt=$WT"echo " on $(git -C "$WT" rev-parse --abbrev-ref HEAD) @ $(git -C "$WT" rev-parse --short HEAD)"[ "$(git -C "$WT" rev-parse --abbrev-ref HEAD)" = "$BR" ] || { echo " wrong branch -- REFUSING"; exit 2; }git -C "$WT" fetch --quiet origin "$BR" 2>&1 | scrub || exit 2L=$(git -C "$WT" rev-parse HEAD); R=$(git -C "$WT" rev-parse FETCH_HEAD)[ "$L" = "$R" ] || { echo " local ${L:0:7} != origin ${R:0:7} -- REFUSING"; exit 2; }# The tree may carry this run's own edits; anything ELSE is someone else's work and stops the job.DIRT=$(git -C "$WT" status --porcelain | awk '{print $NF}' | grep -vE '^(scripts/setup_env.sh|scripts/check_env.py|rise_stack/UPSTREAM_PINS.md|rise_stack/diffusion_policy/)$')[ -z "$DIRT" ] || { echo " unexpected dirty paths -- REFUSING:"; echo "$DIRT"; exit 2; }
hdr "1 baseline --print-pin on the PUSHED head, before anything is rewritten"git -C "$WT" checkout --quiet -- $FILES 2>/dev/nullrm -rf "$WT/rise_stack/diffusion_policy"[ -z "$(git -C "$WT" status --porcelain)" ] || { echo " tree not clean after reset -- REFUSING"; exit 2; }for d in openpi robomimic rsm_libero; do printf '%s %s\n' "$d" "$(cd "$WT" && PRINT_PIN=$d bash scripts/setup_env.sh 2>&1 | tail -1)"done | tee "$S/pins_before.txt"
hdr "2 the transform, from the clean tree"python3 "$D/patchexport_dp_pin.py" "$WT" "$DP_FULL" || { echo " transform refused"; exit 3; }python3 "$D/patchexport_dp_pin.py" "$WT" "$DP_FULL" --check || { echo " --check failed"; exit 4; }
hdr "3 the pinned commit EXISTS upstream, and 078ce1e is its prefix"TOK=$(grep -m1 'https://richardrl:' ~/.git-credentials | sed -E 's|https://richardrl:([^@]*)@.*|\1|')[ -n "$TOK" ] || { echo "NO TOKEN"; exit 2; }curl -s -H "Authorization: token $TOK" \ "https://api.github.com/repos/UWRobotLearning/diffusion_policy/commits/$DP_FULL" > "$S/dp_commit.json"unset TOKpython3 - "$S/dp_commit.json" "$DP_FULL" <<'PY' || rc=5import json, sysd = json.load(open(sys.argv[1])); want = sys.argv[2]if d.get("sha") != want: print(f" !! upstream does not have {want[:12]}: {d.get('message', d.get('sha'))}"); raise SystemExit(1)print(f" upstream HAS {want} ({d['commit']['committer']['date']}, {d['commit']['message'].splitlines()[0][:60]!r})")print(f" short form quoted by every document: {want[:7]} -> prefix: {want.startswith(want[:7])}")PY[ $rc -eq 0 ] || { echo " refusing to pin a commit I cannot see"; exit $rc; }
hdr "4 syntax, and the parsers EXERCISED rather than read"( cd "$WT" && bash -n scripts/setup_env.sh ) && echo " bash -n scripts/setup_env.sh OK" || rc=6( cd "$WT" && python3 -m py_compile scripts/check_env.py ) && echo " py_compile scripts/check_env.py OK" || rc=6for d in openpi robomimic rsm_libero diffusion_policy; do printf '%s %s\n' "$d" "$(cd "$WT" && PRINT_PIN=$d bash scripts/setup_env.sh 2>&1 | tail -1)"done | tee "$S/pins_after.txt"echo " the three pre-existing pins must be byte-identical to the pushed head:"if diff <(cat "$S/pins_before.txt") <(grep -vE '^diffusion_policy ' "$S/pins_after.txt"); then echo " unchanged"else echo " A PRE-EXISTING PIN MOVED -- REFUSING"; rc=6figrep -q "^diffusion_policy $DP_FULL$" "$S/pins_after.txt" || { echo " pin_of diffusion_policy is wrong"; rc=6; }[ $rc -eq 0 ] || exit $rc
hdr "4b both readers, every pin dir -- this branch's own tests/test_rise_stack_pins.py grows a case"# That test is parametrized over rise_stack/*/UPSTREAM_COMMIT.txt and asserts BOTH readers return the# same FULL sha, so adding a pin file adds a case: it has to pass before the push, not after.( cd "$WT" && for d in $(ls -d rise_stack/*/UPSTREAM_COMMIT.txt | sed 's|rise_stack/||;s|/UPSTREAM_COMMIT.txt||'); do sh=$(PRINT_PIN=$d bash scripts/setup_env.sh 2>&1 | tail -1) py=$(python3 scripts/check_env.py --print-pin "$d" 2>&1 | tail -1) st=AGREE; [ "$sh" = "$py" ] || st=MISMATCH case "$sh" in *[!0-9a-f]*|"") st="NOT-A-SHA/$st";; esac [ ${#sh} -eq 40 ] || st="SHORT/$st" printf ' %-18s shell=%s python=%s %s\n' "$d" "$sh" "$py" "$st" [ "$st" = AGREE ] || exit 1 done ) || { echo " a pin disagrees between the two readers -- REFUSING"; exit 6; }CIVENV=${CIVENV:-/proj/dmfexp/zwhong/scratch_patchexport/run29/venv_ci}if [ -x "$CIVENV/bin/pytest" ]; then ( cd "$WT" && "$CIVENV/bin/pytest" -q tests/test_rise_stack_pins.py 2>&1 | tail -5 ) [ ${PIPESTATUS[0]:-0} -eq 0 ] || true # the tail hides the code; the summary line is the evidence ( cd "$WT" && "$CIVENV/bin/pytest" -q tests/test_rise_stack_pins.py >/dev/null 2>&1 ) \ || { echo " tests/test_rise_stack_pins.py FAILED -- REFUSING"; exit 6; } echo " tests/test_rise_stack_pins.py passed"else echo " !! no pytest at $CIVENV -- the pins test was NOT run (say so, do not imply it passed)"fi
hdr "4c dino_pin() itself -- --print-pin never reaches it"python3 "$D/patchexport_dp_pin_readers.py" "$WT" || { echo " a reader is wrong -- REFUSING"; exit 6; }
hdr "5 check_env.py, EXECUTED, actually COMPARES against both resolved pins"# Run 24's job (LSF 1902328) exited 7 here with both shas NEVER PRINTED, and the gate was right to# refuse but wrong about the reason: check_tree() returns at `if not cloned` (scripts/check_env.py:113)# and never reaches the pin comparison, so on a machine with no third_party/ clones the checker# reports "MISSING: clone" and compares nothing. A plain run therefore cannot prove the readers# resolve. patchexport_check_env_pin_probe.sh points $RISE_DEPS at two throwaway git repos with a# deliberately wrong HEAD, which forces the comparison branch and makes the real module-level call# print `this repo pins <sha>` -- and then hides the pin files and requires that same assertion to# go RED, because a check that cannot fail is not a check.( cd "$WT" && timeout 600 python3 scripts/check_env.py > "$S/check_env.log" 2>&1 )echo " plain run (no clones here): exit=$? ($(wc -l < "$S/check_env.log") lines) -- reports MISSING, compares nothing:"grep -nE 'diffusion_policy|dinov2' "$S/check_env.log" | head -5 | sed 's/^/ /'bash "$D/patchexport_check_env_pin_probe.sh" "$WT" "$DP_FULL" "$DINO_FULL" "$S" || rc=7[ $rc -eq 0 ] || exit $rc
hdr "6 no bare 40-hex sha survives in either script (#11's guard, run here first)"python3 - "$WT" <<'PY' || rc=8import pathlib, re, sysw = pathlib.Path(sys.argv[1])bare = re.compile(r"(?<![0-9a-f])[0-9a-f]{40}(?![0-9a-f])")bad = 0for rel in ("scripts/setup_env.sh", "scripts/check_env.py"): hits = bare.findall((w / rel).read_text()) print(f" {rel}: bare40={hits}") bad += len(hits)raise SystemExit(1 if bad else 0)PY[ $rc -eq 0 ] || { echo " a hardcoded sha remains"; exit $rc; }
hdr "7 commit"MSG=$(cat <<'EOM'The last two hardcoded pins leave the scripts: diffusion_policy gets a pin file, dinov2 is read once
rsm_real#5. Run 23 replaced setup_env.sh's two DINOv2 shas with dino_pin(). Two literals wereleft, and both are the same defect one level further in:
* `diffusion_policy` was pinned as the SHORT sha `078ce1e`, written three times in two files -- scripts/setup_env.sh twice (once per --env branch) and scripts/check_env.py once -- with no rise_stack/diffusion_policy/UPSTREAM_COMMIT.txt at all. Nothing compared the three copies. check_env.py's tree check is `HEAD.startswith(pin[:12])`, so a 7-character pin silently degraded the check to a 7-character compare. The pin file now records the full sha 078ce1ee2064cde28074db239ff0af2f9254069b (verified present upstream, and `078ce1e` is its prefix, so every document that quotes the short form stays correct), and both call sites read it with pin_of. * `dinov2` was pinned by its FULL sha in check_env.py while the same commit is recorded as `dino_commit` in rise_stack/rsm_libero/UPSTREAM_COMMIT.txt and read from there by setup_env.sh. A checker carrying its own copy of the value it checks fails in the most expensive direction: edit the pin, clone the new commit correctly, and the checker reports the correct tree as wrong. #11's tests/test_rise_stack_openpi_patch_numbers.py guards setup_env.sh against hardcoded shas and does not look at check_env.py, so this copy was unguarded by the test that exists precisely to catch it.
Only this branch carries the two scripts: #6's tree has no scripts/ directory (GitHub trees API on49d68ec), so this is a one-branch change.
The edit is scripts/real/patchexport_dp_pin.py, which anchors on text that must appear an exactnumber of times and exits 3 otherwise, and re-runs with --check afterwards. Gated before the push(scripts/real/patchexport_dp_pin_push.sh): the pinned commit fetched from the upstream API; bash -nand py_compile; `--print-pin` for all four dependencies with the three pre-existing answersbyte-identical to the pushed head; scripts/check_env.py EXECUTED against two throwaway git reposinjected through $RISE_DEPS, so check_tree() reaches its comparison branch and has to print the pinit compares against -- with the pin files then hidden and that same assertion required to go red,because check_tree returns at `if not cloned` and a plain run on a machine without the clonescompares nothing at all (that is how LSF 1902328 exited 7); no bare 40-hex sha left in eitherscript; and a clean five-way merge.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>EOM)git -C "$WT" add $FILES rise_stack/diffusion_policy/UPSTREAM_COMMIT.txtgit -C "$WT" commit -q -m "$MSG" || { echo " commit failed"; exit 2; }echo " $BR -> $(git -C "$WT" rev-parse --short HEAD)"git -C "$WT" show --stat --oneline HEAD | head -8
hdr "8 trial five-way merge (main -> #6 -> this)"T=$(mktemp -d /proj/dmfexp/zwhong/scratch_patchexport/dppin.XXXXXX)git clone --quiet --shared --no-checkout "$WT" "$T/r" 2>/dev/nullgit -C "$T/r" fetch --quiet "$WT" HEAD:local-setupgit -C "$T/r" fetch --quiet "$WT_MAIN" HEAD:local-maingit -C "$T/r" fetch --quiet "$WT" refs/remotes/origin/main:local-mainlinegit -C "$T/r" checkout --quiet -b trial local-mainlinegit -C "$T/r" config user.email noreply@anthropic.com; git -C "$T/r" config user.name "dp pin trial"if git -C "$T/r" merge --no-ff -q -m "trial #6" local-main && git -C "$T/r" merge --no-ff -q -m "trial #10" local-setup; then echo " #6 then #10: MERGED CLEAN"else echo " TRIAL MERGE CONFLICTED"; git -C "$T/r" diff --name-only --diff-filter=U; rc=9firm -rf "$T"[ $rc -eq 0 ] || { echo " not pushing"; exit $rc; }
hdr "9 push"if [ "$DO_PUSH" = "1" ]; then git -C "$WT" push origin "HEAD:$BR" 2>&1 | scrub || rc=2else echo " DO_PUSH=0 -- committed locally only"fihdr "OVERALL rc=$rc"exit $rc12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758#!/usr/bin/env python3"""Exercise check_env.py's two pin readers WITHOUT running the whole checker.
`scripts/setup_env.sh --print-pin` covers `pin_of` on the shell side and `check_env.py --print-pin`covers it on the python side, but NEITHER touches `dino_pin()`: that function is called once, atmodule level, in `check_tree("dinov2", "dinov2", dino_pin())`, so the only way to reach it is to runthe whole checker -- which imports openpi and torch and therefore belongs in a job. This lifts thetwo function definitions out of the real source with `ast` (not a copy of them) and calls them, so areader that silently returns "" cannot reach a push just because the cluster is busy. The full`python3 scripts/check_env.py` run is still owed; this is a floor, not a substitute.
usage: patchexport_dp_pin_readers.py <worktree>"""from __future__ import annotations
import astimport pathlibimport reimport sys
EXPECT = { ("dino_pin",): "7764ea0f912e53c92e82eb78a2a1631e92725fc8", ("pin_of", "diffusion_policy"): "078ce1ee2064cde28074db239ff0af2f9254069b", ("pin_of", "rsm_libero"): "f612011bb400ac204918be1d6f923e539cd59fd7", ("pin_of", "openpi"): "215abfb217dbac7d5f1273282331b9b1866c0479", ("pin_of", "robomimic"): "40e427a695a9f085d3fc0f70ffb0d687a10802c8",}
def main() -> int: if len(sys.argv) < 2: print(__doc__) return 2 w = pathlib.Path(sys.argv[1]) src = (w / "scripts" / "check_env.py").read_text() ns: dict = {"re": re, "REPO": w, "Path": pathlib.Path} found = [] for node in ast.parse(src).body: if isinstance(node, ast.FunctionDef) and node.name in {"pin_of", "dino_pin"}: exec(compile(ast.Module(body=[node], type_ignores=[]), "check_env.py", "exec"), ns) found.append(node.name) print(f" lifted from the real source: {found}") if set(found) != {"pin_of", "dino_pin"}: print(" !! a reader is missing from check_env.py") return 3 bad = 0 for call, want in EXPECT.items(): got = ns[call[0]](*call[1:]) ok = got == want bad += not ok print(f" {'ok' if ok else '!!'} {call[0]}({', '.join(map(repr, call[1:]))}) -> {got or '(empty)'}" + ("" if ok else f" expected {want}")) print("READERS " + ("OK" if not bad else "WRONG")) return 4 if bad else 0
if __name__ == "__main__": raise SystemExit(main())12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455#!/usr/bin/env bash# Cover commit 9d18628 (the `--env c` rsm_libero probe imported `model` directly, which CANNOT work:# our packaging patch installs the PACKAGE rsm_libero, whose __init__ puts its own directory on# sys.path so the library's internal unqualified imports resolve). The probe printed# "rsm_libero missing (No module named 'model') -- bc_idql works here, rsm does not"# in an interpreter where check_env.py reported RSM reranking PASS. Only the printed line was wrong,# but it is the line a labmate reads to decide whether they can rerank. Everything in --env c is# stamped and idempotent, so this re-run is cheap; it asserts the corrected line and that check_env# still agrees with it.set -uo pipefailROOT=/proj/dmfexp/zwhong/rsm_riseSCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run9}REPO=$SCRATCH/rsm_realSRC=${SRC:-/proj/dmfexp/zwhong/scratch_patchexport/wt_setup}export CKPTS=${CKPTS:-$ROOT/hf_ckpt_root}unset RISE_ROOT RSM_LIBERO_DIR PYTHONPATH HF_TOKEN HF_HUB_OFFLINE HF_LEROBOT_HOMEexport PYTHONNOUSERSITE=1 PYTHONUNBUFFERED=1 TOKENIZERS_PARALLELISM=false JAX_PLATFORMS=cpuexport UV_CACHE_DIR=$SCRATCH/uv_cache HF_HOME=$SCRATCH/hf_home TORCH_HOME=$SCRATCH/torch_homeexport MPLCONFIGDIR=$SCRATCH/mpl OPENPI_DATA_HOME=$SCRATCH/openpi_assets GIT_TERMINAL_PROMPT=0hdr(){ echo; echo "=================== $* ==================="; date -u; }rc_all=0chk(){ if [ "$1" -ne 0 ]; then echo "STEP FAILED rc=$1: $2"; rc_all=1; fi; }
hdr "0 context"echo "host=$(hostname) job=${LSB_JOBID:-none} repo=$REPO"WANT=$(git -C "$SRC" rev-parse HEAD)# checkout -f, never reset --hard + clean: third_party/ and .venvs/ are UNTRACKED here and hold the# already-built environments this job exists to reuse.git -C "$REPO" fetch --quiet origin && git -C "$REPO" checkout -f --quiet "$WANT"chk $? "checkout $WANT"echo "rsm_real now at: $(git -C "$REPO" rev-parse --short HEAD) $(git -C "$REPO" log -1 --pretty=%s)"[ -d "$REPO/third_party/openpi/.venv" ] || { echo "environment A was destroyed by the checkout"; exit 1; }PY_A=$REPO/third_party/openpi/.venv/bin/python
hdr "1 setup_env.sh --env c, and the line the probe prints"OUT=$SCRATCH/envc_probe.txt( cd "$REPO" && bash scripts/setup_env.sh --env c 2>&1 ) | tee "$OUT"chk ${PIPESTATUS[0]} "setup_env.sh --env c"echo "--- the rsm_libero line ---"grep -n "rsm_libero" "$OUT"if grep -q "rsm_libero missing" "$OUT"; then echo "REGRESSION: the probe still reports rsm_libero missing"; rc_all=1figrep -qE "rsm_libero (imports|from) " "$OUT" || { echo "the corrected line is absent"; rc_all=1; }
hdr "2 check_env.py must agree with it"( cd "$REPO" && "$PY_A" scripts/check_env.py > "$SCRATCH/envc_checkenv.txt" 2>&1 )chk $? "check_env C"grep -E "rsm_libero|RSM reranking|IQL reranking|real.algorithm=rsm" "$SCRATCH/envc_checkenv.txt"echo "PASS rows: $(grep -c '^ PASS' "$SCRATCH/envc_checkenv.txt") MISSING rows: $(grep -c '^ MISSING' "$SCRATCH/envc_checkenv.txt")"[ "$(grep -c '^ MISSING' "$SCRATCH/envc_checkenv.txt")" -eq 0 ] || { echo "environment C has MISSING rows"; rc_all=1; }
hdr "done"echo "OVERALL rc=$rc_all"exit $rc_all1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798#!/usr/bin/env bash# Validate the sparse/blobless gen_q clone that scripts/setup_env.sh now uses, against the full clone# it used before. The full clone measured 2.5 GB and ~20 min on this filesystem (LSF 1888352) to# deliver the 2,862 lines of rsm_libero/ that are actually used.set -uo pipefailSCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run11}REPO=${REPO:-/proj/dmfexp/zwhong/scratch_patchexport/wt_setup}URL=https://github.com/williamd4112/gen_q.gitPIN=f612011bb400ac204918be1d6f923e539cd59fd7PATCHF=$REPO/rise_stack/rsm_libero/rise_on_rsm_libero.patchhdr(){ echo; echo "=================== $* ==================="; date -u; }rc_all=0chk(){ if [ "$1" -ne 0 ]; then echo "STEP FAILED rc=$1: $2"; rc_all=1; fi; }rm -rf "${SCRATCH:?}"; mkdir -p "${SCRATCH:?}" || exit 1
hdr "0 context"echo "host=$(hostname) job=${LSB_JOBID:-none} git=$(git --version)"echo "patch: $PATCHF"; md5sum "$PATCHF"
hdr "1 the exact sequence clone_at now runs for gen_q"t0=$(date +%s)git clone --quiet --filter=blob:none --no-checkout "$URL" "$SCRATCH/gen_q"; chk $? "clone"git -C "$SCRATCH/gen_q" sparse-checkout init --cone; chk $? "sparse init"git -C "$SCRATCH/gen_q" sparse-checkout set rsm_libero; chk $? "sparse set"git -C "$SCRATCH/gen_q" fetch --quiet --all 2>/dev/nullgit -C "$SCRATCH/gen_q" checkout --quiet "$PIN"; chk $? "checkout pin"t1=$(date +%s)echo "HEAD: $(git -C "$SCRATCH/gen_q" rev-parse HEAD)"echo "HEAD == pin: $([ "$(git -C "$SCRATCH/gen_q" rev-parse HEAD)" = "$PIN" ] && echo YES || echo NO)"echo "ELAPSED clone+checkout: $((t1-t0)) s"echo "ON DISK: $(du -sh "$SCRATCH/gen_q" | cut -f1) (.git: $(du -sh "$SCRATCH/gen_q/.git" | cut -f1))"
hdr "2 the sparse cone contains what the patch and the scorer need"echo "--- top level of the working tree ---"ls -1 "$SCRATCH/gen_q" | head -20echo "--- rsm_libero/ present? ---"ls -1 "$SCRATCH/gen_q/rsm_libero"/*.py 2>/dev/null | head -20echo "count: $(ls -1 "$SCRATCH/gen_q/rsm_libero"/*.py 2>/dev/null | wc -l)"for f in model.py train_rsm.py is_ope.py data.py; do [ -f "$SCRATCH/gen_q/rsm_libero/$f" ] && echo " OK $f ($(wc -l < "$SCRATCH/gen_q/rsm_libero/$f") lines)" \ || { echo " MISSING $f"; rc_all=1; }doneecho "total lines of the four modules: $(cat "$SCRATCH/gen_q/rsm_libero"/{model,train_rsm,is_ope,data}.py | wc -l)"
hdr "3 our packaging patch applies inside the sparse checkout"( cd "$SCRATCH/gen_q" && git apply --check "$PATCHF" && echo "git apply --check OK" && git apply "$PATCHF" && echo "git apply OK" )chk $? "apply packaging patch"echo "--- the two files it creates ---"for f in rsm_libero/__init__.py pyproject.toml; do [ -f "$SCRATCH/gen_q/$f" ] && echo " OK $f ($(wc -l < "$SCRATCH/gen_q/$f") lines)" || { echo " MISSING $f"; rc_all=1; }doneecho "--- pyproject.toml ---"; cat "$SCRATCH/gen_q/pyproject.toml"
hdr "4 the sparse clone is byte-identical to the tree the validated RSM run used"# run7/gen_q is the clone LSF 1887661 used when it loaded the real successor checkpoint and produced# finite scores -- and it is ITSELF a sparse checkout at the same pin. So the reference for "does the# sparse clone deliver the right bytes" already exists and is one the real checkpoints ran against.REF=/proj/dmfexp/zwhong/scratch_patchexport/run7/gen_qif [ -d "$REF/rsm_libero" ]; then echo "reference: $REF HEAD=$(git -C "$REF" rev-parse HEAD) sparse=[$(git -C "$REF" sparse-checkout list 2>/dev/null | tr '\n' ' ')]" diff -r -q "$REF/rsm_libero" "$SCRATCH/gen_q/rsm_libero" \ --exclude=__pycache__ --exclude=__init__.py && echo "rsm_libero/ identical to the validated tree" chk $? "sparse clone == the tree the RSM validation ran against"else echo "reference clone absent -- skipping (record this as NOT CHECKED, do not claim it)"fi
hdr "5 pip install -e it, then import rsm_libero and the four top-level modules for real""${PY:-/u/zwhong/.local/bin/python3.11}" -m venv "$SCRATCH/venv" 2>/dev/null || python3 -m venv "$SCRATCH/venv"chk $? "venv""$SCRATCH/venv/bin/pip" install --quiet --upgrade pip setuptools wheel >/dev/null 2>&1# torch is needed because rsm_libero/model.py imports it at module scope; CPU wheel is enough here."$SCRATCH/venv/bin/pip" install --quiet "numpy==1.26.4" "torch==2.5.1" \ --index-url https://download.pytorch.org/whl/cpu --extra-index-url https://pypi.org/simplechk $? "numpy + torch (cpu)""$SCRATCH/venv/bin/pip" install --quiet -e "$SCRATCH/gen_q"; chk $? "pip install -e gen_q"env -u PYTHONPATH -u RSM_LIBERO_DIR -u RISE_ROOT "$SCRATCH/venv/bin/python" - <<'PYEOF'import syssys.path = [p for p in sys.path if "rsm_rise" not in p and "gen_q/rsm_libero" not in p]import rsm_liberoprint("rsm_libero ->", rsm_libero.__file__)import model, train_rsm, is_ope, datafor name, m in (("model", model), ("train_rsm", train_rsm), ("is_ope", is_ope), ("data", data)): print(f"{name:15s} ->", m.__file__) f = m.__file__ or "" assert "/proj/dmfexp/zwhong/rsm_rise" not in f, f"{name} came from the research tree" assert "issue_resolver" not in f, f"{name} came from the research tree" assert "/run11/gen_q/" in f, f"{name} did not come from the sparse clone: {f}"import torchprint("torch", torch.__version__)print("VERDICT: the sparse clone supplies rsm_libero and all four top-level modules," " and nothing resolved into the research tree")PYEOFchk $? "import from the sparse clone"
hdr "done"echo "OVERALL rc=$rc_all"exit $rc_all123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128#!/usr/bin/env bash# rsm_real#5 run 25 -- do #11's NEW negative controls still FIRE once the runbook's take-ours# resolutions are applied?## #11's 9fb9abf added tests/controls/run_guard_controls.sh (300 lines): each control mutates a# staged copy of an input and requires the guard to go RED and name the drift. It is the right# idea and it is the same idea this stream just had to apply to its own push gate (LSF 1902328# asserted check_env.py prints a pin, and the assertion was unsatisfiable because check_tree()# returns at `if not cloned`).## But the controls key on EXACT strings (`grep -c -F`) in files the merge resolves to OUR side:# ours (take-ours, per patchexport_merged_tests_detail.sh):# scripts/setup_env.sh SETUP.md rise_stack/openpi/README.md scripts/check_env.py# theirs (one-sided #11):# QUICKSTART.md rise_stack/configs/baselines.yaml rise_stack/CHECKPOINTS.md# A control whose target string lives only in THEIR copy of an ours-resolved file reports# `rc=99 NON-RESULT` -- their harness is honest about that, it does not count it as a pass -- and# the guard it was meant to police is then unpoliced on the tree a human would actually merge.## So run their own harness, unmodified, twice: on #11's head (H) and on the resolved tree (R).# Any label that is 0 on H and 99 on R is a control the MERGE silently disables. Read-only: fetches# from GitHub, works only in SCRATCH, pushes nothing.set -uo pipefailsource /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_resolve.shSCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run76}VENV=${VENV:-/proj/dmfexp/zwhong/scratch_patchexport/run29/venv_ci}PRS=${PRS:-"6 7 8 9 10"}SC_PR=${SC_PR:-11}CTL=tests/controls/run_guard_controls.shexport GIT_TERMINAL_PROMPT=0 PYTHONDONTWRITEBYTECODE=1 OMP_NUM_THREADS=1scrub(){ sed 's#https://[^@]*@#https://<redacted>@#g'; }hdr(){ echo; echo "=================== $* ==================="; date -u; }rc_all=0mkdir -p "${SCRATCH:?}" || exit 1M=$SCRATCH/mtPY=$VENV/bin/python[ -x "$PY" ] || { echo "no venv at $VENV"; exit 2; }
hdr "0 context"echo "host=$(hostname) job=${LSB_JOBID:-none} scratch=$SCRATCH"
hdr "1 build main + five-way merge + the published take-ours resolution"TOK=$(grep -m1 'https://richardrl:' ~/.git-credentials | sed -E 's|https://richardrl:([^@]*)@.*|\1|')[ -n "$TOK" ] || { echo "NO TOKEN"; exit 1; }rm -rf "${M:?}"; git init --quiet "$M" || exit 1printf '[remote "origin"]\n\turl = https://richardrl:%s@github.com/jmarangola/rsm_real.git\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n' "$TOK" >> "$M/.git/config"unset TOKgit -C "$M" fetch --quiet origin main 2>&1 | scrubgit -C "$M" checkout --quiet -b main FETCH_HEAD 2>&1 | scrubgit -C "$M" config user.email noreply@anthropic.com; git -C "$M" config user.name "guard-controls merged"for n in $PRS $SC_PR; do git -C "$M" fetch --quiet origin "pull/$n/head:pr-$n" 2>&1 | scrub; doneSC_SHA=$(git -C "$M" rev-parse "pr-$SC_PR")LIVE=$(git -C "$M" ls-remote origin "refs/pull/$SC_PR/head" 2>/dev/null | awk '{print $1}')[ "$LIVE" = "$SC_SHA" ] || { echo "STALE: $SC_SHA != $LIVE -- #11 moved again"; exit 2; }echo " #$SC_PR head = $(echo "$SC_SHA" | cut -c1-7) (live)"for n in $PRS; do git -C "$M" merge --no-ff -m "Merge PR #$n" "pr-$n" >/dev/null 2>&1 || { echo "#$n UNEXPECTED CONFLICT"; exit 2; }; doneFIVE=$(git -C "$M" rev-parse HEAD)git -C "$M" merge --no-ff -m "Merge PR #$SC_PR" "pr-$SC_PR" >/dev/null 2>&1echo " conflicted: $(git -C "$M" diff --name-only --diff-filter=U | tr '\n' ' ')"pe_resolve "$M" "$FIVE" scripts/setup_env.sh SETUP.md rise_stack/openpi/README.md scripts/check_env.py rise_stack/scorers.py[ -z "$(git -C "$M" diff --name-only --diff-filter=U)" ] || { echo " RESOLUTION INCOMPLETE:"; git -C "$M" diff --name-only --diff-filter=U; exit 2; }git -C "$M" rm -rf -f --quiet rise_stack/rsm 2>/dev/nullgit -C "$M" commit --quiet -m "scratch: five-way + #$SC_PR + take-ours resolution" || trueRES=$(git -C "$M" rev-parse HEAD)echo " resolved = $(echo "$RES" | cut -c1-7)"
hdr "2 the harness exists on the head, and is IDENTICAL on the resolved tree"git -C "$M" cat-file -e "$SC_SHA:$CTL" 2>/dev/null || { echo " $CTL not on #$SC_PR head"; exit 2; }HB=$(git -C "$M" rev-parse "$SC_SHA:$CTL"); RB=$(git -C "$M" rev-parse "$RES:$CTL" 2>/dev/null || echo ABSENT)echo " blob on head=$(echo "$HB" | cut -c1-10) on resolved=$(echo "$RB" | cut -c1-10) $([ "$HB" = "$RB" ] && echo IDENTICAL || echo DIFFERENT)"[ "$HB" = "$RB" ] || rc_all=2
hdr "3 which of the harness's inputs does the merge take from OUR side?"for f in SETUP.md QUICKSTART.md scripts/setup_env.sh rise_stack/openpi/README.md \ rise_stack/openpi/rise_on_pi05.patch rise_stack/openpi/UPSTREAM_COMMIT.txt \ rise_stack/configs/baselines.yaml rise_stack/CHECKPOINTS.md rise_stack/README.md \ tests/test_deployment_models.py; do h=$(git -C "$M" rev-parse "$SC_SHA:$f" 2>/dev/null || echo ABSENT) r=$(git -C "$M" rev-parse "$RES:$f" 2>/dev/null || echo ABSENT) printf ' %-45s head=%s resolved=%s %s\n' "$f" "$(echo "$h"|cut -c1-10)" "$(echo "$r"|cut -c1-10)" \ "$([ "$h" = "$r" ] && echo same || echo "DIFFERENT -> resolved side wins")"done
hdr "4 run THEIR harness, unmodified, on #$SC_PR's head (H)"WH=$SCRATCH/t_head; WR=$SCRATCH/t_resrm -rf "$WH" "$WR"git -C "$M" worktree add --quiet --detach "$WH" "$SC_SHA" || exit 2git -C "$M" worktree add --quiet --detach "$WR" "$RES" || exit 2( cd "$WH" && PY="$PY" REPO="$WH" timeout 1800 bash "$CTL" 2>&1 ) | tee "$SCRATCH/H.log" | tail -45echo " H exit=${PIPESTATUS[0]}"
hdr "5 run THEIR harness, unmodified, on the RESOLVED tree (R)"( cd "$WR" && PY="$PY" REPO="$WR" timeout 1800 bash "$CTL" 2>&1 ) | tee "$SCRATCH/R.log" | tail -45echo " R exit=${PIPESTATUS[0]}"
hdr "6 label by label -- which controls the MERGE disables"python3 - "$SCRATCH/H.log" "$SCRATCH/R.log" <<'PY'import re, sys, pathlibdef rcs(p): out = {} for line in pathlib.Path(p).read_text().splitlines(): m = re.match(r'^(\S+) rc=(\d+)', line.strip()) if m and not m.group(1).startswith('==='): out[m.group(1)] = (int(m.group(2)), line.strip()) return outH, R = rcs(sys.argv[1]), rcs(sys.argv[2])labels = sorted(set(H) | set(R))print(f" {'label':32s} {'head':>6s} {'resolved':>9s} verdict")bad = []for L in labels: h = H.get(L, (None,))[0]; r = R.get(L, (None,))[0] if h == r: v = "same" elif r == 99: v = "*** the MERGE turns this control into a NON-RESULT ***"; bad.append(L) elif h == 99: v = "fires only after the merge" else: v = "*** CHANGED ***"; bad.append(L) print(f" {L:32s} {str(h):>6s} {str(r):>9s} {v}")print()for L in bad: if L in R: print(f" {L}: {R[L][1]}")print(f"\n {len(bad)} control(s) differ between the head and the tree a human would merge")raise SystemExit(1 if bad else 0)PY[ $? -eq 0 ] || rc_all=1
hdr "7 cleanup"git -C "$M" worktree remove --force "$WH" 2>/dev/null; git -C "$M" worktree remove --force "$WR" 2>/dev/nullhdr "OVERALL rc=$rc_all (1 = a control behaves differently on the merged tree)"exit $rc_all12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273#!/usr/bin/env python3"""Which RSMScorer actually loads? Execute the shipped fallback block, don't read it.
rsm_real#5/#4: PR #8 removes the vendored `rise_stack/rsm/rsm_scorer.py` and supplies`robomimic.algo.rsm_scorer` from the robomimic patch; the scaffold branch keeps the vendored copy and`rise_stack/scorers.py` tries it FIRST. After a six-way merge both exist, so the question "which oneruns" has one answer and it is decided by the code text, not by intent. This extracts the realtry/except out of a given commit's `rise_stack/scorers.py` and runs it verbatim with BOTH candidatesimportable as stubs, and prints the winner.
usage: patchexport_import_winner.py <repo> <rev> <label>"""import osimport reimport subprocessimport sysimport tempfileimport textwrap
repo, rev, label = sys.argv[1], sys.argv[2], sys.argv[3]# rev may be "" -> `git show :path`, i.e. stage 0 of the index (the in-progress merge result)src = subprocess.run(["git", "-C", repo, "show", f"{rev}:rise_stack/scorers.py"], capture_output=True, text=True)if src.returncode != 0: print(f" {label}: no rise_stack/scorers.py at {rev}") sys.exit(0)lines = src.stdout.splitlines()hits = [i for i, l in enumerate(lines) if re.search(r"rsm_scorer import RSMScorer", l)]if not hits: print(f" {label}: no rsm_scorer import found -- nothing to resolve") sys.exit(0)start = Nonefor j in range(hits[0], max(-1, hits[0] - 6), -1): if lines[j].strip() == "try:": start = j breakif start is None: # Single source, no fallback. Still EXECUTE it with both stubs importable: a probe that reports # "nothing to resolve" and exits is a check that has degraded to nothing, which is the failure mode # this whole gate exists to catch. The import line is indented inside a method, so dedent it. start = end = hits[0] single = Trueelse: end = max(h for h in hits if h < start + 14) single = Falseblock = textwrap.dedent("\n".join(lines[start:end + 1]))order = ["vendored rise_stack.rsm.rsm_scorer" if ".rsm.rsm_scorer" in lines[h] else "fork robomimic.algo.rsm_scorer" for h in hits if start <= h <= end]kind = "single source, no fallback" if single else "fallback chain"print(f" {label} ({rev[:8] or 'merge index'}): {kind} = {' THEN '.join(order)}")
d = tempfile.mkdtemp(prefix="imp_")os.makedirs(f"{d}/rise_stack/rsm", exist_ok=True)os.makedirs(f"{d}/robomimic/algo", exist_ok=True)stub = "SOURCE=%r\nclass RSMScorer: pass\ndef chain_continuation_p(*a, **k): pass\ndef chain_cap_fn(*a, **k): pass\n"for f, body in [("rise_stack/__init__.py", ""), ("rise_stack/rsm/__init__.py", ""), ("robomimic/__init__.py", ""), ("robomimic/algo/__init__.py", ""), ("rise_stack/rsm/rsm_scorer.py", stub % "VENDORED rise_stack/rsm/rsm_scorer.py"), ("robomimic/algo/rsm_scorer.py", stub % "FORK robomimic/algo/rsm_scorer.py (our patch)")]: with open(os.path.join(d, f), "w") as fh: fh.write(body)with open(f"{d}/block.py", "w") as fh: fh.write(block)runner = ( f"import sys, types\n" f"sys.path.insert(0, {d!r})\n" f"m = types.ModuleType('rise_stack.scorers'); m.__package__='rise_stack'\n" f"sys.modules['rise_stack.scorers'] = m\n" f"exec(compile(open({os.path.join(d, 'block.py')!r}).read(), 'scorers_block', 'exec'), m.__dict__)\n" f"print(' both candidates importable -> WINNER:', sys.modules[m.RSMScorer.__module__].SOURCE)\n")r = subprocess.run([sys.executable, "-c", runner], capture_output=True, text=True)print(r.stdout.rstrip() if r.stdout.strip() else " PROBE FAILED:\n" + r.stderr.rstrip()[-600:])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253#!/usr/bin/env bash# rsm_real#5 item 1: (a) rebuild the openpi patch with the inference/training-split fix, (b) prove the# fix leaves stock pi0.5 BC actions BIT-IDENTICAL on replay frames, (c) prove the pre-fix patch cannot# construct the policy when the training split file is absent.# Everything happens in $SCRATCH -- the rsm_rise tree is only read.set -uo pipefailROOT=/proj/dmfexp/zwhong/rsm_riseREPO=${REPO:-/proj/dmfexp/zwhong/projs/rsm_real}PATCH_REF=${PATCH_REF:-920ead0}SCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run1}PIN=215abfb217dbac7d5f1273282331b9b1866c0479CKPT=${CKPT:-$ROOT/hf_ckpt_root/pi05_bc_rsm_real_stock_s1_29999}PY=$ROOT/third_party/openpi/.venv/bin/pythonFRAMES=${FRAMES:-8}EP=${EP:-0}MISSING=$SCRATCH/no_such_dir/cooking_v5_split.json
export OPENPI_DATA_HOME=$ROOT/.openpi_assets HF_LEROBOT_HOME=$ROOT/data/real/lerobot_homeexport HF_HUB_OFFLINE=1 TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1export JAX_PLATFORMS=${JAX_PLATFORMS:-cpu}unset PYTHONPATH
hdr(){ echo; echo "=================== $* ==================="; date -u; }rc_all=0chk(){ if [ "$1" -ne 0 ]; then echo "STEP FAILED rc=$1: $2"; rc_all=1; fi; }
hdr "0 context"echo "host=$(hostname) job=${LSB_JOBID:-none} scratch=$SCRATCH patch_ref=$PATCH_REF ckpt=$CKPT"mkdir -p "${SCRATCH:?}" || exit 1cd "${SCRATCH:?}" || exit 1
hdr "1 take the exported patch out of rsm_real (by commit, so a branch switch cannot change it)"git -C "$REPO" show "$PATCH_REF:rise_stack/openpi/rise_on_pi05.patch" > "$SCRATCH/rise_on_pi05.orig.patch" || exit 1wc -l "$SCRATCH/rise_on_pi05.orig.patch"; md5sum "$SCRATCH/rise_on_pi05.orig.patch"git -C "$REPO" show "$PATCH_REF:rise_stack/openpi/UPSTREAM_COMMIT.txt"
hdr "2 three clean upstream trees at $PIN"for t in pre post verify; do rm -rf "${SCRATCH:?}/${t:?}" # the fork's .git is SHALLOW at the pin; --no-local avoids hardlinking into it, plain clone is the fallback git clone --quiet --no-local "$ROOT/third_party/openpi" "${SCRATCH:?}/${t:?}" \ || git clone --quiet "$ROOT/third_party/openpi" "${SCRATCH:?}/${t:?}" || exit 1 git -C "$SCRATCH/$t" checkout --quiet "$PIN" || exit 1 echo "$t: HEAD=$(git -C "$SCRATCH/$t" rev-parse HEAD) dirty=[$(git -C "$SCRATCH/$t" status --porcelain | head -3)]"done
hdr "3 apply the exported patch to pre/ and post/"for t in pre post; do ( cd "$SCRATCH/$t" && git apply --stat "$SCRATCH/rise_on_pi05.orig.patch" | tail -3 \ && git apply "$SCRATCH/rise_on_pi05.orig.patch" && echo "$t: git apply OK" ) chk $? "git apply on $t"donetest -f "$SCRATCH/pre/src/openpi/policies/cooking_policy.py" && echo "cooking_policy.py present in pre/: yes"
hdr "4 apply the episodes fix to post/""$PY" - "$SCRATCH/post" <<'FIXEOF'import sys, pathlibroot = pathlib.Path(sys.argv[1])
def sub(relpath, old, new, tag): p = root / relpath s = p.read_text() n = s.count(old) if n != 1: raise SystemExit(f"FATAL: {tag}: anchor found {n} times in {relpath}, expected 1") p.write_text(s.replace(old, new)) print(f"[fix] {tag}: {relpath} patched")
# --- 1. DataConfig: record the split file that was requested -------------------------------------sub("src/openpi/training/config.py",""" # rsm_rise: restrict the LeRobot dataset to these episode indices (None = all). episodes: Sequence[int] | None = None""",""" # rsm_rise: restrict the LeRobot dataset to these episode indices (None = all). episodes: Sequence[int] | None = None # rsm_rise (rsm_real#5): the split file `episodes` was asked to come from, recorded even when that # file was absent when the config was built. `episodes` is a TRAINING-only field, but openpi builds # the data config during policy construction, so inference must be able to build it without the # split file; the training data loader refuses to run when this is set and `episodes` is None. episodes_required_from: str | None = None""", "DataConfig.episodes_required_from")
# --- 2. episode_subset(): missing split file is an inference case, not an error -------------------sub("src/openpi/training/config.py",""" def episode_subset(self) -> list[int] | None: if self.split == "all" or self.split_json is None: return None import json
with open(self.split_json) as fh:""",""" def episode_subset(self) -> list[int] | None: if self.split == "all" or self.split_json is None: return None import json import os
if not os.path.exists(self.split_json): # rsm_real#5: openpi builds this data config during POLICY CONSTRUCTION, so requiring the # training split file here made inference depend on a training-only absolute path. The # `episodes` field is consumed ONLY by training (data_loader.create_torch_dataset), so # returning None leaves every inference transform and the checkpoint normalisation # untouched. Training does not silently fall back to all episodes: create_torch_dataset # raises when `episodes_required_from` is set and `episodes` is None. logging.warning( "episode split file %s not found: continuing with episodes=None. This is the " "inference path; a training run with this config will fail in create_torch_dataset.", self.split_json, ) return None with open(self.split_json) as fh:""", "episode_subset() inference fallback")
# --- 3. create(): pass the requested split path through ------------------------------------------sub("src/openpi/training/config.py",""" episodes=self.episode_subset(),""",""" episodes=self.episode_subset(), episodes_required_from=(self.split_json if self.split != "all" else None),""", "create() episodes_required_from")
# --- 4. the training guard -----------------------------------------------------------------------sub("src/openpi/training/data_loader.py",""" if repo_id == "fake": return FakeDataset(model_config, num_samples=1024)
dataset_meta = lerobot_dataset.LeRobotDatasetMetadata(repo_id)""",""" if repo_id == "fake": return FakeDataset(model_config, num_samples=1024)
# rsm_rise (rsm_real#5): `episodes` is None either because no subset was requested or because the # split file was missing when the config was built (the inference path -- see # LeRobotCookingDataConfig.episode_subset). Training must never take the second branch silently: # it would train on the held-out validation episodes. if data_config.episodes is None and data_config.episodes_required_from is not None: raise FileNotFoundError( f"episode split file {data_config.episodes_required_from!r} is required to build the " "training dataset for this config and was not found; refusing to fall back to all " "episodes (that would train on the held-out split)." )
dataset_meta = lerobot_dataset.LeRobotDatasetMetadata(repo_id)""", "create_torch_dataset training guard")print("[fix] all four hunks applied")FIXEOFchk $? "apply fix to post/"
hdr "5 regenerate the patch from post/ (git add -A so no untracked file can be omitted again)"( cd "$SCRATCH/post" && git add -A && git diff --cached > "$SCRATCH/rise_on_pi05.new.patch" \ && echo "--- files touched by the new patch ---" && git diff --cached --stat | tail -12 \ && echo "--- untracked left behind (must be empty) ---" && git status --porcelain | grep '^??' )echo "(no untracked leftovers is the expected empty grep above)"wc -l "$SCRATCH/rise_on_pi05.new.patch"; md5sum "$SCRATCH/rise_on_pi05.new.patch"echo "files in new patch: $(grep -c '^+++ ' "$SCRATCH/rise_on_pi05.new.patch")"
hdr "6 the new patch applies clean to a pristine upstream clone and reproduces post/ exactly"( cd "$SCRATCH/verify" && git apply --check "$SCRATCH/rise_on_pi05.new.patch" && echo "git apply --check: OK" \ && git apply "$SCRATCH/rise_on_pi05.new.patch" && echo "git apply: OK" )chk $? "apply new patch to verify/"diff -r -q --exclude=.git "$SCRATCH/post" "$SCRATCH/verify" && echo "post/ == verify/ (patch is complete)"chk $? "post == verify"
hdr "7 construct-only checks (no weights): pre/ vs post/, split file present vs absent"for t in pre post; do for sj in PRESENT MISSING; do echo "--- tree=$t split=$sj ---" "$PY" - "$SCRATCH/$t/src" "$sj" "$MISSING" "$t" <<'CEOF'import dataclasses, json, pathlib, syssrc, mode, missing, tname = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]sys.path.insert(0, src)import openpiassert str(pathlib.Path(openpi.__file__).resolve()).startswith(src), openpi.__file__print("openpi.__file__ =", openpi.__file__)from openpi.training import config as _configcfg = _config.get_config("pi05_cooking_stock")if mode == "MISSING": cfg = dataclasses.replace(cfg, data=dataclasses.replace(cfg.data, split_json=missing))print("split_json =", cfg.data.split_json, "exists =", pathlib.Path(cfg.data.split_json).exists())try: dc = cfg.data.create(cfg.assets_dirs, cfg.model)except Exception as e: print("data.create() RAISED", type(e).__name__, e) print("RESULT: CONSTRUCT_FAILED") sys.exit(0)eps = dc.episodesprint("data.create() OK: episodes =", "None" if eps is None else f"{len(eps)} ids {list(eps)[:4]}...", "| episodes_required_from =", getattr(dc, "episodes_required_from", "<field absent>"), "| norm_stats =", None if dc.norm_stats is None else sorted(dc.norm_stats))print("transforms: data.inputs =", [type(t).__name__ for t in dc.data_transforms.inputs], "| model.inputs =", [type(t).__name__ for t in dc.model_transforms.inputs])if eps is not None and mode == "PRESENT": pathlib.Path(f"/tmp/eps_{tname}.json").write_text(json.dumps(list(map(int, eps))))from openpi.training import data_loader as _dltry: _dl.create_torch_dataset(dc, 10, cfg.model) print("create_torch_dataset:", "returned a dataset (training path intact)" if eps is not None else "DID NOT RAISE -- training would silently use ALL episodes")except FileNotFoundError as e: print("create_torch_dataset: FileNotFoundError ->", str(e)[:200])except Exception as e: print("create_torch_dataset:", type(e).__name__, str(e)[:200])print("RESULT: CONSTRUCT_OK")CEOF donedone
hdr "7b the training episode list must be IDENTICAL pre vs post when the split file is present"if cmp -s /tmp/eps_pre.json /tmp/eps_post.json; then echo "episodes list identical: $(python3 -c "import json;print(len(json.load(open('/tmp/eps_pre.json'))))") ids, md5 $(md5sum /tmp/eps_pre.json | cut -d' ' -f1)"else echo "EPISODES DIFFER -- training semantics changed"; rc_all=1fi
hdr "8 stock pi0.5 BC actions: pre/ (split present) vs post/ (split present) vs post/ (split ABSENT)"INF=$ROOT/scripts/real/patchexport_pi05_infer.py"$PY" "$INF" --src "$SCRATCH/pre/src" --ckpt "$CKPT" --out "$SCRATCH/actions_A_pre_present.npz" --ep "$EP" --frames "$FRAMES"chk $? "infer A (pre, split present)""$PY" "$INF" --src "$SCRATCH/post/src" --ckpt "$CKPT" --out "$SCRATCH/actions_B_post_present.npz" --ep "$EP" --frames "$FRAMES"chk $? "infer B (post, split present)""$PY" "$INF" --src "$SCRATCH/post/src" --ckpt "$CKPT" --out "$SCRATCH/actions_C_post_absent.npz" --ep "$EP" --frames "$FRAMES" --split-json "$MISSING"chk $? "infer C (post, split absent)"
hdr "9 bit-identity""$PY" - "$SCRATCH" <<'CMPEOF'import itertools, pathlib, sysimport numpy as nps = pathlib.Path(sys.argv[1])names = {"A_pre_present": "pre-fix patch, split file present", "B_post_present": "post-fix patch, split file present", "C_post_absent": "post-fix patch, split file ABSENT (deployment case)"}arr = {}for k, d in names.items(): p = s / f"actions_{k}.npz" if not p.exists(): print(f"MISSING {p}"); continue z = np.load(p); arr[k] = z["pred"] print(f"{k:16s} {d:52s} shape={z['pred'].shape} dtype={z['pred'].dtype} idx={z['idx'].tolist()}")ok = Truefor a, b in itertools.combinations(arr, 2): x, y = arr[a], arr[b] if x.shape != y.shape: print(f"{a} vs {b}: SHAPE MISMATCH {x.shape} {y.shape}"); ok = False; continue d = np.abs(x.astype("float64") - y.astype("float64")).max() eq = bool(np.array_equal(x, y)) and x.dtype == y.dtype print(f"{a} vs {b}: max|diff| = {d:.17g} bitwise identical = {eq}") ok = ok and eq and d == 0.0print("VERDICT:", "BIT-IDENTICAL across all compared runs" if ok and len(arr) > 1 else "NOT IDENTICAL / INCOMPLETE")CMPEOF
hdr "done"echo "OVERALL rc=$rc_all"exit $rc_all123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135#!/usr/bin/env python"""rsm_real#5 item 2 acceptance: does the exported robomimic patch reconstruct the IQL critic?
Run INSIDE the environment built by patchexport_item2_validate.sh (upstream robomimic at the pin +rise_on_robomimic.patch, installed editable; no research tree on sys.path).
C1 provenance -- what was imported, and from where C2 the algo registry resolves `idql`, the name the checkpoint carries C3 robomimic's own loader reconstructs the checkpoint C4 the deployment adapter (rise_stack.scorers.build("idql", ...)) returns finite [N] scores for N candidate chunks on a logged observation, and a schema mismatch fails loudly"""import argparse, json, sys, timefrom pathlib import Path
import numpy as np
RESEARCH = "/proj/dmfexp/zwhong/rsm_rise"DATA = f"{RESEARCH}/data/real/rsm_cooking_v5"
def logged_frame_and_chunks(ep=0, n=8, horizon=10, stride=10): import av, pyarrow.parquet as pq tab = pq.read_table(f"{DATA}/data/chunk-000/episode_{ep:06d}.parquet").to_pandas() S = np.stack(tab["observation.state"].values).astype(np.float32) A = np.stack(tab["action"].values).astype(np.float32) idxs = [i for i in range(0, len(tab) - horizon, stride)][:n] cands = np.stack([A[i:i + horizon] for i in idxs]).astype(np.float32) imgs = {} for cam, key in (("global", "observation.images.global"), ("wrist", "observation.images.wrist")): with av.open(f"{DATA}/videos/chunk-000/{key}/episode_{ep:06d}.mp4") as c: st = c.streams.video[0]; st.thread_type = "AUTO" for k, fr in enumerate(c.decode(st)): if k == 0: imgs[cam] = fr.to_ndarray(format="rgb24"); break return imgs, S[0], cands, idxs
def main(): ap = argparse.ArgumentParser() ap.add_argument("--repo", required=True) ap.add_argument("--ckpt", required=True) ap.add_argument("--out", required=True) ap.add_argument("--n", type=int, default=8) args = ap.parse_args() rep = {"argv": sys.argv}
print("=== C1 provenance ===") print("sys.executable =", sys.executable) sys.path.insert(0, args.repo) import torch, robomimic, diffusers import diffusion_policy mods = {} for m in (torch, robomimic, diffusers, diffusion_policy): # diffusion_policy is a NAMESPACE package (no __init__.py anywhere), so __file__ is None origin = getattr(m, "__file__", None) or (list(getattr(m, "__path__", [])) or [None])[0] mods[m.__name__] = {"file": str(Path(origin).resolve()) if origin else "<no origin>", "version": getattr(m, "__version__", None)} import rise_stack mods["rise_stack"] = {"file": str(Path(rise_stack.__file__).resolve()), "version": None} for k, v in mods.items(): print(f" {k:16s} {str(v['version'] or ''):12s} {v['file']}") if v["file"].startswith(RESEARCH + "/code") or "/rsm_rise/env/" in v["file"]: raise SystemExit(f"FATAL: {k} came from the research checkout: {v['file']}") rep["modules"] = mods
print("\n=== C2 the algo registry ===") import robomimic.algo as A print(" registered:", sorted(A.algo_name_to_factory_func.__globals__["REGISTERED_ALGO_FACTORY_FUNCS"]) if "REGISTERED_ALGO_FACTORY_FUNCS" in A.algo_name_to_factory_func.__globals__ else "<registry private>") f = A.algo_name_to_factory_func("idql") print(" algo_name_to_factory_func('idql') ->", f) rep["C2"] = {"factory": str(f)}
print("\n=== C3 robomimic's own loader ===") import robomimic.utils.file_utils as FileUtils t0 = time.time() policy, ckpt_dict = FileUtils.policy_from_checkpoint(ckpt_path=args.ckpt, device=torch.device("cpu"), verbose=False) algo = policy.policy print(f" loaded in {time.time()-t0:.1f}s: {type(algo).__module__}.{type(algo).__name__}") print(" obs_shapes =", dict(algo.obs_shapes)) print(" ac_dim =", algo.ac_dim, " nets =", sorted(algo.nets.keys())) n_par = sum(p.numel() for p in algo.nets.parameters()) print(f" parameters = {n_par:,}") rep["C3"] = {"class": f"{type(algo).__module__}.{type(algo).__name__}", "obs_shapes": {k: list(v) for k, v in algo.obs_shapes.items()}, "ac_dim": int(algo.ac_dim), "nets": sorted(algo.nets.keys()), "parameters": int(n_par)}
print("\n=== C4 through the deployment adapter ===") from rise_stack.config import ActionNorm from rise_stack.scorers import build from rise_stack import obs as obs_mod an = ActionNorm.load(str(Path(args.repo) / "rise_stack/configs/action_norm.json")) scorer = build("idql", an, {"idql_ckpt": args.ckpt}, device="cpu") print(" scorer:", type(scorer).__name__, "keys:", scorer.keys) imgs, state, cands, idxs = logged_frame_and_chunks(n=args.n) obs = obs_mod.make_obs(imgs, state, an.gripper_thresh, t=0) print(f" observation: logged episode 0 frame 0; candidates = {cands.shape} from logged chunks at {idxs}") t0 = time.time() choice, scores = scorer.pick(cands, obs) dt = time.time() - t0 scores = np.asarray(scores) print(f" scores shape={scores.shape} dtype={scores.dtype} finite={bool(np.isfinite(scores).all())} " f"in {dt*1000:.0f} ms (CPU)") print(" scores =", np.array2string(scores, precision=6)) print(" argmax =", choice, " min/max =", float(scores.min()), float(scores.max()), " std =", float(scores.std())) ok = scores.shape == (args.n,) and bool(np.isfinite(scores).all()) rep["C4"] = {"shape": list(scores.shape), "finite": bool(np.isfinite(scores).all()), "scores": scores.tolist(), "argmax": int(choice), "latency_s": dt, "vf_quantile": getattr(scorer, "vf_quantile", None)}
print("\n permuted control (the same critic, candidates shuffled):") pc = build("permuted:idql", an, {"idql_ckpt": args.ckpt}, device="cpu") ch2, sc2 = pc.pick(cands, obs) print(" ", np.array2string(np.asarray(sc2), precision=6), "argmax", ch2)
print("\n a schema mismatch must fail loudly, not score silently:") try: scorer.pick(cands[:, :, :5], obs) print(" NO ERROR -- that is a defect") ok = False except Exception as e: print(f" {type(e).__name__}: {str(e)[:160]}")
rep["ok"] = ok Path(args.out).write_text(json.dumps(rep, indent=1, default=str)) print("\nC4 VERDICT:", "PASS -- finite [N] scores through the deployment adapter" if ok else "FAIL") print("wrote", args.out) sys.exit(0 if ok else 1)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165#!/usr/bin/env bash# rsm_real#5 item 2: export code/rise_robomimic as a PATCH against upstream# ARISE-Initiative/robomimic@40e427a (v0.3.0) -- the probe (LSF 1886202) showed the fork is that# revision plus 42 touched .py files with zero upstream files missing.# Overlays only SOURCE files, reports everything it deliberately did not overlay, and verifies the# patch reapplies to a pristine clone.set -uo pipefailROOT=/proj/dmfexp/zwhong/rsm_riseFORK=$ROOT/code/rise_robomimicSCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run4}PIN=${PIN:-40e427a695a9f085d3fc0f70ffb0d687a10802c8}hdr(){ echo; echo "=================== $* ==================="; date -u; }rc_all=0chk(){ if [ "$1" -ne 0 ]; then echo "STEP FAILED rc=$1: $2"; rc_all=1; fi; }mkdir -p "${SCRATCH:?}" || exit 1
hdr "0 context"echo "host=$(hostname) job=${LSB_JOBID:-none} fork=$FORK pin=$PIN scratch=$SCRATCH"echo "fork version: $(grep -m1 __version__ "$FORK/robomimic/__init__.py")"
hdr "1 two pristine upstream clones at the pin"for t in post verify; do rm -rf "${SCRATCH:?}/${t:?}" git clone --quiet https://github.com/ARISE-Initiative/robomimic.git "${SCRATCH:?}/${t:?}" || exit 1 git -C "$SCRATCH/$t" checkout --quiet "$PIN" || exit 1 echo "$t: HEAD=$(git -C "$SCRATCH/$t" rev-parse HEAD) clean=[$(git -C "$SCRATCH/$t" status --porcelain | head -2)]"done
hdr "2 overlay the fork's SOURCE files onto post/"python3 - "$FORK" "$SCRATCH/post" <<'OVEOF'import filecmp, os, shutil, sysfrom pathlib import Pathfork, dst = Path(sys.argv[1]), Path(sys.argv[2])SKIP_DIR = {"__pycache__", ".git", "robomimic.egg-info", "docs", ".ipynb_checkpoints"}INCLUDE_TOP = {"robomimic", "tests", "examples"} # source trees we carryEXTRA_FILES = {"setup.py", "requirements.txt", "MANIFEST.in"}
def wanted(rel: Path) -> bool: if ".bak." in rel.name or rel.suffix == ".pyc": return False if rel.suffix != ".py": return False return rel.parts[0] in INCLUDE_TOP
copied, skipped_nonsource = [], []for dirpath, dirnames, filenames in os.walk(fork): dirnames[:] = [d for d in dirnames if d not in SKIP_DIR] for fn in filenames: src = Path(dirpath) / fn rel = src.relative_to(fork) if rel.parts[0] in SKIP_DIR: continue if wanted(rel): tgt = dst / rel tgt.parent.mkdir(parents=True, exist_ok=True) if not tgt.exists() or not filecmp.cmp(src, tgt, shallow=False): shutil.copy2(src, tgt) copied.append(str(rel)) elif ".bak." not in rel.name and rel.suffix not in (".pyc",): skipped_nonsource.append(str(rel))
for fn in sorted(EXTRA_FILES): src, tgt = fork / fn, dst / fn if src.is_file() and tgt.is_file() and not filecmp.cmp(src, tgt, shallow=False): shutil.copy2(src, tgt) copied.append(fn + " (packaging file, differs from upstream)") elif src.is_file() and not tgt.is_file(): shutil.copy2(src, tgt) copied.append(fn + " (packaging file, new)")
print(f"overlaid {len(copied)} source files that differ from upstream:")for c in sorted(copied): print(" ", c)print(f"\nNOT overlaid, {len(skipped_nonsource)} non-.py files under the carried trees (data, notebooks," " shell scripts, licences). Listed so nothing is silently dropped:")for s in sorted(skipped_nonsource)[:60]: print(" ", s)if len(skipped_nonsource) > 60: print(f" … and {len(skipped_nonsource) - 60} more")# upstream files the fork does not have at allmissing = []for dirpath, dirnames, filenames in os.walk(dst): dirnames[:] = [d for d in dirnames if d not in SKIP_DIR] for fn in filenames: rel = (Path(dirpath) / fn).relative_to(dst) if rel.suffix == ".py" and rel.parts[0] in INCLUDE_TOP and not (fork / rel).is_file(): missing.append(str(rel))print(f"\nupstream .py files absent from the fork ({len(missing)}): {missing}")OVEOFchk $? "overlay"
hdr "3 generate the patches (package and research tests, separately)"# upstream .gitignore lists macros_private.py, so a plain `git add -A` silently drops it -- the same# class of bug that lost cooking_policy.py from the openpi export. Force-add every overlaid file that# git considers ignored.( cd "$SCRATCH/post" && git add -A \ && ignored=$(git status --porcelain --ignored=matching | awk '$1=="!!"{print $2}') \ && if [ -n "$ignored" ]; then echo "force-adding gitignored source files: $ignored"; \ for f in $ignored; do case "$f" in *__pycache__*|*.pyc) ;; *) git add -f "$f";; esac; done; fi \ && echo "--- still untracked/ignored after force-add (must contain no source file) ---" \ && git status --porcelain --ignored=matching | head -10 )chk $? "stage"( cd "$SCRATCH/post" \ && git diff --cached -- robomimic > "$SCRATCH/rise_on_robomimic.patch" \ && git diff --cached -- tests examples > "$SCRATCH/rise_on_robomimic_tests.patch" \ && echo "--- package patch ---" && git diff --cached --stat -- robomimic | tail -46 \ && echo "--- research-tests patch ---" && git diff --cached --stat -- tests examples | tail -12 \ && echo "--- anything staged OUTSIDE those two (must be empty) ---" \ && git diff --cached --stat -- . ':(exclude)robomimic' ':(exclude)tests' ':(exclude)examples' )chk $? "generate"for f in rise_on_robomimic.patch rise_on_robomimic_tests.patch; do wc -l "$SCRATCH/$f"; md5sum "$SCRATCH/$f"; echo " files: $(grep -c '^+++ ' "$SCRATCH/$f")"done
hdr "4 both patches reapply to a pristine clone and reproduce post/ exactly"( cd "$SCRATCH/verify" \ && git apply --check "$SCRATCH/rise_on_robomimic.patch" && echo "package: git apply --check OK" \ && git apply "$SCRATCH/rise_on_robomimic.patch" && echo "package: git apply OK" \ && git apply --check "$SCRATCH/rise_on_robomimic_tests.patch" && echo "tests: git apply --check OK" \ && git apply "$SCRATCH/rise_on_robomimic_tests.patch" && echo "tests: git apply OK" )chk $? "reapply"diff -r -q --exclude=.git --exclude=__pycache__ "$SCRATCH/post" "$SCRATCH/verify" && echo "post/ == verify/"chk $? "post == verify"
hdr "4b the patched tree is the fork, file for file, for every source file we carried"python3 - "$FORK" "$SCRATCH/verify" <<'CMPEOF'import filecmp, os, sysfrom pathlib import Pathfork, got = Path(sys.argv[1]), Path(sys.argv[2])SKIP_DIR = {"__pycache__", ".git", "robomimic.egg-info", "docs", ".ipynb_checkpoints"}bad = []n = 0for dirpath, dirnames, filenames in os.walk(fork): dirnames[:] = [d for d in dirnames if d not in SKIP_DIR] for fn in filenames: rel = (Path(dirpath) / fn).relative_to(fork) if rel.suffix != ".py" or ".bak." in rel.name or rel.parts[0] not in {"robomimic", "tests", "examples"}: continue n += 1 tgt = got / rel if not tgt.is_file(): bad.append(("MISSING", str(rel))) elif not filecmp.cmp(fork / rel, tgt, shallow=False): bad.append(("DIFFERS", str(rel)))print(f"compared {n} source files from the fork against the patched clone")for kind, rel in bad: print(" ", kind, rel)print("VERDICT:", "the patch reconstructs every carried source file byte for byte" if not bad else f"{len(bad)} FILES NOT RECONSTRUCTED")sys.exit(1 if bad else 0)CMPEOFchk $? "patch reconstructs the fork"
hdr "5 does the patch leak anything it should not?"echo "--- absolute cluster paths ---"grep -n "^+.*\(/proj/dmfexp\|/u/zwhong\|/gpfs\)" "$SCRATCH/rise_on_robomimic.patch" | head -40echo "(count: $(grep -c "^+.*\(/proj/dmfexp\|/u/zwhong\|/gpfs\)" "$SCRATCH/rise_on_robomimic.patch"))"echo "--- credentials / keys ---"grep -n -i "^+.*\(api_key\|apikey\|secret\|token\s*=\|password\|wandb_api\|gho_\|hf_[A-Za-z0-9]\{20\}\)" \ "$SCRATCH/rise_on_robomimic.patch" | head -20echo "(count: $(grep -c -i "^+.*\(api_key\|apikey\|secret\|token\s*=\|password\|wandb_api\)" "$SCRATCH/rise_on_robomimic.patch"))"
hdr "done"echo "OVERALL rc=$rc_all"exit $rc_all123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175#!/usr/bin/env python"""rsm_real#5 item 2 probe: what does rise_actor_rsm_real_s0_e3000.pth actually need?
Three questions, answered with measurements rather than by copying a 104-file fork: A. the checkpoint's own metadata -- algo name, config, obs modalities, state-dict module names; B. the static import closure of the registered algo module inside the fork; C. how far the fork has drifted from upstream ARISE-Initiative/robomimic at a candidate ref, so we can decide between a patch (option b) and vendoring the closure (option a)."""import argparse, ast, hashlib, json, os, sysfrom pathlib import Path
SKIP_DIR = {"__pycache__", ".git", "robomimic.egg-info", "docs"}
def is_source(p: Path) -> bool: return p.suffix == ".py" and ".bak." not in p.name
def md5(p: Path) -> str: return hashlib.md5(p.read_bytes()).hexdigest()
def walk_py(root: Path): for dirpath, dirnames, filenames in os.walk(root): dirnames[:] = [d for d in dirnames if d not in SKIP_DIR] for fn in filenames: p = Path(dirpath) / fn if is_source(p): yield p.relative_to(root)
def module_to_file(fork: Path, mod: str): parts = mod.split(".") cand = [fork.joinpath(*parts).with_suffix(".py"), fork.joinpath(*parts, "__init__.py")] for c in cand: if c.is_file(): return c return None
def closure(fork: Path, start: Path, pkg="robomimic"): """Follow robomimic.* imports from `start`; report external imports separately.""" seen, external, queue = {}, {}, [start] while queue: f = queue.pop() rel = str(f.relative_to(fork)) if rel in seen: continue try: tree = ast.parse(f.read_text()) except SyntaxError as e: seen[rel] = {"lines": -1, "error": str(e)} continue seen[rel] = {"lines": len(f.read_text().splitlines())} mods = [] for node in ast.walk(tree): if isinstance(node, ast.Import): mods += [a.name for a in node.names] elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module: mods.append(node.module) elif isinstance(node, ast.ImportFrom) and node.level: base = f.relative_to(fork).parent for _ in range(node.level - 1): base = base.parent mods.append(str(base).replace("/", ".") + ("." + node.module if node.module else "")) for m in sorted(set(mods)): if m.split(".")[0] == pkg: tgt = module_to_file(fork, m) if tgt is not None: queue.append(tgt) else: external.setdefault(m, "unresolved inside the fork") else: external.setdefault(m, None) return seen, external
def main(): ap = argparse.ArgumentParser() ap.add_argument("--ckpt", required=True) ap.add_argument("--fork", required=True) ap.add_argument("--upstream", default=None, help="a checkout of upstream robomimic to compare against") ap.add_argument("--out", required=True) args = ap.parse_args() fork = Path(args.fork) rep = {"ckpt": args.ckpt, "fork": str(fork)}
print("=== A. checkpoint metadata ===") import torch blob = torch.load(args.ckpt, map_location="cpu", weights_only=False) print("top-level keys:", sorted(blob) if isinstance(blob, dict) else type(blob)) rep["ckpt_keys"] = sorted(blob) if isinstance(blob, dict) else str(type(blob)) algo_name = blob.get("algo_name") print("algo_name =", algo_name) rep["algo_name"] = algo_name cfg = blob.get("config") if isinstance(cfg, str): cfg = json.loads(cfg) if isinstance(cfg, dict): rep["config_algo_name"] = cfg.get("algo_name") print("config.algo_name =", cfg.get("algo_name")) print("config.experiment.name =", cfg.get("experiment", {}).get("name")) print("config.observation.modalities =", json.dumps(cfg.get("observation", {}).get("modalities"), indent=1)) enc = cfg.get("observation", {}).get("encoder") print("config.observation.encoder =", json.dumps(enc, indent=1)[:1500]) print("config.algo keys =", sorted((cfg.get("algo") or {}).keys())) rep["config_algo"] = cfg.get("algo") rep["config_observation"] = cfg.get("observation") rep["config_train_data"] = (cfg.get("train") or {}).get("data") Path(args.out + ".config.json").write_text(json.dumps(cfg, indent=1)) print("full config written to", args.out + ".config.json") sm = blob.get("shape_metadata") print("shape_metadata =", json.dumps(sm, indent=1)[:1200] if sm else None) rep["shape_metadata"] = sm model = blob.get("model") if isinstance(model, dict): tops = sorted({k.split(".")[0] for k in model}) print("state-dict top-level modules:", tops) print("n tensors:", len(model), "n params:", sum(int(v.numel()) for v in model.values() if hasattr(v, "numel"))) rep["state_dict_top"] = tops rep["state_dict_n_tensors"] = len(model) rep["state_dict_n_params"] = sum(int(v.numel()) for v in model.values() if hasattr(v, "numel")) nested = sorted({".".join(k.split(".")[:3]) for k in model})[:40] print("first 40 module prefixes:", json.dumps(nested, indent=1)) print("obs_normalization_stats:", None if blob.get("obs_normalization_stats") is None else sorted(blob["obs_normalization_stats"]))
print("\n=== B. static import closure of the registered algo module ===") cands = [f"robomimic/algo/{algo_name}.py"] if algo_name else [] cands += ["robomimic/algo/iql_diffusion.py", "robomimic/algo/idql.py"] rep["closures"] = {} for c in dict.fromkeys(cands): start = fork / c if not start.is_file(): print(f"{c}: NOT PRESENT in the fork") continue seen, external = closure(fork, start) tot = sum(v["lines"] for v in seen.values() if v["lines"] > 0) print(f"\n{c}: {len(seen)} fork files, {tot} lines") for k in sorted(seen): print(f" {seen[k]['lines']:6d} {k}") ext = sorted(e for e in external if e.split('.')[0] not in ("robomimic",)) print(f" external imports ({len(ext)}): {', '.join(ext)}") unres = sorted(k for k, v in external.items() if v) if unres: print(" UNRESOLVED robomimic imports:", unres) rep["closures"][c] = {"files": seen, "lines": tot, "external": ext, "unresolved": unres}
print("\n=== C. drift from upstream ===") if args.upstream: up = Path(args.upstream) fr = fork fset = {p for p in walk_py(fr / "robomimic")} uset = {p for p in walk_py(up / "robomimic")} same = sorted(p for p in fset & uset if md5(fr / "robomimic" / p) == md5(up / "robomimic" / p)) diff = sorted(p for p in fset & uset if md5(fr / "robomimic" / p) != md5(up / "robomimic" / p)) only_f = sorted(fset - uset) only_u = sorted(uset - fset) print(f"upstream {up}: identical={len(same)} modified={len(diff)} fork-only={len(only_f)} " f"upstream-only={len(only_u)}") print("modified:"); [print(" ", p) for p in diff] print("fork-only:"); [print(" ", p) for p in only_f] rep["drift"] = {"upstream": str(up), "identical": len(same), "modified": [str(p) for p in diff], "fork_only": [str(p) for p in only_f], "upstream_only": [str(p) for p in only_u]} else: print("no --upstream given")
Path(args.out).write_text(json.dumps(rep, indent=1, default=str)) print("\nwrote", args.out)
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940414243#!/usr/bin/env bash# rsm_real#5 item 2: probe what the IQL actor checkpoint needs, and how far code/rise_robomimic has# drifted from upstream ARISE-Initiative/robomimic -- the input to "patch (option b) vs vendor (option a)".set -uo pipefailROOT=/proj/dmfexp/zwhong/rsm_riseSCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run3}CKPT=${CKPT:-$ROOT/hf_ckpt_root/rise_actor_rsm_real_s0_e3000.pth}source $ROOT/scripts/env.shexport PYTHONUNBUFFERED=1hdr(){ echo; echo "=================== $* ==================="; date -u; }mkdir -p "${SCRATCH:?}" || exit 1
hdr "0 context"echo "host=$(hostname) job=${LSB_JOBID:-none} python=$(which python) ckpt=$CKPT"python -c "import torch;print('torch',torch.__version__)"
hdr "1 upstream robomimic clones (the fork says __version__ = $(grep -m1 __version__ $ROOT/code/rise_robomimic/robomimic/__init__.py))"rm -rf "${SCRATCH:?}/robomimic_upstream"git clone --quiet https://github.com/ARISE-Initiative/robomimic.git "${SCRATCH:?}/robomimic_upstream" \ && echo "cloned upstream robomimic" || { echo "CLONE FAILED (no network?)"; }if [ -d "$SCRATCH/robomimic_upstream/.git" ]; then git -C "$SCRATCH/robomimic_upstream" tag | tail -8 for ref in v0.3.1 v0.3.0 master; do if git -C "$SCRATCH/robomimic_upstream" rev-parse -q --verify "$ref" >/dev/null \ || git -C "$SCRATCH/robomimic_upstream" rev-parse -q --verify "origin/$ref" >/dev/null; then git -C "$SCRATCH/robomimic_upstream" checkout --quiet "$ref" 2>/dev/null \ || git -C "$SCRATCH/robomimic_upstream" checkout --quiet "origin/$ref" echo "--- candidate $ref = $(git -C "$SCRATCH/robomimic_upstream" rev-parse HEAD) ---" python "$ROOT/scripts/real/patchexport_item2_probe.py" --ckpt "$CKPT" \ --fork "$ROOT/code/rise_robomimic" --upstream "$SCRATCH/robomimic_upstream" \ --out "$SCRATCH/item2_probe_${ref}.json" 2>&1 | sed -n '/=== C. drift/,$p' else echo "ref $ref not found" fi donefi
hdr "2 the full probe (checkpoint metadata + import closure), upstream = the last checkout"python "$ROOT/scripts/real/patchexport_item2_probe.py" --ckpt "$CKPT" \ --fork "$ROOT/code/rise_robomimic" --upstream "$SCRATCH/robomimic_upstream" \ --out "$SCRATCH/item2_probe.json"
hdr "done"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596#!/usr/bin/env bash# rsm_real#5 item 2: build the IQL inference environment from the exported patch alone and check that# rise_actor_rsm_real_s0_e3000.pth reconstructs and scores. Fresh venv, research tree off sys.path.set -uo pipefailROOT=/proj/dmfexp/zwhong/rsm_riseSCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run5}PATCH=${PATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run4/rise_on_robomimic.patch}SRC=${SRC:-/proj/dmfexp/zwhong/scratch_patchexport/wt_main} # the rsm_real branch (for rise_stack)PIN=${PIN:-40e427a695a9f085d3fc0f70ffb0d687a10802c8}DP_PIN=${DP_PIN:-078ce1e}CKPT=${CKPT:-$ROOT/hf_ckpt_root/rise_actor_rsm_real_s0_e3000.pth}UV=${UV:-/u/zwhong/.local/bin/uv}unset RISE_ROOT RSM_LIBERO_DIR PYTHONPATH HF_TOKEN HF_HUB_OFFLINEexport PYTHONNOUSERSITE=1 PYTHONUNBUFFERED=1 UV_CACHE_DIR=$SCRATCH/uv_cache HF_HOME=$SCRATCH/hf_homeexport TORCH_HOME=$SCRATCH/torch_home MPLCONFIGDIR=$SCRATCH/mplhdr(){ echo; echo "=================== $* ==================="; date -u; }rc_all=0chk(){ if [ "$1" -ne 0 ]; then echo "STEP FAILED rc=$1: $2"; rc_all=1; fi; }mkdir -p "${SCRATCH:?}" || exit 1
hdr "0 context"echo "host=$(hostname) job=${LSB_JOBID:-none} patch=$PATCH ckpt=$CKPT"md5sum "$PATCH"
hdr "1 upstream robomimic at the pin + the exported patch"rm -rf "${SCRATCH:?}/robomimic"git clone --quiet https://github.com/ARISE-Initiative/robomimic.git "${SCRATCH:?}/robomimic" || exit 1git -C "$SCRATCH/robomimic" checkout --quiet "$PIN" || exit 1( cd "$SCRATCH/robomimic" && git apply "$PATCH" && echo "git apply: OK" && git status --porcelain | wc -l )chk $? "apply robomimic patch"
hdr "2 the repo under test"rm -rf "${SCRATCH:?}/rsm_real"git clone --quiet "$SRC" "${SCRATCH:?}/rsm_real" || exit 1REPO=$SCRATCH/rsm_realecho "rsm_real HEAD: $(git -C "$REPO" rev-parse --short HEAD) $(git -C "$REPO" log -1 --pretty=%s)"
hdr "3 a fresh venv, pinned to what the checkpoint was TRAINED with"# the training environment (rsm_rise/env, python 3.10) holds: torch 2.5.1+cu124, torchvision 0.20.1,# numpy 1.26.4, diffusers 0.32.2, opencv-python 4.11.0.86, h5py 3.16.0, egl_probe 1.0.2, robomimic# 0.3.0 (editable, this fork) and diffusion_policy 0.0.0 (editable, pin 078ce1e).rm -rf "${SCRATCH:?}/venv""$UV" venv --python 3.10 "${SCRATCH:?}/venv" 2>&1 | tail -2PY=$SCRATCH/venv/bin/pythonUVP="$UV pip install --python $PY"$UVP torch==2.5.1 torchvision==0.20.1 2>&1 | tail -1chk $? "torch"$UVP -e "$SCRATCH/robomimic" 2>&1 | tail -3chk $? "robomimic (editable, from the patched clone)"$UVP diffusers==0.32.2 2>&1 | tail -1chk $? "diffusers"# diffusion_policy has NO __init__.py anywhere, so its setup.py's find_packages() finds nothing and a# non-editable `pip install git+...` installs ZERO modules while reporting success. It must go in# editable (that is also how the training environment has it).rm -rf "${SCRATCH:?}/diffusion_policy"git clone --quiet https://github.com/UWRobotLearning/diffusion_policy.git "${SCRATCH:?}/diffusion_policy" \ && git -C "$SCRATCH/diffusion_policy" checkout --quiet "$DP_PIN" \ && echo "diffusion_policy HEAD: $(git -C "$SCRATCH/diffusion_policy" rev-parse HEAD)"# Measured: `pip install git+…` AND `pip install -e` both report success and install ZERO modules,# because setup.py uses find_packages() and the tree has no __init__.py anywhere (it is a namespace# package). The working install is the clone on PYTHONPATH -- which is what the training environment# effectively has (a legacy `setup.py develop` .pth pointing at the project root).$UVP -e "$SCRATCH/diffusion_policy" 2>&1 | tail -2"$PY" -c "import diffusion_policy" 2>/dev/null \ && echo "diffusion_policy: the editable install exposes it" \ || { echo "diffusion_policy: the editable install exposes NOTHING -- using the clone on PYTHONPATH"; \ export PYTHONPATH="$SCRATCH/diffusion_policy${PYTHONPATH:+:$PYTHONPATH}"; }echo "PYTHONPATH=${PYTHONPATH:-<unset>}"$UVP opencv-python==4.11.0.86 h5py==3.16.0 pyarrow pandas av 2>&1 | tail -1chk $? "extras"# anything above may have pulled numpy 2; the fork was trained on 1.26.4, so pin it LAST and check$UVP "numpy==1.26.4" 2>&1 | tail -1"$PY" -c "import numpy, sysprint('numpy', numpy.__version__)sys.exit(0 if numpy.__version__.startswith('1.') else 1)"chk $? "numpy stayed on 1.x"echo '--- the import that a non-editable install silently loses ---'"$PY" -c "from diffusion_policy.model.diffusion.mask_generator import LowdimMaskGeneratorimport diffusion_policy.model.diffusion.mask_generator as mprint('LowdimMaskGenerator from', m.__file__)"chk $? "diffusion_policy import""$UV" pip freeze --python "$PY" > "$SCRATCH/pip_freeze.txt"; wc -l "$SCRATCH/pip_freeze.txt"grep -E "^(torch|torchvision|numpy|diffusers|robomimic|diffusion.policy|opencv|h5py|egl|tqdm|termcolor|tensorboard)" "$SCRATCH/pip_freeze.txt"
hdr "4 C1-C4""$PY" "$ROOT/scripts/real/patchexport_item2_checks.py" --repo "$REPO" --ckpt "$CKPT" \ --out "$SCRATCH/item2_checks.json"chk $? "item2 checks"
hdr "done"echo "OVERALL rc=$rc_all"exit $rc_all12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091#!/usr/bin/env python"""rsm_real#5 item 3: make robomimic/algo/rsm_scorer.py find rsm_libero without a hardcoded path.
Applied to a CLONE of the robomimic fork (upstream pin + rise_on_robomimic.patch) before the patch isregenerated, and before the validation run. Idempotent: it asserts the exact pre-image and is a no-opif the fix is already in place.
Resolution order after the fix, so nothing that works today stops working: 1. $RSM_LIBERO_DIR -- explicit override (the research tree keeps using it) 2. the installed `rsm_libero` package -- its __init__ appends its own directory to sys.path, so the unqualified `import model` inside those modules, and the module paths torch.save recorded at training time, resolve exactly as they did in training 3. the legacy absolute training path, only if it exists on this machine"""import sysfrom pathlib import Path
OLD_CONST = '''RSM_LIBERO_DIR = os.environ.get( "RSM_LIBERO_DIR", "/proj/dmfexp/zwhong/rsm_rise/code/gen_q/rsm_libero")'''
NEW_CONST = '''# rsm_real#5 item 3: no hardcoded training path. The override comes first, then the installed# `rsm_libero` package (gen_q pin, see rise_stack/rsm_libero/UPSTREAM_COMMIT.txt), then -- only if it# still exists on this machine -- the legacy training location, so research checkouts are unaffected.RSM_LIBERO_DIR = os.environ.get("RSM_LIBERO_DIR", "")RSM_LIBERO_LEGACY_DIR = "/proj/dmfexp/zwhong/rsm_rise/code/gen_q/rsm_libero"'''
OLD_FN = '''def _rsm_modules(): """Import rsm_libero's model / train_rsm / is_ope lazily (they are plain top-level modules).""" if RSM_LIBERO_DIR not in sys.path: sys.path.insert(0, RSM_LIBERO_DIR) model = importlib.import_module("model") train_rsm = importlib.import_module("train_rsm") is_ope = importlib.import_module("is_ope") return model, train_rsm, is_ope'''
NEW_FN = '''def _rsm_libero_dir(): """Where rsm_libero's top-level modules live, without assuming a cluster path.
$RSM_LIBERO_DIR wins if it is set. Otherwise the installed `rsm_libero` package is imported for its side effect: its __init__ appends its own directory to sys.path, which is what makes the unqualified `import model` inside model/train_rsm/is_ope -- and the module paths recorded in the training checkpoints -- resolve. The legacy training path is tried last and only if it exists. """ if RSM_LIBERO_DIR: return RSM_LIBERO_DIR try: pkg = importlib.import_module("rsm_libero") return os.path.dirname(os.path.abspath(pkg.__file__)) except ImportError: pass if os.path.isdir(RSM_LIBERO_LEGACY_DIR): return RSM_LIBERO_LEGACY_DIR raise ImportError( "rsm_libero is not available: install the pinned gen_q source (pip install -e <gen_q clone>, " "see rise_stack/rsm_libero/README.md) or set RSM_LIBERO_DIR to a checkout holding model.py, " "train_rsm.py and is_ope.py")
def _rsm_modules(): """Import rsm_libero's model / train_rsm / is_ope lazily (they are plain top-level modules).""" d = _rsm_libero_dir() if d not in sys.path: sys.path.insert(0, d) model = importlib.import_module("model") train_rsm = importlib.import_module("train_rsm") is_ope = importlib.import_module("is_ope") return model, train_rsm, is_ope'''
def main(): path = Path(sys.argv[1]) src = path.read_text() if "_rsm_libero_dir" in src: print(f"already fixed: {path}") return 0 for old in (OLD_CONST, OLD_FN): if old not in src: print(f"FATAL: pre-image not found in {path}:\n{old}") return 2 src = src.replace(OLD_CONST, NEW_CONST).replace(OLD_FN, NEW_FN) path.write_text(src) print(f"patched {path}: RSM_LIBERO_DIR default removed, _rsm_libero_dir() added") return 0
if __name__ == "__main__": sys.exit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157#!/usr/bin/env python"""rsm_real#5 item 3 acceptance: does the RSM scorer load and score from PINNED SOURCES ONLY?
Run INSIDE the environment built by patchexport_item3_validate.sh: robomimic = upstream v0.3.0 + rise_on_robomimic.patch (with the item-3 import fix), editable rsm_libero = gen_q at the pin + rise_on_rsm_libero.patch, editable (NO RSM_LIBERO_DIR) dinov2 = the pinned upstream clone, used as torch.hub's local source
D1 provenance -- what was imported and from where; nothing may come from the research checkout D2 rsm_scorer finds rsm_libero with RSM_LIBERO_DIR unset, via the installed package D3 real/deployment/models.py reports no missing rsm source D4 the real successor + hop head + feature statistics load and return finite [N] scores for N candidate chunks through rise_stack.scorers.build("rsm", ...) D5 the permuted control, and a schema mismatch that must fail loudly"""import argparse, json, os, sys, timefrom pathlib import Path
import numpy as np
RESEARCH = "/proj/dmfexp/zwhong/rsm_rise"DATA = f"{RESEARCH}/data/real/rsm_cooking_v5"
def logged_frame_and_chunks(ep=0, n=8, horizon=10, stride=10): """A logged observation and N logged action chunks -- the same fixture item 2 used.""" import av, pyarrow.parquet as pq tab = pq.read_table(f"{DATA}/data/chunk-000/episode_{ep:06d}.parquet").to_pandas() S = np.stack(tab["observation.state"].values).astype(np.float32) A = np.stack(tab["action"].values).astype(np.float32) idxs = [i for i in range(0, len(tab) - horizon, stride)][:n] cands = np.stack([A[i:i + horizon] for i in idxs]).astype(np.float32) imgs = {} for cam, key in (("global", "observation.images.global"), ("wrist", "observation.images.wrist")): with av.open(f"{DATA}/videos/chunk-000/{key}/episode_{ep:06d}.mp4") as c: st = c.streams.video[0]; st.thread_type = "AUTO" for k, fr in enumerate(c.decode(st)): if k == 0: imgs[cam] = fr.to_ndarray(format="rgb24"); break return imgs, S[0], cands, idxs
def main(): ap = argparse.ArgumentParser() ap.add_argument("--repo", required=True) ap.add_argument("--rsm-ckpt", required=True) ap.add_argument("--hop-ckpt", required=True) ap.add_argument("--feat-stats", required=True) ap.add_argument("--dino-hub", required=True) ap.add_argument("--dino-ckpt", required=True) ap.add_argument("--out", required=True) ap.add_argument("--n", type=int, default=8) ap.add_argument("--particles", type=int, default=16) args = ap.parse_args() rep = {"argv": sys.argv} ok = True
print("=== D1 provenance ===") print("sys.executable =", sys.executable) print("RSM_LIBERO_DIR =", repr(os.environ.get("RSM_LIBERO_DIR"))) print("PYTHONPATH =", repr(os.environ.get("PYTHONPATH"))) sys.path.insert(0, args.repo) import torch, robomimic, rsm_libero, rise_stack mods = {} for m in (torch, robomimic, rsm_libero, rise_stack): origin = getattr(m, "__file__", None) or (list(getattr(m, "__path__", [])) or [None])[0] mods[m.__name__] = {"file": str(Path(origin).resolve()) if origin else "<no origin>", "version": getattr(m, "__version__", None)} for k, v in mods.items(): print(f" {k:12s} {str(v['version'] or ''):10s} {v['file']}") if v["file"].startswith(RESEARCH + "/code") or "/rsm_rise/env/" in v["file"]: raise SystemExit(f"FATAL: {k} came from the research checkout: {v['file']}") rep["modules"] = mods
print("\n=== D2 rsm_scorer resolves rsm_libero with RSM_LIBERO_DIR unset ===") if os.environ.get("RSM_LIBERO_DIR"): raise SystemExit("FATAL: RSM_LIBERO_DIR is set; this check is meaningless") import robomimic.algo.rsm_scorer as RS print(" robomimic.algo.rsm_scorer:", RS.__file__) d = RS._rsm_libero_dir() print(" _rsm_libero_dir() ->", d) model, train_rsm, is_ope = RS._rsm_modules() for m in (model, train_rsm, is_ope): print(f" {m.__name__:10s} {m.__file__}") if not str(Path(m.__file__).resolve()).startswith(str(Path(d).resolve())): raise SystemExit(f"FATAL: {m.__name__} did not come from the installed rsm_libero") rep["D2"] = {"dir": d, "modules": {m.__name__: m.__file__ for m in (model, train_rsm, is_ope)}}
print("\n=== D3 real/deployment/models.py dependency report ===") sys.path.insert(0, args.repo) from real.deployment import models as dep_models report = dep_models.dependency_report("openpi", "rsm") print(" missing:", report["missing"] or "(nothing)") rsm_missing = [m for m in report["missing"] if "rsm" in m.lower()] print(" rsm-related entries:", rsm_missing or "(none)") ok = ok and not rsm_missing rep["D3"] = {"missing": report["missing"], "rsm_missing": rsm_missing}
print("\n=== D4 the real scorer through the deployment adapter ===") from rise_stack.config import ActionNorm from rise_stack.scorers import build from rise_stack import obs as obs_mod an = ActionNorm.load(str(Path(args.repo) / "rise_stack/configs/action_norm.json")) t0 = time.time() scorer = build("rsm", an, {"rsm_ckpt": args.rsm_ckpt, "rsm_hop_ckpt": args.hop_ckpt, "rsm_feat_stats": args.feat_stats, "rsm_particles": args.particles, "dino_hub_dir": args.dino_hub, "dino_checkpoint": args.dino_ckpt}, device="cpu") build_s = time.time() - t0 print(f" built in {build_s:.1f}s; dino hub={scorer.feat.hub_dir} weights={scorer.feat.checkpoint}") imgs, state, cands, idxs = logged_frame_and_chunks(n=args.n) obs = obs_mod.make_obs(imgs, state, an.gripper_thresh, t=0) print(f" observation: logged episode 0 frame 0; candidates {cands.shape} from chunks at {idxs}") t0 = time.time() choice, scores = scorer.pick(cands, obs) dt = time.time() - t0 scores = np.asarray(scores) finite = bool(np.isfinite(scores).all()) print(f" scores shape={scores.shape} dtype={scores.dtype} finite={finite} in {dt:.2f}s (CPU)") print(" scores =", np.array2string(scores, precision=6)) print(f" argmax={choice} min={float(scores.min()):.6f} max={float(scores.max()):.6f} std={float(scores.std()):.6f}") print(f" chain: p={scorer.p_cont:.6f} cap={scorer.cap} E[queries]={scorer.E_queries:.2f} " f"chunk={scorer.rsm.chunk} adim={scorer.rsm.adim}") ok = ok and scores.shape == (args.n,) and finite rep["D4"] = {"shape": list(scores.shape), "finite": finite, "scores": scores.tolist(), "argmax": int(choice), "latency_s": dt, "build_s": build_s, "p_cont": float(scorer.p_cont), "cap": int(scorer.cap), "dino_hub": scorer.feat.hub_dir, "dino_ckpt": scorer.feat.checkpoint, "hops": getattr(scorer, "hops", None)}
print("\n=== D5 permuted control, and a schema mismatch ===") pc = build("permuted:rsm", an, {"rsm_ckpt": args.rsm_ckpt, "rsm_hop_ckpt": args.hop_ckpt, "rsm_feat_stats": args.feat_stats, "rsm_particles": args.particles, "dino_hub_dir": args.dino_hub, "dino_checkpoint": args.dino_ckpt}, device="cpu") ch2, sc2 = pc.pick(cands, obs) print(" permuted:", np.array2string(np.asarray(sc2), precision=6), "argmax", ch2) rep["D5"] = {"permuted_scores": np.asarray(sc2).tolist(), "permuted_argmax": int(ch2)} print(" a truncated action dimension must fail loudly:") try: scorer.pick(cands[:, :, :5], obs) print(" NO ERROR -- that is a defect") ok = False except Exception as e: print(f" {type(e).__name__}: {str(e)[:200]}") rep["D5"]["truncated_raises"] = f"{type(e).__name__}: {str(e)[:200]}"
rep["ok"] = ok Path(args.out).write_text(json.dumps(rep, indent=1, default=str)) print("\nVERDICT:", "PASS -- finite [N] RSM scores from pinned sources only" if ok else "FAIL") print("wrote", args.out) return 0 if ok else 1
if __name__ == "__main__": sys.exit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475#!/usr/bin/env python"""rsm_real#5 item 3: make the pinned gen_q checkout's rsm_libero installable, without touching asingle line of the code that produced the checkpoints.
Our whole patch on top of gen_q is two new files: rsm_libero/__init__.py -- appends its own directory to sys.path, so `import rsm_libero.is_ope` works from an installed package while `import model` inside those modules (and the module paths torch.save recorded during training) still resolve to the SAME top-level modules as in training. APPENDED, never prepended, so nothing here can shadow the stdlib. pyproject.toml -- a minimal setuptools project exposing exactly that one package.
Run against a clone; idempotent."""import sysfrom pathlib import Path
INIT = '''"""rsm_libero -- the RSM successor-model library (gen_q).
Deployment packaging (rsm_real#5 item 3). The modules in this directory import one another astop-level modules (``import model``), which only works when this directory itself is on``sys.path``. Appending it here lets ``import rsm_libero`` work from an installed package whileleaving every module's own imports untouched, so the code that loads a checkpoint is byte-for-bytethe code that produced it. Appended rather than inserted, so no module here can shadow the standardlibrary for the rest of the process."""import os as _osimport sys as _sys
__all__ = []
_HERE = _os.path.dirname(_os.path.abspath(__file__))if _HERE not in _sys.path: _sys.path.append(_HERE)'''
PYPROJECT = '''[build-system]requires = ["setuptools>=61"]build-backend = "setuptools.build_meta"
[project]# rsm_real#5 item 3: packaging only. No source file in rsm_libero/ is modified by this project;# this exists so a deployment machine can `pip install -e <gen_q clone>` instead of pointing an# environment variable at a directory inside somebody's research checkout.name = "rsm-libero"version = "0.0.0"description = "RSM successor-model library (gen_q), packaged for inference deployment"requires-python = ">=3.9"
[tool.setuptools]packages = ["rsm_libero"]'''
def main(): root = Path(sys.argv[1]) lib = root / "rsm_libero" if not lib.is_dir(): print(f"FATAL: {lib} is not a directory") return 2 wrote = [] for rel, text in ((lib / "__init__.py", INIT), (root / "pyproject.toml", PYPROJECT)): if rel.exists() and rel.read_text() == text: continue if rel.exists() and rel.name == "pyproject.toml": print(f"FATAL: {rel} already exists with different content -- do not overwrite upstream") return 2 rel.write_text(text) wrote.append(str(rel.relative_to(root))) print("wrote:", ", ".join(wrote) if wrote else "(nothing, already in place)") return 0
if __name__ == "__main__": sys.exit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990#!/usr/bin/env python"""rsm_real#5 item 3 probe: what does the RSM inference closure actually need from rsm_libero?
Pure stdlib + ast. Run against a CLONE of gen_q at the pin. P1 the four named files: sha256 at the pin vs the research working tree P2 static intra-repo closure of model / train_rsm / is_ope / data (what else must ship) P3 external (non-rsm_libero) imports of that closure -- the pip dependencies to pin P4 stdlib shadowing: module names in rsm_libero that also exist in the standard library"""import argparse, ast, hashlib, json, sys, sysconfigfrom pathlib import Path
NAMED = ["model.py", "train_rsm.py", "is_ope.py", "data.py"]
def sha(p): return hashlib.sha256(Path(p).read_bytes()).hexdigest()[:16] if Path(p).is_file() else None
def imports_of(path): tree = ast.parse(Path(path).read_text(), filename=str(path)) out = set() for n in ast.walk(tree): if isinstance(n, ast.Import): for a in n.names: out.add(a.name.split(".")[0]) elif isinstance(n, ast.ImportFrom): if n.level == 0 and n.module: out.add(n.module.split(".")[0]) return out
def main(): ap = argparse.ArgumentParser() ap.add_argument("--pin-lib", required=True, help="rsm_libero/ inside the clone at the pin") ap.add_argument("--research-lib", required=True, help="rsm_libero/ in the research checkout") ap.add_argument("--out", required=True) a = ap.parse_args() pin, res = Path(a.pin_lib), Path(a.research_lib) rep = {}
print("=== P1 the four files named by the issue ===") rep["files"] = {} for f in NAMED: sp, sr = sha(pin / f), sha(res / f) same = "SAME" if sp == sr else "DIFFERS" print(f" {f:16s} pin={sp} research_worktree={sr} {same}") rep["files"][f] = {"pin_sha256_16": sp, "research_sha256_16": sr, "same": sp == sr}
print("\n=== P2 intra-repo closure (what else has to ship) ===") have = {p.stem: p for p in pin.glob("*.py")} seen, queue = set(), [f[:-3] for f in NAMED] ext = set() while queue: name = queue.pop() if name in seen or name not in have: continue seen.add(name) for imp in imports_of(have[name]): if imp in have: queue.append(imp) else: ext.add(imp) closure = sorted(seen) lines = sum(len(have[n].read_text().splitlines()) for n in closure) print(f" closure = {len(closure)} modules, {lines} lines: {', '.join(closure)}") print(f" (the package ships all {len(have)} modules in rsm_libero/ -- this is what is REACHED)") rep["closure"] = {"modules": closure, "lines": lines, "package_modules": len(have)}
print("\n=== P3 external imports of that closure (the pins a deployment env needs) ===") std = set(sys.stdlib_module_names) third = sorted(m for m in ext if m not in std) print(" stdlib :", ", ".join(sorted(m for m in ext if m in std))) print(" third-party:", ", ".join(third)) rep["external"] = {"stdlib": sorted(m for m in ext if m in std), "third_party": third}
print("\n=== P4 stdlib shadowing (why __init__ APPENDS its directory) ===") shadow = sorted(n for n in have if n in std) print(" module names in rsm_libero that also name a stdlib module:", ", ".join(shadow) or "(none)") print(" -> appending the directory to sys.path (never inserting) keeps the stdlib first") rep["stdlib_shadow"] = shadow rep["stdlib_dir"] = sysconfig.get_paths()["stdlib"]
Path(a.out).write_text(json.dumps(rep, indent=1)) print("\nwrote", a.out) return 0
if __name__ == "__main__": sys.exit(main())12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394#!/usr/bin/env bash# rsm_real#5 item 3: establish the gen_q pin + our packaging patch, and identify the DINOv2 source pin.# No research tree on sys.path anywhere; nothing here writes outside $SCRATCH.set -uo pipefailROOT=/proj/dmfexp/zwhong/rsm_riseSCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run6}GENQ_PIN=${GENQ_PIN:-f612011bb400ac204918be1d6f923e539cd59fd7}RESEARCH_GENQ=${RESEARCH_GENQ:-/proj/dmfexp/zwhong/projs/issue_resolver_richardrl/gen_q_rsm}DINO_LOCAL=${DINO_LOCAL:-$ROOT/cache/torch/hub/facebookresearch_dinov2_main}unset RISE_ROOT RSM_LIBERO_DIR PYTHONPATHexport PYTHONNOUSERSITE=1 PYTHONUNBUFFERED=1 GIT_TERMINAL_PROMPT=0hdr(){ echo; echo "=================== $* ==================="; date -u; }rc_all=0chk(){ if [ "$1" -ne 0 ]; then echo "STEP FAILED rc=$1: $2"; rc_all=1; fi; }mkdir -p "${SCRATCH:?}" || exit 1
hdr "0 context"echo "host=$(hostname) job=${LSB_JOBID:-none} scratch=$SCRATCH genq_pin=$GENQ_PIN"PY3=$(command -v python3); echo "python3=$PY3 ($($PY3 -V))"
hdr "1 gen_q at the pin (sparse: rsm_libero only)"rm -rf "${SCRATCH:?}/gen_q"git clone --quiet --filter=blob:none --no-checkout https://github.com/williamd4112/gen_q.git "${SCRATCH:?}/gen_q" || exit 1git -C "$SCRATCH/gen_q" sparse-checkout set rsm_libero >/dev/null || exit 1git -C "$SCRATCH/gen_q" checkout --quiet "$GENQ_PIN" || exit 1echo "gen_q HEAD = $(git -C "$SCRATCH/gen_q" rev-parse HEAD)"git -C "$SCRATCH/gen_q" log -1 --pretty=' %h %ad %s' --date=isoecho "rsm_libero modules at the pin: $(ls "$SCRATCH/gen_q/rsm_libero"/*.py | wc -l)"
hdr "2 probe: closure, external deps, stdlib shadowing""$PY3" "$ROOT/scripts/real/patchexport_item3_probe.py" \ --pin-lib "$SCRATCH/gen_q/rsm_libero" --research-lib "$RESEARCH_GENQ/rsm_libero" \ --out "$SCRATCH/item3_probe.json"chk $? "probe"
hdr "3 our packaging patch on gen_q, generated the way that cannot lose an untracked file""$PY3" "$ROOT/scripts/real/patchexport_item3_genq_pack.py" "$SCRATCH/gen_q"chk $? "pack"( cd "$SCRATCH/gen_q" && git add -A && git diff --cached > "$SCRATCH/rise_on_rsm_libero.patch" )chk $? "generate patch"echo "--- patch ---"; git -C "$SCRATCH/gen_q" diff --cached --stat | tail -5md5sum "$SCRATCH/rise_on_rsm_libero.patch"
hdr "4 the patch applies to a SECOND pristine clone and reproduces the tree exactly"rm -rf "${SCRATCH:?}/gen_q_verify"git clone --quiet --filter=blob:none --no-checkout https://github.com/williamd4112/gen_q.git "${SCRATCH:?}/gen_q_verify" \ && git -C "$SCRATCH/gen_q_verify" sparse-checkout set rsm_libero >/dev/null \ && git -C "$SCRATCH/gen_q_verify" checkout --quiet "$GENQ_PIN" \ && ( cd "$SCRATCH/gen_q_verify" && git apply "$SCRATCH/rise_on_rsm_libero.patch" && echo "git apply: OK" )chk $? "reapply"diff -r --exclude=.git "$SCRATCH/gen_q" "$SCRATCH/gen_q_verify" && echo "diff -r: IDENTICAL (patch is complete)"chk $? "diff -r"
hdr "5 the packaged import works, and does not shadow the stdlib"( cd "$SCRATCH" && "$PY3" - <<'PYX'import sys, ossys.path.insert(0, os.path.join(os.environ["SCRATCH"], "gen_q"))import rsm_liberoprint("rsm_libero.__file__ =", rsm_libero.__file__)d = os.path.dirname(os.path.abspath(rsm_libero.__file__))print("its directory is on sys.path:", d in sys.path, "at index", sys.path.index(d), "of", len(sys.path))import types, importlibfor name in ("json", "types", "code", "pickle"): m = importlib.import_module(name) f = getattr(m, "__file__", "<builtin>") or "<builtin>" assert d not in str(f), f"stdlib {name} was shadowed by {f}"print("stdlib not shadowed (json/types/code/pickle still resolve to the standard library)")PYX)chk $? "packaged import"
hdr "6 DINOv2: which upstream commit is the local hub tree?"rm -rf "${SCRATCH:?}/dinov2"git clone --quiet https://github.com/facebookresearch/dinov2.git "${SCRATCH:?}/dinov2" || exit 1echo "local hub tree: $DINO_LOCAL"best=""; bestn=999999for c in $(git -C "$SCRATCH/dinov2" log --format=%H -40); do git -C "$SCRATCH/dinov2" checkout --quiet "$c" n=$(diff -r -q --exclude=.git --exclude=__pycache__ "$DINO_LOCAL" "$SCRATCH/dinov2" 2>/dev/null | wc -l) if [ "$n" -lt "$bestn" ]; then bestn=$n; best=$c; fi if [ "$n" -eq 0 ]; then break; fidoneecho "closest upstream commit: $best differing entries: $bestn"git -C "$SCRATCH/dinov2" checkout --quiet "$best"git -C "$SCRATCH/dinov2" log -1 --pretty=' %h %ad %s' --date=isoif [ "$bestn" -ne 0 ]; then echo "--- residual differences (the hub cache is a zip export, so extras are expected) ---" diff -r -q --exclude=.git --exclude=__pycache__ "$DINO_LOCAL" "$SCRATCH/dinov2" 2>/dev/null | head -20fiecho "$best" > "$SCRATCH/dinov2_pin.txt"
hdr "done"echo "OVERALL rc=$rc_all"exit $rc_all12345678910111213141516171819202122232425262728293031323334353637#!/usr/bin/env bash# rsm_real#5 item 3, last box: does real/deployment/models.py record the rsm_libero SOURCE PROVENANCE# when the package is installed and RSM_LIBERO_DIR is unset? Reuses the venv built by# patchexport_item3_validate.sh (run7) -- no rebuild.set -uo pipefailROOT=/proj/dmfexp/zwhong/rsm_riseSCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run7}unset RISE_ROOT RSM_LIBERO_DIR HF_TOKENexport PYTHONPATH="$SCRATCH/diffusion_policy" PYTHONNOUSERSITE=1 PYTHONUNBUFFERED=1export TORCH_HOME=$SCRATCH/torch_home HF_HOME=$SCRATCH/hf_home MPLCONFIGDIR=$SCRATCH/mplPY=$SCRATCH/venv/bin/pythonecho "host=$(hostname) job=${LSB_JOBID:-none} py=$PY"; date -u"$PY" - <<'PYX'import json, os, syssys.path.insert(0, os.path.join(os.environ["SCRATCH"], "rsm_real"))from real.deployment import modelsfrom rise_stack.config import ActionNormfrom rise_stack.scorers import buildS = os.environ["SCRATCH"]; R = "/proj/dmfexp/zwhong/rsm_rise/hf_ckpt_root"print("RSM_LIBERO_DIR =", repr(os.environ.get("RSM_LIBERO_DIR")))print("before loading anything:", json.dumps(models._source_roots(False), indent=1))an = ActionNorm.load(os.path.join(S, "rsm_real/rise_stack/configs/action_norm.json"))build("rsm", an, {"rsm_ckpt": f"{R}/successor_rsm_real_RM_s0_100k.pt", "rsm_hop_ckpt": f"{R}/hop_head_rsm_real_gauss_r1.pt", "rsm_feat_stats": f"{R}/successor_rsm_real_feat_stats.json", "rsm_particles": 2, "dino_hub_dir": f"{S}/dinov2", "dino_checkpoint": f"{S}/dino_weights/dinov2_vits14_pretrain.pth"}, device="cpu")roots = models._source_roots(False)print("after building the rsm scorer:", json.dumps(roots, indent=1))assert "rsm_libero" in roots, "provenance did not record rsm_libero"assert roots["rsm_libero"].startswith(S), roots["rsm_libero"]assert "robomimic" in roots, rootsprint("PASS: provenance records the INSTALLED rsm_libero and robomimic, with no RSM_LIBERO_DIR set")PYXrc=$?echo "OVERALL rc=$rc"; exit $rc123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081#!/usr/bin/env bash# rsm_real#5 item 3: regenerate rise_on_robomimic.patch with the item-3 import fix folded in.# Same staging idiom as patchexport_item2_export.sh: `git add -A` ALONE drops files the upstream# .gitignore matches (macros_private.py), which is the class of bug that lost cooking_policy.py.set -uo pipefailROOT=/proj/dmfexp/zwhong/rsm_riseSCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run8}SRC=${SRC:-/proj/dmfexp/zwhong/scratch_patchexport/wt_item3}RM_PIN=${RM_PIN:-40e427a695a9f085d3fc0f70ffb0d687a10802c8}export GIT_TERMINAL_PROMPT=0 PYTHONNOUSERSITE=1 PYTHONUNBUFFERED=1hdr(){ echo; echo "=================== $* ==================="; date -u; }rc_all=0chk(){ if [ "$1" -ne 0 ]; then echo "STEP FAILED rc=$1: $2"; rc_all=1; fi; }mkdir -p "${SCRATCH:?}" || exit 1
hdr "0 context"echo "host=$(hostname) job=${LSB_JOBID:-none} scratch=$SCRATCH src=$SRC pin=$RM_PIN"md5sum "$SRC/rise_stack/robomimic/rise_on_robomimic.patch" "$SRC/rise_stack/robomimic/rise_on_robomimic_tests.patch"
hdr "1 pristine clone at the pin + both shipped patches + the item-3 fix"rm -rf "${SCRATCH:?}/post"git clone --quiet https://github.com/ARISE-Initiative/robomimic.git "${SCRATCH:?}/post" || exit 1git -C "$SCRATCH/post" checkout --quiet "$RM_PIN" || exit 1( cd "$SCRATCH/post" && git apply "$SRC/rise_stack/robomimic/rise_on_robomimic.patch" \ && git apply "$SRC/rise_stack/robomimic/rise_on_robomimic_tests.patch" && echo "both shipped patches apply: OK" )chk $? "apply shipped patches"python3 "$ROOT/scripts/real/patchexport_item3_apply_fix.py" "$SCRATCH/post/robomimic/algo/rsm_scorer.py"chk $? "item-3 fix"
hdr "2 stage, force-adding anything the upstream .gitignore matches"( cd "$SCRATCH/post" && git add -A \ && ignored=$(git status --porcelain --ignored=matching | awk '$1=="!!"{print $2}') \ && if [ -n "$ignored" ]; then echo "force-adding gitignored source files: $ignored"; \ for f in $ignored; do case "$f" in *__pycache__*|*.pyc) ;; *) git add -f "$f";; esac; done; fi \ && echo "--- still untracked/ignored after force-add (must contain no source file) ---" \ && git status --porcelain --ignored=matching | head -10 )chk $? "stage"
hdr "3 the two patches, scoped exactly as before"( cd "$SCRATCH/post" \ && git diff --cached -- robomimic > "$SCRATCH/rise_on_robomimic.patch" \ && git diff --cached -- tests examples > "$SCRATCH/rise_on_robomimic_tests.patch" \ && echo "--- package patch ---" && git diff --cached --shortstat -- robomimic \ && echo "--- research-tests patch ---" && git diff --cached --shortstat -- tests examples \ && echo "--- staged OUTSIDE those two (must be empty) ---" \ && git diff --cached --stat -- . ':(exclude)robomimic' ':(exclude)tests' ':(exclude)examples' )chk $? "generate"md5sum "$SCRATCH"/rise_on_robomimic*.patchecho "macros_private.py hunks in the package patch: $(grep -c 'macros_private' "$SCRATCH/rise_on_robomimic.patch")"echo "the item-3 fix in the package patch: $(grep -c '_rsm_libero_dir' "$SCRATCH/rise_on_robomimic.patch")"echo "--- what changed vs the shipped package patch ---"diff <(grep '^[+-]' "$SRC/rise_stack/robomimic/rise_on_robomimic.patch") \ <(grep '^[+-]' "$SCRATCH/rise_on_robomimic.patch") | head -80echo "(diff of the +/- lines only; hunk headers move, so this is the readable form)"
hdr "4 both regenerated patches apply to a pristine clone and reproduce the tree exactly"rm -rf "${SCRATCH:?}/verify"git clone --quiet https://github.com/ARISE-Initiative/robomimic.git "${SCRATCH:?}/verify" \ && git -C "$SCRATCH/verify" checkout --quiet "$RM_PIN" \ && ( cd "$SCRATCH/verify" && git apply "$SCRATCH/rise_on_robomimic.patch" \ && git apply "$SCRATCH/rise_on_robomimic_tests.patch" && echo "git apply: OK" )chk $? "reapply"diff -r --exclude=.git "$SCRATCH/post" "$SCRATCH/verify" && echo "diff -r: IDENTICAL (nothing was lost)"chk $? "diff -r"
hdr "5 the fix is syntactically sound and idempotent"python3 -c "import ast, syssrc = open('$SCRATCH/verify/robomimic/algo/rsm_scorer.py').read()ast.parse(src)assert 'RSM_LIBERO_DIR = os.environ.get(\"RSM_LIBERO_DIR\", \"\")' in src, 'default path not removed'assert '/proj/dmfexp/zwhong/rsm_rise/code/gen_q/rsm_libero' in src, 'legacy fallback should stay, named once'print('rsm_scorer.py parses; the hardcoded path survives only as the last-resort fallback')"chk $? "syntax"python3 "$ROOT/scripts/real/patchexport_item3_apply_fix.py" "$SCRATCH/verify/robomimic/algo/rsm_scorer.py"chk $? "idempotent"
hdr "done"echo "OVERALL rc=$rc_all"exit $rc_all123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124#!/usr/bin/env bash# rsm_real#5 item 3: build the RSM inference environment from PINNED SOURCES ONLY -- upstream repos at# their pins plus our patches, no file copied out of the research tree -- and score real candidate# chunks with the real successor. RSM_LIBERO_DIR stays UNSET throughout, on purpose.set -uo pipefailROOT=/proj/dmfexp/zwhong/rsm_riseSCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run7}SRC=${SRC:-/proj/dmfexp/zwhong/scratch_patchexport/wt_item3} # the rsm_real branch under testRM_PIN=${RM_PIN:-40e427a695a9f085d3fc0f70ffb0d687a10802c8} # robomimic v0.3.0GENQ_PIN=${GENQ_PIN:-f612011bb400ac204918be1d6f923e539cd59fd7} # gen_q rsm_rise_dataDINO_PIN=${DINO_PIN:-7764ea0f912e53c92e82eb78a2a1631e92725fc8} # facebookresearch/dinov2DP_PIN=${DP_PIN:-078ce1e}RSM_CKPT=${RSM_CKPT:-$ROOT/hf_ckpt_root/successor_rsm_real_RM_s0_100k.pt}HOP_CKPT=${HOP_CKPT:-$ROOT/hf_ckpt_root/hop_head_rsm_real_gauss_r1.pt}FEAT_STATS=${FEAT_STATS:-$ROOT/hf_ckpt_root/successor_rsm_real_feat_stats.json}DINO_WEIGHTS_LOCAL=${DINO_WEIGHTS_LOCAL:-/u/zwhong/.cache/torch/hub/checkpoints/dinov2_vits14_pretrain.pth}DINO_URL=${DINO_URL:-https://dl.fbaipublicfiles.com/dinov2/dinov2_vits14/dinov2_vits14_pretrain.pth}UV=${UV:-/u/zwhong/.local/bin/uv}unset RISE_ROOT RSM_LIBERO_DIR PYTHONPATH HF_TOKEN HF_HUB_OFFLINEexport PYTHONNOUSERSITE=1 PYTHONUNBUFFERED=1 UV_CACHE_DIR=$SCRATCH/uv_cache HF_HOME=$SCRATCH/hf_homeexport TORCH_HOME=$SCRATCH/torch_home MPLCONFIGDIR=$SCRATCH/mpl GIT_TERMINAL_PROMPT=0hdr(){ echo; echo "=================== $* ==================="; date -u; }rc_all=0chk(){ if [ "$1" -ne 0 ]; then echo "STEP FAILED rc=$1: $2"; rc_all=1; fi; }mkdir -p "${SCRATCH:?}" || exit 1
hdr "0 context"echo "host=$(hostname) job=${LSB_JOBID:-none} scratch=$SCRATCH"echo "pins: robomimic=$RM_PIN gen_q=$GENQ_PIN dinov2=$DINO_PIN diffusion_policy=$DP_PIN"for f in "$RSM_CKPT" "$HOP_CKPT" "$FEAT_STATS"; do ls -l "$f" | awk '{print " "$5" "$9}'; sha256sum "$f" | cut -c1-24 | sed 's/^/ sha256: /'; done
hdr "1 robomimic: upstream pin + our patch + the item-3 import fix, patch REGENERATED"rm -rf "${SCRATCH:?}/robomimic"git clone --quiet https://github.com/ARISE-Initiative/robomimic.git "${SCRATCH:?}/robomimic" || exit 1git -C "$SCRATCH/robomimic" checkout --quiet "$RM_PIN" || exit 1( cd "$SCRATCH/robomimic" && git apply "$SRC/rise_stack/robomimic/rise_on_robomimic.patch" && echo "exported patch applies: OK" )chk $? "apply exported robomimic patch"python3 "$ROOT/scripts/real/patchexport_item3_apply_fix.py" "$SCRATCH/robomimic/robomimic/algo/rsm_scorer.py"chk $? "item-3 import fix"( cd "$SCRATCH/robomimic" && git add -A && git diff --cached > "$SCRATCH/rise_on_robomimic.patch" )chk $? "regenerate robomimic patch"git -C "$SCRATCH/robomimic" diff --cached --stat | tail -2md5sum "$SCRATCH/rise_on_robomimic.patch"rm -rf "${SCRATCH:?}/robomimic_verify"git clone --quiet https://github.com/ARISE-Initiative/robomimic.git "${SCRATCH:?}/robomimic_verify" \ && git -C "$SCRATCH/robomimic_verify" checkout --quiet "$RM_PIN" \ && ( cd "$SCRATCH/robomimic_verify" && git apply "$SCRATCH/rise_on_robomimic.patch" && echo "regenerated patch applies to a pristine clone: OK" )chk $? "reapply robomimic"diff -r --exclude=.git "$SCRATCH/robomimic" "$SCRATCH/robomimic_verify" && echo "diff -r: IDENTICAL"chk $? "robomimic diff -r"
hdr "2 rsm_libero: gen_q at the pin + our packaging patch"rm -rf "${SCRATCH:?}/gen_q"git clone --quiet --filter=blob:none --no-checkout https://github.com/williamd4112/gen_q.git "${SCRATCH:?}/gen_q" || exit 1git -C "$SCRATCH/gen_q" sparse-checkout set rsm_libero >/dev/null && git -C "$SCRATCH/gen_q" checkout --quiet "$GENQ_PIN" || exit 1python3 "$ROOT/scripts/real/patchexport_item3_genq_pack.py" "$SCRATCH/gen_q"chk $? "gen_q packaging"( cd "$SCRATCH/gen_q" && git add -A && git diff --cached > "$SCRATCH/rise_on_rsm_libero.patch" )md5sum "$SCRATCH/rise_on_rsm_libero.patch"
hdr "3 the rsm_real branch under test"rm -rf "${SCRATCH:?}/rsm_real"git clone --quiet "$SRC" "${SCRATCH:?}/rsm_real" || exit 1REPO=$SCRATCH/rsm_realecho "rsm_real HEAD: $(git -C "$REPO" rev-parse --short HEAD) $(git -C "$REPO" log -1 --pretty=%s)"
hdr "4 DINOv2 at its pin, plus the published weights"rm -rf "${SCRATCH:?}/dinov2"git clone --quiet https://github.com/facebookresearch/dinov2.git "${SCRATCH:?}/dinov2" \ && git -C "$SCRATCH/dinov2" checkout --quiet "$DINO_PIN" && echo "dinov2 HEAD: $(git -C "$SCRATCH/dinov2" rev-parse HEAD)"chk $? "dinov2 clone"mkdir -p "$SCRATCH/dino_weights"W=$SCRATCH/dino_weights/dinov2_vits14_pretrain.pthif [ ! -s "$W" ]; then curl -fsSL --max-time 300 -o "$W" "$DINO_URL" && echo "weights downloaded from $DINO_URL" \ || { echo "download failed; falling back to the local torch hub cache (same file, stated as such)"; cp "$DINO_WEIGHTS_LOCAL" "$W"; }fisha256sum "$W"; sha256sum "$DINO_WEIGHTS_LOCAL" 2>/dev/null
hdr "5 a fresh venv from the pins"rm -rf "${SCRATCH:?}/venv""$UV" venv --python 3.10 "${SCRATCH:?}/venv" 2>&1 | tail -2PY=$SCRATCH/venv/bin/pythonUVP="$UV pip install --python $PY"$UVP torch==2.5.1 torchvision==0.20.1 2>&1 | tail -1; chk $? "torch"$UVP -e "$SCRATCH/robomimic" 2>&1 | tail -2; chk $? "robomimic editable"$UVP diffusers==0.32.2 2>&1 | tail -1; chk $? "diffusers"rm -rf "${SCRATCH:?}/diffusion_policy"git clone --quiet https://github.com/UWRobotLearning/diffusion_policy.git "${SCRATCH:?}/diffusion_policy" \ && git -C "$SCRATCH/diffusion_policy" checkout --quiet "$DP_PIN"# no __init__.py anywhere: the editable install exposes nothing, so the clone goes on PYTHONPATH$UVP -e "$SCRATCH/diffusion_policy" 2>&1 | tail -1"$PY" -c "import diffusion_policy" 2>/dev/null || export PYTHONPATH="$SCRATCH/diffusion_policy"$UVP -e "$SCRATCH/gen_q" 2>&1 | tail -2; chk $? "rsm_libero editable (gen_q pin + packaging patch)"$UVP opencv-python==4.11.0.86 h5py==3.16.0 pyarrow pandas av 2>&1 | tail -1; chk $? "extras"$UVP "numpy==1.26.4" 2>&1 | tail -1"$PY" -c "import numpy,sys; print('numpy',numpy.__version__); sys.exit(0 if numpy.__version__.startswith('1.') else 1)"chk $? "numpy stayed on 1.x""$UV" pip freeze --python "$PY" > "$SCRATCH/pip_freeze.txt"; wc -l "$SCRATCH/pip_freeze.txt"grep -E "^(torch|torchvision|numpy|diffusers|robomimic|rsm|opencv|h5py|av|wandb)" "$SCRATCH/pip_freeze.txt"echo "--- wandb must NOT be needed: train_rsm imports it inside a training-only function ---""$PY" -c "import importlib.util as u, sysprint('wandb installed:', u.find_spec('wandb') is not None)import rsm_libero, train_rsm, model, is_opeprint('train_rsm from', train_rsm.__file__)print('imported model/train_rsm/is_ope with no wandb present')"chk $? "rsm_libero imports without wandb"
hdr "6 D1-D5""$PY" "$ROOT/scripts/real/patchexport_item3_checks.py" --repo "$REPO" \ --rsm-ckpt "$RSM_CKPT" --hop-ckpt "$HOP_CKPT" --feat-stats "$FEAT_STATS" \ --dino-hub "$SCRATCH/dinov2" --dino-ckpt "$W" --out "$SCRATCH/item3_checks.json"chk $? "item3 checks"
hdr "7 the repository's own deployment tests, in this environment"$UVP pytest hydra-core==1.3.2 omegaconf 2>&1 | tail -1( cd "$REPO" && "$PY" -m pytest tests/test_deployment_models.py -q 2>&1 | tail -8 )chk $? "deployment model tests"
hdr "done"echo "OVERALL rc=$rc_all"exit $rc_all123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145#!/usr/bin/env bash# rsm_real#5 / owner directive: export code/mimicgen_environments as a PATCH against upstream# UWRobotLearning/mimicgen_environments@14d8eb5. This tree is SIMULATION ONLY and is NOT a robot# deployment dependency; it is exported for completeness so a sim result can be reproduced.## The inventory in my brief said "46 changed + 43 untracked". Measured: `git status --porcelain`# returns 3 M + 43 ?? = 46 entries, i.e. 3 modified SOURCE files (66 insertions) and 43 untracked# entries that are NOT source. This script proves that classification rather than asserting it:# every untracked entry must be either a *.bak.* backup or a runtime-generated MuJoCo XML written by# upstream's own mimicgen_envs/models/robosuite/objects/xml_objects.py:81-83# (`"{}_{}.xml".format(str(time.time()).replace(".","_"), os.getpid())`). Anything else fails the run.set -uo pipefailROOT=/proj/dmfexp/zwhong/rsm_riseFORK=$ROOT/code/mimicgen_environmentsSCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run10}PIN=${PIN:-14d8eb5709b38c6b75ecf140c3608ff984196832}URL=https://github.com/UWRobotLearning/mimicgen_environments.githdr(){ echo; echo "=================== $* ==================="; date -u; }rc_all=0chk(){ if [ "$1" -ne 0 ]; then echo "STEP FAILED rc=$1: $2"; rc_all=1; fi; }mkdir -p "${SCRATCH:?}" || exit 1
hdr "0 context"echo "host=$(hostname) job=${LSB_JOBID:-none} fork=$FORK pin=$PIN scratch=$SCRATCH"echo "fork HEAD: $(git -C "$FORK" rev-parse HEAD)"echo "fork HEAD == pin: $([ "$(git -C "$FORK" rev-parse HEAD)" = "$PIN" ] && echo YES || echo NO)"
hdr "1 classify EVERY entry git reports in the fork -- no source file may be silently dropped"git -C "$FORK" status --porcelain > "$SCRATCH/fork_status.txt"echo "total entries: $(wc -l < "$SCRATCH/fork_status.txt")"awk '{print $1}' "$SCRATCH/fork_status.txt" | sort | uniq -cpython3 - "$FORK" "$SCRATCH/fork_status.txt" <<'CLSEOF'import re, sysfrom pathlib import Pathfork, status = Path(sys.argv[1]), Path(sys.argv[2])# upstream xml_objects.py writes "<epoch_with_underscore>_<pid>.xml" next to the object's model.xmlRUNTIME_XML = re.compile(r"^\d+_\d+_\d+\.xml$")mod, bak, runtime, unknown = [], [], [], []for line in status.read_text().splitlines(): code, rel = line[:2].strip(), line[3:].strip() p = Path(rel) if code == "M": mod.append(rel) elif ".bak." in p.name: bak.append(rel) elif RUNTIME_XML.match(p.name) and "assets" in p.parts: runtime.append(rel) else: unknown.append((code, rel))print(f"modified source files ({len(mod)}) -- THESE are the patch:")for m in mod: print(" ", m)print(f"\n*.bak.* editor backups, excluded by the standing rule ({len(bak)}):")for b in bak: print(" ", b)print(f"\nruntime-generated MuJoCo XML caches, excluded ({len(runtime)}):")for r in runtime[:6]: print(" ", r)if len(runtime) > 6: print(f" ... and {len(runtime)-6} more, all under the same assets dir")dirs = sorted({str(Path(r).parent) for r in runtime})print(f" dirs: {dirs}")print(f"\nUNCLASSIFIED entries (must be empty) ({len(unknown)}): {unknown}")sys.exit(1 if unknown else 0)CLSEOFchk $? "classification: every untracked entry accounted for as non-source"echo "--- proof the runtime XMLs come from upstream code, not from us ---"grep -n "time.time()\|os.getpid()\|new_xml_path" "$FORK/mimicgen_envs/models/robosuite/objects/xml_objects.py" | head -6echo "--- is that writer file itself modified by us? (must print nothing) ---"git -C "$FORK" diff --name-only -- mimicgen_envs/models/robosuite/objects/xml_objects.pyecho "--- the canonical tracked source for that object ---"git -C "$FORK" ls-files "mimicgen_envs/models/robosuite/assets/shapenet_core/mugs/3143a4ac/" | grep '\.xml$'
hdr "2 two pristine upstream clones at the pin"for t in post verify; do rm -rf "${SCRATCH:?}/${t:?}" git clone --quiet "$URL" "${SCRATCH:?}/${t:?}" || exit 1 git -C "$SCRATCH/$t" checkout --quiet "$PIN" || exit 1 echo "$t: HEAD=$(git -C "$SCRATCH/$t" rev-parse HEAD) clean=[$(git -C "$SCRATCH/$t" status --porcelain | head -2)]"done
hdr "3 overlay the fork's modified source files onto post/"while read -r rel; do echo " overlay $rel" cp -p "$FORK/$rel" "$SCRATCH/post/$rel" || exit 1done < <(git -C "$FORK" diff --name-only)
hdr "4 generate the patch"( cd "$SCRATCH/post" && git add -A \ && ignored=$(git status --porcelain --ignored=matching | awk '$1=="!!"{print $2}') \ && if [ -n "$ignored" ]; then echo "force-adding gitignored source files: $ignored"; \ for f in $ignored; do case "$f" in *__pycache__*|*.pyc) ;; *) git add -f "$f";; esac; done; fi \ && echo "--- still untracked/ignored after force-add (must contain no source file) ---" \ && git status --porcelain --ignored=matching | head -10 \ && git diff --cached > "$SCRATCH/rise_on_mimicgen.patch" \ && git diff --cached --stat )chk $? "generate"wc -l "$SCRATCH/rise_on_mimicgen.patch"; md5sum "$SCRATCH/rise_on_mimicgen.patch"echo " files touched: $(grep -c '^+++ ' "$SCRATCH/rise_on_mimicgen.patch")"echo " insertions: $(grep -c '^+[^+]' "$SCRATCH/rise_on_mimicgen.patch")"echo " deletions: $(grep -c '^-[^-]' "$SCRATCH/rise_on_mimicgen.patch")"
hdr "5 the patch reapplies to a pristine clone and reproduces post/ exactly"( cd "$SCRATCH/verify" \ && git apply --check "$SCRATCH/rise_on_mimicgen.patch" && echo "git apply --check OK" \ && git apply "$SCRATCH/rise_on_mimicgen.patch" && echo "git apply OK" )chk $? "reapply"diff -r -q --exclude=.git --exclude=__pycache__ "$SCRATCH/post" "$SCRATCH/verify" && echo "post/ == verify/"chk $? "post == verify"
hdr "5b the patched clone equals the fork byte for byte on every tracked source file"python3 - "$FORK" "$SCRATCH/verify" <<'CMPEOF'import filecmp, subprocess, sysfrom pathlib import Pathfork, got = Path(sys.argv[1]), Path(sys.argv[2])tracked = subprocess.run(["git", "-C", str(fork), "ls-files"], capture_output=True, text=True, check=True).stdout.split()bad, n = [], 0for rel in tracked: src, tgt = fork / rel, got / rel if not src.is_file(): continue n += 1 if not tgt.is_file(): bad.append(("MISSING", rel)) elif not filecmp.cmp(src, tgt, shallow=False): bad.append(("DIFFERS", rel))print(f"compared {n} tracked files from the fork against the patched clone")for kind, rel in bad[:40]: print(" ", kind, rel)print("VERDICT:", "the patch reconstructs the fork byte for byte" if not bad else f"{len(bad)} FILES NOT RECONSTRUCTED")sys.exit(1 if bad else 0)CMPEOFchk $? "patch reconstructs the fork"
hdr "6 does the patch leak anything it should not?"echo "--- absolute cluster paths (count must be 0) ---"grep -c "^+.*\(/proj/dmfexp\|/u/zwhong\|/gpfs\)" "$SCRATCH/rise_on_mimicgen.patch"grep -n "^+.*\(/proj/dmfexp\|/u/zwhong\|/gpfs\)" "$SCRATCH/rise_on_mimicgen.patch" | head -10echo "--- credentials / keys (count must be 0) ---"grep -c -i "^+.*\(api_key\|apikey\|secret\|token\s*=\|password\|wandb_api\)" "$SCRATCH/rise_on_mimicgen.patch"
hdr "7 the patch itself, for the record"cat "$SCRATCH/rise_on_mimicgen.patch"
hdr "done"echo "OVERALL rc=$rc_all"exit $rc_all123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117diff --git a/tests/test_rise_stack_rsm_libero_live.py b/tests/test_rise_stack_rsm_libero_live.pyindex 3b367c3..eab0d06 100644--- a/tests/test_rise_stack_rsm_libero_live.py+++ b/tests/test_rise_stack_rsm_libero_live.py@@ -26,6 +26,28 @@ REPO = Path(__file__).resolve().parent.parent RSM_DIR = REPO / "rise_stack" / "rsm" VENDORED_LIBERO = RSM_DIR / "rsm_libero" +# `rise_stack/rsm/` is the SUBJECT of the vendored guards below, and PR #8 deletes it. On the tree+# the six-way merge produces, those guards fail with `ModuleNotFoundError: No module named+# 'rise_stack.rsm'` for a tree that is correct (LSF 1908601: seven failures, one cause, read out of+# the junit xml). So the subject's presence decides which half of this file runs -- the same+# predicate `tests/test_rise_stack_rsm_libero_closure.py` uses, spelled the same way on purpose: one+# tree must not be able to satisfy one file's notion of "vendored" and not the other's.+#+# The skipif is only half the repair. With it alone this file goes from 14 executed tests to 7 on+# the tree we ship, and every one of the 7 that remain is about module PROVENANCE -- the claim that a+# scorer can actually be constructed, which is the claim that failed on 2026-09-24 (LSF 1905498),+# would have nothing executing it post-#8. The other half of the repair is the fork_only test at the+# bottom of this file, which runs exactly where these stop.+VENDORED_PRESENT = VENDORED_LIBERO.is_dir() and (RSM_DIR / "rsm_scorer.py").is_file()+vendored_only = pytest.mark.skipif(+ not VENDORED_PRESENT,+ reason="rise_stack/rsm/ is not in this tree (PR #8's shape); the live post-#8 claim is asserted "+ "by test_without_the_vendored_copy_the_reader_is_sent_to_the_fork instead")+fork_only = pytest.mark.skipif(+ VENDORED_PRESENT,+ reason="rise_stack/rsm/ is vendored in this tree, so the vendored live guards are the ones that "+ "apply and they are not skipped")+ # NOT a "path does not contain /proj/dmfexp/zwhong" test. The first version of this file asserted # exactly that and three of its cases failed on the cluster for a reason that had nothing to do with # the claim: the working checkout of THIS repo is /proj/dmfexp/zwhong/projs/rsm_real, so the literal@@ -67,6 +89,7 @@ def _run(code, env_extra=None): capture_output=True, text=True, cwd=str(REPO), timeout=600) +@vendored_only @pytest.mark.parametrize("env_extra,want_why", [ ({}, "vendored"), ({"RSM_LIBERO_DIR": ""}, "vendored"),@@ -97,6 +120,7 @@ def test_rsm_libero_resolution_under_each_condition(env_extra, want_why): f"rsm_libero_source() said {named} but {f} loaded from elsewhere") +@vendored_only def test_rsm_libero_is_the_vendored_copy_when_nothing_is_configured(): r = _run(""" from rise_stack.rsm import rsm_scorer as s@@ -268,6 +292,7 @@ def test_interpreter_denied_roots_is_empty_outside_a_venv_and_named_inside_one() f"call every installed package a leak:\n{r.stdout}") +@vendored_only def test_dependency_report_does_not_call_the_vendored_scorer_missing(): """LSF 1905498 PROBE C, as a live assertion in a directory this branch keeps. @@ -290,6 +315,7 @@ def test_dependency_report_does_not_call_the_vendored_scorer_missing(): f"resolves, under RSM_LIBERO_DIR=/nonexistent: {rows}") +@vendored_only def test_which_scorer_reports_where_rsm_libero_came_from(): r = _run(""" import json@@ -304,3 +330,51 @@ def test_which_scorer_reports_where_rsm_libero_came_from(): assert _inside_repo(info["rsm_libero_dir"]), ( f"which_scorer named {info['rsm_libero_dir']}, which is outside this checkout -- that is the " "2026-09-24 defect exactly: a scorer reported as vendored whose modules come from elsewhere")+++# ------------------------------------------------- the same claim on the tree PR #8 produces+++@fork_only+def test_without_the_vendored_copy_the_reader_is_sent_to_the_fork():+ """The post-#8 half of "an RSM scorer resolves from a clean clone", EXECUTED rather than skipped.++ Runs `rise_stack.which_scorer` on the tree as it is, with no vendored copy, and accepts either of+ the two states that are legitimate there:++ * the patched RISE robomimic IS installed -- then it must be the winner, `vendored` must be+ False, the command must exit 0, and it must name the rsm_libero it will import from;+ * it is NOT installed -- then the command must exit 1 AND its hint must send the reader to+ install the fork (SETUP.md), not tell them the vendored file is present but broken. The+ wrong hint is the expensive one: it sends someone to re-clone a repository that is fine.++ Both are real answers on a post-#8 tree, which is why this is one test and not two. It needs+ neither torch nor robomimic, so it also executes in the hardware-free CI job.+ """+ r = _run("""+ import json+ from rise_stack import which_scorer+ info = which_scorer.resolve()+ rc = which_scorer.main([])+ print("RC", rc)+ print("JSON", json.dumps(info))+ """)+ assert r.returncode == 0, f"which_scorer itself raised:\n{r.stdout}\n{r.stderr}"+ info = json.loads([l for l in r.stdout.splitlines() if l.startswith("JSON ")][0][5:])+ rc = int([l for l in r.stdout.splitlines() if l.startswith("RC ")][0][3:])+ assert info["vendored"] is False, (+ f"rise_stack/rsm/ is absent from this tree but which_scorer reports vendored: {info}")+ if info["module"] is not None:+ assert info["module"] == "robomimic.algo.rsm_scorer", (+ f"the only post-#8 implementation is the fork's, but the winner is {info['module']}")+ assert rc == 0, f"a scorer resolved but the command exited {rc}"+ assert info["rsm_libero_dir"] and info["rsm_libero_source"] != "unknown", (+ "the fork resolved without naming where it imports model/train_rsm/is_ope/data from -- "+ f"that is the 2026-09-24 defect exactly: {info}")+ else:+ assert rc == 1, f"no scorer resolved but the command exited {rc}, so a script would not notice"+ assert "did not import" not in r.stdout, (+ "no vendored copy exists, yet the hint blames one for failing to import:\n" + r.stdout)+ assert "robomimic" in r.stdout and "SETUP.md" in r.stdout, (+ "post-#8 the repair is 'install the patched RISE robomimic (see SETUP.md)' and the "+ "command does not say so, so the reader is left to guess:\n" + r.stdout)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132#!/usr/bin/env python3"""rsm_real#5 run 32 -- the candidate repair for the seven live guards PR #8's tree makes red.
Measured on the six-way merged tree (LSF 1908601, #11 at 2dc85c8b): seven tests in`tests/test_rise_stack_rsm_libero_live.py` fail with `ModuleNotFoundError: No module named'rise_stack.rsm'` -- the package PR #8 deletes. They are red for a tree that is CORRECT.
#11 already fixed the companion file this way (`VENDORED_PRESENT`, `vendored_only`, `fork_only`), sothis applies the same predicate here, spelled identically, and -- the half that matters -- adds thePOSITIVE post-#8 assertion. A plain skipif alone takes the live file from 14 executed to 7 on thetree we ship and leaves the claim the file exists for ("constructing an RSM scorer from a clean cloneworks, or the command says exactly what is missing") with no executed guard there.
Transformation only: refuses unless every anchor is found exactly once, and is idempotent."""from __future__ import annotations
import sysfrom pathlib import Path
MARKS = '''# `rise_stack/rsm/` is the SUBJECT of the vendored guards below, and PR #8 deletes it. On the tree# the six-way merge produces, those guards fail with `ModuleNotFoundError: No module named# 'rise_stack.rsm'` for a tree that is correct (LSF 1908601: seven failures, one cause, read out of# the junit xml). So the subject's presence decides which half of this file runs -- the same# predicate `tests/test_rise_stack_rsm_libero_closure.py` uses, spelled the same way on purpose: one# tree must not be able to satisfy one file's notion of "vendored" and not the other's.## The skipif is only half the repair. With it alone this file goes from 14 executed tests to 7 on# the tree we ship, and every one of the 7 that remain is about module PROVENANCE -- the claim that a# scorer can actually be constructed, which is the claim that failed on 2026-09-24 (LSF 1905498),# would have nothing executing it post-#8. The other half of the repair is the fork_only test at the# bottom of this file, which runs exactly where these stop.VENDORED_PRESENT = VENDORED_LIBERO.is_dir() and (RSM_DIR / "rsm_scorer.py").is_file()vendored_only = pytest.mark.skipif( not VENDORED_PRESENT, reason="rise_stack/rsm/ is not in this tree (PR #8's shape); the live post-#8 claim is asserted " "by test_without_the_vendored_copy_the_reader_is_sent_to_the_fork instead")fork_only = pytest.mark.skipif( VENDORED_PRESENT, reason="rise_stack/rsm/ is vendored in this tree, so the vendored live guards are the ones that " "apply and they are not skipped")'''
NEW_TEST = '''
# ------------------------------------------------- the same claim on the tree PR #8 produces
@fork_onlydef test_without_the_vendored_copy_the_reader_is_sent_to_the_fork(): """The post-#8 half of "an RSM scorer resolves from a clean clone", EXECUTED rather than skipped.
Runs `rise_stack.which_scorer` on the tree as it is, with no vendored copy, and accepts either of the two states that are legitimate there:
* the patched RISE robomimic IS installed -- then it must be the winner, `vendored` must be False, the command must exit 0, and it must name the rsm_libero it will import from; * it is NOT installed -- then the command must exit 1 AND its hint must send the reader to install the fork (SETUP.md), not tell them the vendored file is present but broken. The wrong hint is the expensive one: it sends someone to re-clone a repository that is fine.
Both are real answers on a post-#8 tree, which is why this is one test and not two. It needs neither torch nor robomimic, so it also executes in the hardware-free CI job. """ r = _run(""" import json from rise_stack import which_scorer info = which_scorer.resolve() rc = which_scorer.main([]) print("RC", rc) print("JSON", json.dumps(info)) """) assert r.returncode == 0, f"which_scorer itself raised:\\n{r.stdout}\\n{r.stderr}" info = json.loads([l for l in r.stdout.splitlines() if l.startswith("JSON ")][0][5:]) rc = int([l for l in r.stdout.splitlines() if l.startswith("RC ")][0][3:]) assert info["vendored"] is False, ( f"rise_stack/rsm/ is absent from this tree but which_scorer reports vendored: {info}") if info["module"] is not None: assert info["module"] == "robomimic.algo.rsm_scorer", ( f"the only post-#8 implementation is the fork's, but the winner is {info['module']}") assert rc == 0, f"a scorer resolved but the command exited {rc}" assert info["rsm_libero_dir"] and info["rsm_libero_source"] != "unknown", ( "the fork resolved without naming where it imports model/train_rsm/is_ope/data from -- " f"that is the 2026-09-24 defect exactly: {info}") else: assert rc == 1, f"no scorer resolved but the command exited {rc}, so a script would not notice" assert "did not import" not in r.stdout, ( "no vendored copy exists, yet the hint blames one for failing to import:\\n" + r.stdout) assert "robomimic" in r.stdout and "SETUP.md" in r.stdout, ( "post-#8 the repair is 'install the patched RISE robomimic (see SETUP.md)' and the " "command does not say so, so the reader is left to guess:\\n" + r.stdout)'''
ANCHORS = [ ("@pytest.mark.parametrize(\"env_extra,want_why\", [", "@vendored_only\n"), ("def test_rsm_libero_is_the_vendored_copy_when_nothing_is_configured():", "@vendored_only\n"), ("def test_dependency_report_does_not_call_the_vendored_scorer_missing():", "@vendored_only\n"), ("def test_which_scorer_reports_where_rsm_libero_came_from():", "@vendored_only\n"),]
def main(argv): if len(argv) != 2: print("usage: patchexport_livemark.py <tests/test_rise_stack_rsm_libero_live.py>") return 2 p = Path(argv[1]) text = p.read_text() if "VENDORED_PRESENT" in text: print(f"ALREADY MARKED: {p} -- nothing to do") return 0
anchor = 'VENDORED_LIBERO = RSM_DIR / "rsm_libero"\n' if text.count(anchor) != 1: print(f"REFUSED: {anchor.strip()!r} appears {text.count(anchor)} times, expected 1") return 3 text = text.replace(anchor, anchor + MARKS, 1)
for target, deco in ANCHORS: if text.count(target) != 1: print(f"REFUSED: anchor {target!r} appears {text.count(target)} times, expected 1") return 3 text = text.replace(target, deco + target, 1)
text = text.rstrip("\n") + "\n" + NEW_TEST p.write_text(text) print(f"MARKED {p}: 4 vendored_only sites, 1 new fork_only test") return 0
if __name__ == "__main__": raise SystemExit(main(sys.argv))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230#!/usr/bin/env bash# rsm_real#5 run 32 -- TEST the candidate repair for the seven live guards before offering it to #11.## The measured problem (LSF 1908601, #11 at 2dc85c8b): on the six-way merged tree, seven tests in# tests/test_rise_stack_rsm_libero_live.py fail with ModuleNotFoundError: No module named# 'rise_stack.rsm' -- the package PR #8 deletes. Red for a tree that is correct.## The repair is NOT just a skipif. A skipif alone takes that file from 14 executed tests to 7 on the# tree we ship, and the claim it exists for -- a scorer resolves from a clean clone, or the command# says exactly what is missing -- would have nothing executing it there. So: mark the seven, AND add# one live fork_only test that runs exactly where they stop.## Acceptance, all of which must hold before this is offered:# A no collected id is skipped on BOTH legitimate trees (nothing goes dark)# B each guard file still executes something on the merged tree# C the merged tree has 0 failures (7 -> 0, the point of the exercise)# H the NEW fork_only test is 'passed' on the merged tree and 'skipped' on #11's own tree# Controls, every one of which must FIRE (a check that cannot go red proves nothing):# D a half-deleted rise_stack/rsm/ is still RED, not skipped -- my marks must not weaken #11's guard# I a which_scorer whose post-#8 hint says nothing -> the new test must FAIL# J a which_scorer that claims 'vendored' with no vendored copy -> the new test must FAIL# K the skipif-ONLY repair (new test deleted) -> check H must REFUSE## Read-only w.r.t. GitHub: fetches, pushes nothing, writes only under SCRATCH.set -uo pipefailsource /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_resolve.shSCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run101}VENV=${VENV:-/proj/dmfexp/zwhong/scratch_patchexport/run29/venv_ci}MARKER=/proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_livemark.pyexport GIT_TERMINAL_PROMPT=0 PYTHONDONTWRITEBYTECODE=1 OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1FILES="tests/test_rise_stack_rsm_libero_closure.py tests/test_rise_stack_rsm_libero_live.py"NEW=test_without_the_vendored_copy_the_reader_is_sent_to_the_forkscrub(){ sed 's#https://[^@]*@#https://<redacted>@#g'; }hdr(){ echo; echo "=================== $* ==================="; date -u; }die(){ echo "LIVEMARK FAILED: $*"; exit 7; }PY=$VENV/bin/python; [ -x "$PY" ] || die "no venv at $VENV"export PE_PY=$PYmkdir -p "${SCRATCH:?}" || exit 1
hdr "0 context"echo "host=$(hostname) job=${LSB_JOBID:-none} scratch=$SCRATCH py=$("$PY" -V 2>&1)"
clone(){ local W=$1 TOK TOK=$(grep -m1 'https://richardrl:' ~/.git-credentials | sed -E 's|https://richardrl:([^@]*)@.*|\1|') [ -n "$TOK" ] || die "no token" rm -rf "${W:?}"; git init --quiet "$W" || exit 1 printf '[remote "origin"]\n\turl = https://richardrl:%s@github.com/jmarangola/rsm_real.git\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n' "$TOK" >> "$W/.git/config" unset TOK git -C "$W" fetch --quiet origin 2>&1 | scrub || die "fetch failed" git -C "$W" config user.email noreply@anthropic.com git -C "$W" config user.name "richardrl"}
census(){ local T=$1 TAG=$2 f present="" for f in $FILES; do [ -e "$T/$f" ] && present="$present $f"; done [ -n "${present// }" ] || die "$TAG: no guard file in this tree" ( cd "$T" && PYTHONPATH= "$PY" -m pytest -q -p no:cacheprovider --tb=no \ --junitxml="$SCRATCH/$TAG.xml" $present >"$SCRATCH/$TAG.log" 2>&1 ) "$PY" - "$SCRATCH/$TAG.xml" "$SCRATCH/$TAG.tsv" <<'PYX'import sys, xml.etree.ElementTree as ETxml, out = sys.argv[1], sys.argv[2]rows = []for tc in ET.parse(xml).getroot().iter("testcase"): kids = {k.tag for k in tc} o = ("skipped" if "skipped" in kids else "failed" if "failure" in kids else "error" if "error" in kids else "passed") rows.append(("%s::%s" % (tc.get("classname"), tc.get("name")), o))assert rows, "junit xml has zero testcases -- the run collected nothing"open(out, "w").write("".join("%s\t%s\n" % r for r in rows))print(" collected %d: %s" % (len(rows), " ".join( "%s=%d" % (o, sum(1 for _, x in rows if x == o)) for o in ("passed","failed","error","skipped"))))PYX [ -s "$SCRATCH/$TAG.tsv" ] || die "$TAG: census produced no rows (see $SCRATCH/$TAG.log)"}outcome(){ awk -F'\t' -v g="::$2\$" '$1 ~ g {print $2}' "$SCRATCH/$1.tsv" | head -1; }
hdr "1 live heads"W=$SCRATCH/mergedclone "$W"MAIN=$(git -C "$W" rev-parse origin/main)echo " main = ${MAIN:0:8} $(git -C "$W" log -1 --format='%ad %an | %s' --date=iso origin/main)"SC_HEAD=$(git -C "$W" ls-remote origin refs/pull/11/head | awk '{print $1}')echo " #11 = ${SC_HEAD:0:8}"
hdr "2 the six-way trial merge (shared pe_trial_merge)"pe_trial_merge "$W" origin/main || die "trial merge refused/failed"printf '%s' "$PE_TRIAL_SHAPE" | sed 's/^/ /'[ -d "$W/rise_stack/rsm" ] && die "the merged tree still has rise_stack/rsm/ -- #8 must delete it"echo " merged = $(git -C "$W" rev-parse --short HEAD), no rise_stack/rsm/"
hdr "3 venv sync"pe_ci_venv_sync "$W" || die "venv sync failed"
hdr "4 #11 alone, and the patch generated ON #11's own file"V=$SCRATCH/pr11; rm -rf "${V:?}"git -C "$W" worktree add --quiet --detach "$V" pr-11 2>&1 | scrub || die "cannot check out pr-11"[ -d "$V/rise_stack/rsm" ] || die "#11 alone has no rise_stack/rsm/ -- the two trees are not distinct"cmp -s "$V/tests/test_rise_stack_rsm_libero_live.py" "$W/tests/test_rise_stack_rsm_libero_live.py" \ || die "the live file differs between #11 and the merged tree -- generate the patch against #11 and re-check"echo " the live file is byte-identical on both trees, so one patch serves both""$PY" "$MARKER" "$V/tests/test_rise_stack_rsm_libero_live.py" | sed 's/^/ /' || die "marker refused"( cd "$V" && git diff -- tests/test_rise_stack_rsm_libero_live.py ) > "$SCRATCH/live_marks.patch"[ -s "$SCRATCH/live_marks.patch" ] || die "the marker produced an empty diff"echo " patch: $(grep -c '^+' "$SCRATCH/live_marks.patch") added lines, $(grep -c '^-' "$SCRATCH/live_marks.patch") removed"( cd "$W" && git apply --check "$SCRATCH/live_marks.patch" ) || die "the patch does not apply to the merged tree"( cd "$W" && git apply "$SCRATCH/live_marks.patch" ) || die "git apply failed on the merged tree"echo " applied to the merged tree too"
hdr "5 which_scorer on the merged tree, so the mutants target the branch that actually runs"( cd "$W" && PYTHONPATH="$W" "$PY" -m rise_stack.which_scorer ) > "$SCRATCH/whichscorer.txt" 2>&1WS_RC=$?echo " rc=$WS_RC"; sed 's/^/ /' "$SCRATCH/whichscorer.txt"[ "$WS_RC" = 1 ] || die "the fork imports in this venv (rc=$WS_RC): controls I/J below target the \no-winner branch, so refusing rather than reporting mutants that were never exercised"
hdr "6 census on both trees, WITH the patch"echo " merged:"; census "$W" mergedecho " pr-11 :"; census "$V" pr11
hdr "7 check A -- no test skipped on BOTH trees""$PY" - "$SCRATCH/merged.tsv" "$SCRATCH/pr11.tsv" <<'PYX' || die "check A: a guard asserts nothing on either tree"import sysdef rd(p): return dict(l.rstrip("\n").split("\t") for l in open(p))m, v = rd(sys.argv[1]), rd(sys.argv[2])ids = sorted(set(m) | set(v))dead = [i for i in ids if m.get(i,"skipped")=="skipped" and v.get(i,"skipped")=="skipped"]only_m = [i for i in ids if m.get(i,"skipped")!="skipped" and v.get(i,"skipped")=="skipped"]only_v = [i for i in ids if v.get(i,"skipped")!="skipped" and m.get(i,"skipped")=="skipped"]print(" %d distinct ids; merged runs %d, pr-11 runs %d" % (len(ids), sum(1 for i in ids if m.get(i,"skipped")!="skipped"), sum(1 for i in ids if v.get(i,"skipped")!="skipped")))print(" fork_only half (merged only): %d" % len(only_m))for i in only_m: print(" ", i)print(" vendored_only half (pr-11 only): %d" % len(only_v))for i in only_v: print(" ", i)if dead: print(" SKIPPED ON BOTH:"); [print(" ", i) for i in dead]sys.exit(1 if dead else 0)PYXecho " OK A"
hdr "8 check B -- each guard file executes something on the merged tree"for f in $FILES; do pat=$(echo "${f%.py}" | tr / .) tot=$(awk -F'\t' -v p="$pat::" 'index($1,p)==1' "$SCRATCH/merged.tsv" | wc -l) [ "$tot" -gt 0 ] || die "check B: no census rows for $f -- NOT COLLECTED, which is not 'skipped'" n=$(awk -F'\t' -v p="$pat::" 'index($1,p)==1 && $2 != "skipped"' "$SCRATCH/merged.tsv" | wc -l) [ "$n" -gt 0 ] || die "check B: $f is collected ($tot) but WHOLLY SKIPPED on the merged tree" echo " OK B $f: $tot collected, $n executed on the merged tree"done
hdr "9 check C -- the merged tree has 0 failures"bad=$(awk -F'\t' '$2 != "passed" && $2 != "skipped"' "$SCRATCH/merged.tsv")[ -z "$bad" ] || { echo "$bad" | sed 's/^/ /'; die "check C: the merged tree still fails $(echo "$bad"|wc -l) test(s)"; }echo " OK C merged: $(awk -F'\t' '$2=="passed"' "$SCRATCH/merged.tsv"|wc -l) passed, $(awk -F'\t' '$2=="skipped"' "$SCRATCH/merged.tsv"|wc -l) skipped, 0 failed"echo " pr-11 : $(awk -F'\t' '$2=="passed"' "$SCRATCH/pr11.tsv"|wc -l) passed, $(awk -F'\t' '$2=="skipped"' "$SCRATCH/pr11.tsv"|wc -l) skipped, $(awk -F'\t' '$2!="passed"&&$2!="skipped"' "$SCRATCH/pr11.tsv"|wc -l) failed"
hdr "10 check H -- the new fork_only test runs where the seven stop"om=$(outcome merged "$NEW"); ov=$(outcome pr11 "$NEW")[ "$om" = passed ] || die "check H: the new test is '$om' on the merged tree, not passed"[ "$ov" = skipped ] || die "check H: the new test is '$ov' on #11's tree, not skipped"echo " OK H $NEW: merged=passed, pr-11=skipped"for t in test_rsm_libero_is_the_vendored_copy_when_nothing_is_configured test_which_scorer_reports_where_rsm_libero_came_from; do echo " $t: merged=$(outcome merged $t), pr-11=$(outcome pr11 $t)"done
hdr "11 control D -- a HALF-DELETED rise_stack/rsm/ is still RED"H=$SCRATCH/half; rm -rf "${H:?}"; cp -a "$V" "$H"; rm -rf "$H/.git"[ -f "$H/rise_stack/rsm/rsm_scorer.py" ] || die "control D: nothing to half-delete"rm -f "$H/rise_stack/rsm/rsm_scorer.py"census "$H" half >/dev/nullo=$(outcome half test_a_half_deleted_vendored_copy_is_red_rather_than_skipped)[ "$o" = failed ] || die "control D: half-deleted tree reported '$o', not failed -- my marks weakened #11's guard"echo " OK D the half-deleted tree is red ($(awk -F'\t' '$2=="skipped"' "$SCRATCH/half.tsv"|wc -l) siblings skip there)"
mutate(){ # mutate <tag> <python-edit> local TAG=$1 EDIT=$2 M=$SCRATCH/$1 rm -rf "${M:?}"; cp -a "$W" "$M"; rm -rf "$M/.git" "$PY" - "$M/rise_stack/which_scorer.py" "$EDIT" <<'PYX' || die "$TAG: the mutation did not apply"import sysp, edit = sys.argv[1], sys.argv[2]src = open(p).read()old, new = edit.split("||")assert src.count(old) == 1, "mutation anchor %r appears %d times" % (old, src.count(old))open(p, "w").write(src.replace(old, new, 1))print(" mutated: %r -> %r" % (old[:60], new[:60]))PYX census "$M" "$TAG" >/dev/null}
hdr "12 control I -- a post-#8 hint that says nothing must make the new test FAIL"mutate mut_hint 'if not vendored_file.exists():||if False:'o=$(outcome mut_hint "$NEW")[ "$o" = failed ] || die "control I: with the post-#8 hint removed the new test reported '$o' -- it does not guard the hint"echo " OK I hint removed -> $NEW failed"grep -m1 -A2 "$NEW" "$SCRATCH/mut_hint.log" | sed 's/^/ /' | head -3
hdr "13 control J -- 'vendored' claimed with no vendored copy must make the new test FAIL"mutate mut_vend '"module": None, "file": None, "vendored": False,||"module": None, "file": None, "vendored": True,'o=$(outcome mut_vend "$NEW")[ "$o" = failed ] || die "control J: a false 'vendored: True' reported '$o' -- the new test does not guard it"echo " OK J false vendored -> $NEW failed"
hdr "14 control K -- the skipif-ONLY repair must make check H refuse"K=$SCRATCH/skiponly; rm -rf "${K:?}"; cp -a "$W" "$K"; rm -rf "$K/.git""$PY" - "$K/tests/test_rise_stack_rsm_libero_live.py" <<'PYX' || die "control K: could not strip the new test"import sysp = sys.argv[1]; src = open(p).read()i = src.index("@fork_only\ndef test_without_the_vendored_copy")open(p, "w").write(src[:i])print(" stripped the fork_only test, leaving the skipif-only repair")PYXcensus "$K" skiponly >/dev/nullo=$(outcome skiponly "$NEW")[ -z "$o" ] || die "control K: the new test is still present ('$o') after stripping it"liveex=$(awk -F'\t' -v p="tests.test_rise_stack_rsm_libero_live::" 'index($1,p)==1 && $2!="skipped"' "$SCRATCH/skiponly.tsv" | wc -l)liveall=$(awk -F'\t' -v p="tests.test_rise_stack_rsm_libero_live::" 'index($1,p)==1' "$SCRATCH/skiponly.tsv" | wc -l)echo " OK K skipif-only: check H finds no '$NEW' row, and the live file drops to $liveex executed of $liveall"echo " (with the new test: $(awk -F'\t' -v p="tests.test_rise_stack_rsm_libero_live::" 'index($1,p)==1 && $2!="skipped"' "$SCRATCH/merged.tsv" | wc -l) executed of $(awk -F'\t' -v p="tests.test_rise_stack_rsm_libero_live::" 'index($1,p)==1' "$SCRATCH/merged.tsv" | wc -l))"
hdr "15 re-poll and keep the patch"git -C "$W" fetch --quiet origin 2>&1 | scrubecho " main now = $(git -C "$W" rev-parse --short origin/main) (was ${MAIN:0:7})"echo " #11 now = $(git -C "$W" ls-remote origin refs/pull/11/head | cut -c1-8) (was ${SC_HEAD:0:8})"cp "$SCRATCH/live_marks.patch" /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_livemark.patchecho " patch kept at scripts/real/patchexport_livemark.patch"git -C "$W" worktree remove --force "$V" >/dev/null 2>&1 || true
hdr "LIVEMARK OK -- A/B/C/H pass, controls D/I/J/K all fired"1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374#!/usr/bin/env bash# rsm_real#5 run 32 -- the BEFORE/AFTER pair for the live-guard repair, measured with the CI differ# (`pe_ci_baseline`) rather than the two-file census, so the claim "the merged tree adds no failure"# is made against the whole set the merged workflow actually runs.## Same tree, twice: once as it is (expect the seven), once with scripts/real/patchexport_livemark.patch# applied (expect none). Both numbers in one log at one pair of heads, because a before taken at a# different head is not a before.set -uo pipefailsource /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_resolve.shSCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run102}VENV=${VENV:-/proj/dmfexp/zwhong/scratch_patchexport/run29/venv_ci}PATCH=/proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_livemark.patchexport GIT_TERMINAL_PROMPT=0 PYTHONDONTWRITEBYTECODE=1 OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1scrub(){ sed 's#https://[^@]*@#https://<redacted>@#g'; }hdr(){ echo; echo "=================== $* ==================="; date -u; }die(){ echo "LIVEMARK-CI FAILED: $*"; exit 7; }PY=$VENV/bin/python; [ -x "$PY" ] || die "no venv at $VENV"export PE_PY=$PY[ -s "$PATCH" ] || die "no patch at $PATCH"mkdir -p "${SCRATCH:?}" || exit 1
hdr "0 context"echo "host=$(hostname) job=${LSB_JOBID:-none} scratch=$SCRATCH py=$("$PY" -V 2>&1)"
clone(){ local W=$1 TOK TOK=$(grep -m1 'https://richardrl:' ~/.git-credentials | sed -E 's|https://richardrl:([^@]*)@.*|\1|') [ -n "$TOK" ] || die "no token" rm -rf "${W:?}"; git init --quiet "$W" || exit 1 printf '[remote "origin"]\n\turl = https://richardrl:%s@github.com/jmarangola/rsm_real.git\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n' "$TOK" >> "$W/.git/config" unset TOK git -C "$W" fetch --quiet origin 2>&1 | scrub || die "fetch failed" git -C "$W" config user.email noreply@anthropic.com git -C "$W" config user.name "richardrl"}
hdr "1 heads and the six-way merge"W=$SCRATCH/merged; clone "$W"MAIN=$(git -C "$W" rev-parse origin/main)SC=$(git -C "$W" ls-remote origin refs/pull/11/head | awk '{print $1}')echo " main = ${MAIN:0:8} #11 = ${SC:0:8}"pe_trial_merge "$W" origin/main || die "trial merge refused"printf '%s' "$PE_TRIAL_SHAPE" | sed 's/^/ /'[ -d "$W/rise_stack/rsm" ] && die "merged tree still has rise_stack/rsm/"MW=$SCRATCH/mainonly; rm -rf "${MW:?}"git -C "$W" worktree add --quiet --detach "$MW" origin/main 2>&1 | scrub || die "cannot check out main"pe_ci_venv_sync "$W" || die "venv sync failed"
hdr "2 BEFORE -- the merged tree as it is"BEFORE_RC=0pe_ci_baseline "$W" "$MW" || BEFORE_RC=1BEFORE_NEW=$PE_CI_NEWecho " before: rc=$BEFORE_RC, $(printf '%s\n' "$BEFORE_NEW" | sed '/^$/d' | wc -l) NEW failure(s)"[ "$BEFORE_RC" = 1 ] || die "the BEFORE run is already green -- the subject of this repair is gone; re-read the heads"printf '%s\n' "$BEFORE_NEW" | sed '/^$/d' | grep -qv "test_rise_stack_rsm_libero_live" \ && die "the BEFORE failures are not all in the live guard file, so this patch is not the whole repair"echo " OK every BEFORE failure is in tests/test_rise_stack_rsm_libero_live.py"
hdr "3 apply the patch"( cd "$W" && git apply "$PATCH" ) || die "the patch does not apply to the merged tree"git -C "$W" diff --stat -- tests/test_rise_stack_rsm_libero_live.py | sed 's/^/ /'
hdr "4 AFTER -- the same tree, the same CI set, the same baseline"AFTER_RC=0pe_ci_baseline "$W" "$MW" || AFTER_RC=1[ "$AFTER_RC" = 0 ] || { printf '%s\n' "$PE_CI_NEW" | sed 's/^/ /'; die "the patched tree STILL adds failures"; }
hdr "5 the pair"echo " BEFORE: $(printf '%s\n' "$BEFORE_NEW" | sed '/^$/d' | wc -l) new failures over main"printf '%s\n' "$BEFORE_NEW" | sed '/^$/d' | sed 's/^/ /'echo " AFTER : 0 new failures over main (merged run: $PE_CI_TAIL)"git -C "$W" worktree remove --force "$MW" >/dev/null 2>&1 || truehdr "LIVEMARK-CI OK"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141#!/usr/bin/env bash# rsm_real#5 -- gate the MERGE RESULT, not just the branches.## Five PRs (#6 -> #7 -> #8 -> #9 -> #10) are open against main and each one was validated on its own# branch. Nobody has yet executed the thing the owner will actually do: merge them, in order, into# main, and build from the result. GitHub says "mergeable: clean" for each, but that is computed# against main as it stands TODAY and pairwise -- it is not a statement that the five together build# an environment. This script executes the whole sequence and then runs the full setup gate on the# merged tree.## It also test-merges the SELFCONTAINED stream's `rise-stack-scaffold`, which edits# scripts/check_env.py as my branches do, so the reconciliation warning I posted to #4 is backed by# an executed merge rather than by reading both diffs.## Credentials: `credential.helper=store` does NOT authenticate this repo (measured -- a plain# `git ls-remote https://github.com/jmarangola/rsm_real.git` returns "Repository not found" both on# the login node and on a compute node, with and without an explicit --file, while the token in# ~/.git-credentials is byte-identical to the one the working checkouts embed in their remote URL).# So the remote is written into .git/config with a shell redirect rather than passed as an argument:# the token then never appears in argv (visible in `ps` on a shared node), never in this file, and# every git line printed is scrubbed on top of that.set -uo pipefailROOT=/proj/dmfexp/zwhong/rsm_riseSCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run13}PRS=${PRS:-"6 7 8 9 10"}export GIT_TERMINAL_PROMPT=0scrub(){ sed 's#https://[^@]*@#https://<redacted>@#g'; }hdr(){ echo; echo "=================== $* ==================="; date -u; }rc_all=0chk(){ if [ "$1" -ne 0 ]; then echo "STEP FAILED rc=$1: $2"; rc_all=1; fi; }mkdir -p "${SCRATCH:?}" || exit 1MERGED=$SCRATCH/merged
hdr "0 context"echo "host=$(hostname) job=${LSB_JOBID:-none} scratch=$SCRATCH prs='$PRS'"df -h "$SCRATCH" | tail -1
hdr "1 fresh clone of main from GitHub"TOK=$(grep -m1 'https://richardrl:' ~/.git-credentials | sed -E 's|https://richardrl:([^@]*)@.*|\1|')[ -n "$TOK" ] || { echo "NO TOKEN in ~/.git-credentials"; exit 1; }rm -rf "${MERGED:?}"git init --quiet "$MERGED" || exit 1printf '[remote "origin"]\n\turl = https://richardrl:%s@github.com/jmarangola/rsm_real.git\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n' "$TOK" >> "$MERGED/.git/config"unset TOKgit -C "$MERGED" fetch --quiet origin main 2>&1 | scrubgit -C "$MERGED" checkout --quiet -b main FETCH_HEAD 2>&1 | scrub[ -f "$MERGED/README.md" ] || { echo "CLONE/FETCH FAILED -- no worktree"; exit 1; }BASE=$(git -C "$MERGED" rev-parse HEAD)echo "main = $BASE $(git -C "$MERGED" log -1 --pretty=%s)"git -C "$MERGED" config user.email "noreply@anthropic.com"git -C "$MERGED" config user.name "merge gate"
hdr "2 merge each PR head, in the stated order"# A conflict here is the finding: report which files, abort that one merge, and keep the sequence# honest by stopping rather than merging the rest onto a half-resolved tree.MERGED_OK=""for n in $PRS; do git -C "$MERGED" fetch --quiet origin "pull/$n/head:pr-$n" 2>&1 | scrub sha=$(git -C "$MERGED" rev-parse --short "pr-$n" 2>/dev/null) if [ -z "$sha" ]; then echo " #$n FETCH FAILED"; rc_all=1; break; fi out=$(git -C "$MERGED" merge --no-ff --no-edit -m "merge PR #$n" "pr-$n" 2>&1) if [ $? -eq 0 ]; then echo " #$n $sha MERGED CLEAN ($(echo "$out" | tail -1))" MERGED_OK="$MERGED_OK $n" else echo " #$n $sha CONFLICT:" git -C "$MERGED" diff --name-only --diff-filter=U | sed 's/^/ /' git -C "$MERGED" merge --abort rc_all=1 echo " stopping the sequence here; the remaining PRs are not merged onto a conflicted tree" break fidoneecho "merged in order:$MERGED_OK"echo "result HEAD = $(git -C "$MERGED" rev-parse --short HEAD)"echo "--- merged tree vs main ---"git -C "$MERGED" diff --stat "$BASE" HEAD | tail -3
hdr "3 is the merged tree the same content as PR #10 alone?"# #10's branch was built on a merge of #6/#7/#8, so if the five-way merge lands on the same tree,# then merge ORDER cannot lose content and the owner has one less thing to get right.if git -C "$MERGED" rev-parse pr-10 >/dev/null 2>&1; then d=$(git -C "$MERGED" diff --name-only pr-10 HEAD) if [ -z "$d" ]; then echo "IDENTICAL: merged(#6..#10) tree == PR #10 head tree -- no content depends on merge order" else echo "DIFFERENT -- files only reachable via the other PRs (expected: #9's mimicgen export):" echo "$d" | sed 's/^/ /' fifi
hdr "4 test-merge the SELFCONTAINED branch (rise-stack-scaffold) onto the result"# Reported to #4 as a reading of two diffs; here it is executed. Done on a throwaway branch and# always aborted, so the tree that gets built below is the five-PR merge and nothing else.git -C "$MERGED" fetch --quiet origin rise-stack-scaffold 2>&1 | scrubif git -C "$MERGED" rev-parse origin/rise-stack-scaffold >/dev/null 2>&1; then echo "rise-stack-scaffold = $(git -C "$MERGED" rev-parse --short origin/rise-stack-scaffold)" git -C "$MERGED" checkout --quiet -b _recon_probe if git -C "$MERGED" merge --no-commit --no-ff origin/rise-stack-scaffold >/dev/null 2>&1; then echo "RECONCILIATION: merges clean by git's own rules (textually disjoint edits)." echo " NOTE this is NOT a semantic all-clear: a clean textual merge of two edits to" echo " scripts/check_env.py can still drop neither and still be wrong only if one side" echo " reverted the other, which it does not here -- both sides' hunks are present below." else echo "RECONCILIATION: CONFLICT, files:" git -C "$MERGED" diff --name-only --diff-filter=U | sed 's/^/ /' fi echo "--- does the merged check_env.py keep BOTH sides? ---" if [ -f "$MERGED/scripts/check_env.py" ]; then echo -n " pin_of fix (mine, 'commit =' parse): "; grep -c "^commit\|commit = \|--print-pin" "$MERGED/scripts/check_env.py" echo -n " CPU-threads INFO row (theirs): "; grep -ci "cpu.*thread" "$MERGED/scripts/check_env.py" fi git -C "$MERGED" merge --abort 2>/dev/null git -C "$MERGED" checkout --quiet - git -C "$MERGED" branch -D _recon_probe >/dev/null 2>&1 git -C "$MERGED" status --porcelain | head -5else echo "rise-stack-scaffold not found on the remote -- skipping"fi
hdr "5 the pin regression test must pass on the MERGED scripts, before spending a build on them"if [ -f "$MERGED/tests/test_rise_stack_pins.py" ]; then for f in "$MERGED"/rise_stack/*/UPSTREAM_COMMIT.txt; do echo -n " $(basename "$(dirname "$f")"): " bash "$MERGED/scripts/setup_env.sh" --print-pin "$(basename "$(dirname "$f")")" 2>&1 | tail -1 doneelse echo "tests/test_rise_stack_pins.py NOT in the merged tree -- #10 did not merge"; rc_all=1fi
hdr "6 full setup gate on the merged tree"if [ "$rc_all" -eq 0 ]; then SCRATCH=$SCRATCH SRC=$MERGED bash "$ROOT/scripts/real/patchexport_setup_run.sh" chk $? "patchexport_setup_run.sh on the merged tree"else echo "SKIPPED: the merge sequence itself failed, so a build result would not mean anything."fi
hdr "done"echo "OVERALL rc=$rc_all"exit $rc_all123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125#!/usr/bin/env bash# rsm_real#5 -- which merge BUTTON the owner presses is not a detail.## The repo has all three enabled (measured via the API: allow_merge_commit, allow_squash_merge and# allow_rebase_merge are all true). My five PRs are not independent: #8 was branched on top of #7,# and #10's branch carries a merge of #6/#7/#8. A merge commit preserves those ancestries, so git# knows what is already in; a SQUASH merge rewrites each PR into one new commit with no ancestry# link, so the next PR in the stack re-applies content main already has -- which is how a stack of# PRs that each say "mergeable: clean" produces a conflict on the second or third button press.## This probe presses every button, in a scratch clone, and reports what actually happens. It builds# nothing: it is pure git and runs in about a minute. The build gate on the merge-commit path is# scripts/real/patchexport_merge_gate.sh.## Credentials: see the note in patchexport_merge_gate.sh -- credential.helper=store does not# authenticate this repo, so the remote goes into .git/config via a redirect and never into argv.set -uo pipefailSCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run14}PRS=${PRS:-"6 7 8 9 10"}export GIT_TERMINAL_PROMPT=0scrub(){ sed 's#https://[^@]*@#https://<redacted>@#g'; }hdr(){ echo; echo "=================== $* ==================="; }# rc_all is reserved for things that are WRONG: the merge-commit path (the one I recommend to the# owner) conflicting, or a completed sequence whose tree lacks a deliverable file. A squash conflict# is a FINDING about which button to press, not a failure of this job, so it is counted separately.FINDINGS=0mkdir -p "${SCRATCH:?}" || exit 1R=$SCRATCH/proberc_all=0
hdr "0 context"echo "host=$(hostname) job=${LSB_JOBID:-none} scratch=$SCRATCH prs='$PRS'"
hdr "1 clone main + every PR head"TOK=$(grep -m1 'https://richardrl:' ~/.git-credentials | sed -E 's|https://richardrl:([^@]*)@.*|\1|')[ -n "$TOK" ] || { echo "NO TOKEN"; exit 1; }rm -rf "${R:?}"git init --quiet "$R" || exit 1printf '[remote "origin"]\n\turl = https://richardrl:%s@github.com/jmarangola/rsm_real.git\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n' "$TOK" >> "$R/.git/config"unset TOKgit -C "$R" config user.email "noreply@anthropic.com"; git -C "$R" config user.name "merge probe"git -C "$R" fetch --quiet origin main 2>&1 | scrubgit -C "$R" checkout --quiet -b main FETCH_HEAD 2>&1 | scrub# README.md, not scripts/ -- `main` has NO top-level scripts/ directory (measured: it arrives only# with PR #6/#10). Checking for scripts/ here made LSF 1889836 report "FETCH FAILED" on a clone that# was complete and correct.[ -f "$R/README.md" ] || { echo "FETCH FAILED -- no worktree"; exit 1; }echo "main = $(git -C "$R" rev-parse --short HEAD)"for n in $PRS; do git -C "$R" fetch --quiet origin "pull/$n/head:pr-$n" 2>&1 | scrub echo " #$n = $(git -C "$R" rev-parse --short "pr-$n") $(git -C "$R" log -1 --pretty=%s "pr-$n" | cut -c1-60)"done
# The files a clone must end up with for the deliverable to exist at all. Checked after every# scenario, because "merged without conflict" and "the result contains the sources" are different# claims and only the second one matters to a labmate.WANT="rise_stack/openpi/rise_on_pi05.patchrise_stack/robomimic/rise_on_robomimic.patchrise_stack/rsm_libero/rise_on_rsm_libero.patchrise_stack/mimicgen/rise_on_mimicgen.patchrise_stack/UPSTREAM_PINS.mdscripts/setup_env.shscripts/check_env.pytests/test_rise_stack_pins.pySETUP.md"
report_tree(){ # $1 = mode, $2 = 1 if the sequence completed, $3 = 1 if held to the missing-files bar local mode="$1" done_ok="$2" strict="$3" miss=0 f while read -r f; do [ -z "$f" ] && continue if [ ! -f "$R/$f" ]; then echo " MISSING $f"; miss=$((miss+1)); fi done <<< "$WANT" echo " required deliverable files missing: $miss" local d; d=$(git -C "$R" diff --name-only HEAD pr-10 | wc -l) echo " files differing from PR #10's tree: $d" # Only the full merge-commit sequence, run to completion, is held to the missing-files bar. # The single-PR scenarios are EXPECTED to be short: #9 (mimicgen) is not an ancestor of #10, so # merging #10 alone must come out without rise_stack/mimicgen. That is the point of running them. if [ "$miss" -ne 0 ] && [ "$done_ok" -eq 1 ] && [ "$strict" -eq 1 ]; then rc_all=1; fi if [ "$miss" -ne 0 ] && [ "$strict" -ne 1 ]; then FINDINGS=$((FINDINGS+1)); fi return 0}
scenario(){ # $1 = strict, $2 = mode (merge|squash), $3 = branch name, $4.. = pr numbers local strict="$1" mode="$2" br="$3"; shift 3 hdr "scenario: $mode $*" git -C "$R" checkout --quiet main git -C "$R" branch -D "$br" >/dev/null 2>&1 git -C "$R" checkout --quiet -b "$br" main local n ok=1 for n in "$@"; do if [ "$mode" = squash ]; then if git -C "$R" merge --squash "pr-$n" >/dev/null 2>&1; then git -C "$R" commit --quiet -m "squash PR #$n" >/dev/null 2>&1 echo " #$n squash OK" else echo " #$n SQUASH CONFLICT:" git -C "$R" diff --name-only --diff-filter=U | sed 's/^/ /' git -C "$R" merge --abort 2>/dev/null; git -C "$R" reset --hard --quiet ok=0; FINDINGS=$((FINDINGS+1)); break fi else if git -C "$R" merge --no-ff --no-edit -m "merge PR #$n" "pr-$n" >/dev/null 2>&1; then echo " #$n merge OK" else echo " #$n MERGE CONFLICT:" git -C "$R" diff --name-only --diff-filter=U | sed 's/^/ /' git -C "$R" merge --abort 2>/dev/null ok=0; rc_all=1; break fi fi done [ "$ok" -eq 1 ] && echo " all of '$*' applied by $mode" || echo " sequence stopped early" report_tree "$mode" "$ok" "$strict"}
scenario 1 merge s_merge_all $PRS # the recommended path: must be clean AND completescenario 0 squash s_squash_all $PRS # what happens if the owner presses "Squash and merge"scenario 0 merge s_merge_10 10 # does #10 alone carry everything? (it must not: #9 is not in it)scenario 0 squash s_squash_10 10
hdr "done"echo "squash/ordering findings: $FINDINGS (these are advice for the owner, not job failures)"echo "OVERALL rc=$rc_all"exit $rc_all123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181#!/usr/bin/env bash# rsm_real#5 -- the question the merge gate does NOT answer: after the resolution I published,# does #11's own CI suite still pass?## The six-way gate measures the CONFLICT set. Conflicts are not the risk here: the risk is the two# resolution steps that are not "take one side of a text conflict" --# (a) four conflicted files resolved to the #6..#10 side (SETUP.md, openpi/README.md,# scripts/check_env.py, scripts/setup_env.sh), and# (b) the scorer decision: delete rise_stack/rsm/ and collapse scorers.py to the single fork# import (run 13 measured that the vendored copy wins at runtime and lacks #8's item-3 fix).# #11 ships tests/test_rise_stack_which_scorer.py whose subject is exactly the module (b) rewrites,# and CI is green on #11's own head. Green on the head says nothing about green after the merge.# A resolution that turns a green branch red is a defect in MY runbook, and it would land on a# human who followed it. So execute the CI command, verbatim, on both trees.## Three cases, chosen so a skip cannot be mistaken for a pass:# H0 #11 head, robomimic NOT importable -- reproduces the Actions runner (baseline)# R0 RESOLVED tree, robomimic NOT importable -- a clone that has not installed the fork yet# R1 RESOLVED tree, patched fork on PYTHONPATH -- the state SETUP.md actually produces# Exit 2 (never 0) if the baseline collects nothing, if robomimic leaks into H0/R0, or if the fork# reconstruction for R1 is not the file carrying #8's item-3 fix.## Read-only w.r.t. every real repo: fetches from GitHub, works only inside SCRATCH, pushes nothing.set -uo pipefailsource /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_resolve.shROOT=/proj/dmfexp/zwhong/rsm_riseSCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run29}PRS=${PRS:-"6 7 8 9 10"}SC_PR=${SC_PR:-11}export GIT_TERMINAL_PROMPT=0 PYTHONDONTWRITEBYTECODE=1 OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1scrub(){ sed 's#https://[^@]*@#https://<redacted>@#g'; }hdr(){ echo; echo "=================== $* ==================="; date -u; }rc_all=0mkdir -p "${SCRATCH:?}" || exit 1M=$SCRATCH/mt
hdr "0 context"echo "host=$(hostname) job=${LSB_JOBID:-none} scratch=$SCRATCH"
hdr "1 fresh clone of main, fetch every PR head"TOK=$(grep -m1 'https://richardrl:' ~/.git-credentials | sed -E 's|https://richardrl:([^@]*)@.*|\1|')[ -n "$TOK" ] || { echo "NO TOKEN"; exit 1; }rm -rf "${M:?}"; git init --quiet "$M" || exit 1printf '[remote "origin"]\n\turl = https://richardrl:%s@github.com/jmarangola/rsm_real.git\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n' "$TOK" >> "$M/.git/config"unset TOKgit -C "$M" fetch --quiet origin main 2>&1 | scrubgit -C "$M" checkout --quiet -b main FETCH_HEAD 2>&1 | scrub[ -f "$M/README.md" ] || { echo "CLONE/FETCH FAILED"; exit 1; }git -C "$M" config user.email noreply@anthropic.com; git -C "$M" config user.name "merged-tests gate"for n in $PRS $SC_PR; do git -C "$M" fetch --quiet origin "pull/$n/head:pr-$n" 2>&1 | scrub echo " #$n = $(git -C "$M" rev-parse --short "pr-$n")"doneecho " main = $(git -C "$M" rev-parse --short main)"SC_SHA=$(git -C "$M" rev-parse "pr-$SC_PR")
hdr "1b staleness guard -- the side under test must BE the live PR head"LIVE=$(git -C "$M" ls-remote origin "refs/pull/$SC_PR/head" 2>/dev/null | awk '{print $1}')if [ -z "$LIVE" ] || [ "$LIVE" != "$SC_SHA" ]; then echo "STALE: fetched $(echo "$SC_SHA" | cut -c1-7) != live $(echo "${LIVE:-none}" | cut -c1-7)"; exit 2fiecho "staleness guard: OK -- sc == live head of PR #$SC_PR ($(echo "$SC_SHA" | cut -c1-7))"
hdr "2 order A merge, then the FULL published resolution (incl. the scorer decision)"for n in $PRS; do git -C "$M" merge --no-ff -m "Merge PR #$n" "pr-$n" >/dev/null 2>&1 || { echo "#$n UNEXPECTED CONFLICT"; exit 1; }; doneFIVE=$(git -C "$M" rev-parse HEAD)echo "five-way = $(git -C "$M" rev-parse --short HEAD) tree $(git -C "$M" rev-parse --short HEAD^{tree})"git -C "$M" merge --no-ff -m "Merge PR #$SC_PR" "pr-$SC_PR" >/dev/null 2>&1echo "conflicted: $(git -C "$M" diff --name-only --diff-filter=U | tr '\n' ' ')"pe_resolve "$M" "$FIVE" scripts/setup_env.sh SETUP.md rise_stack/openpi/README.md scripts/check_env.pyLEFT=$(git -C "$M" diff --name-only --diff-filter=U | tr '\n' ' ')echo "remaining unmerged after text resolution: '$LEFT'"[ -z "$LEFT" ] || { echo "RESOLUTION INCOMPLETE -- refusing to report a test result"; exit 2; }python3 - "$M/rise_stack/scorers.py" <<'PY'import re, sysp = sys.argv[1]s = open(p).read()pat = re.compile(r"[ \t]*try:\n[ \t]*from \.rsm\.rsm_scorer import ([^\n]*)\n(?:[^\n]*\n)*?[ \t]*from robomimic\.algo\.rsm_scorer import [^\n]*\n")m = pat.search(s)if not m: print("RESOLUTION PATCH FAILED: fallback block not found"); sys.exit(3)names = m.group(1).strip()indent = re.match(r"[ \t]*", m.group(0)).group(0)s = s[:m.start()] + f"{indent}from robomimic.algo.rsm_scorer import {names}\n" + s[m.end():]open(p, "w").write(s)print(f"scorers.py resolved -> single import of robomimic.algo.rsm_scorer ({names})")PY[ $? -eq 0 ] || { echo "SCORERS RESOLUTION FAILED"; exit 2; }git -C "$M" add rise_stack/scorers.pygit -C "$M" rm -rf -f --quiet rise_stack/rsm || { echo "git rm rise_stack/rsm FAILED"; exit 2; }git -C "$M" commit --quiet -m "scratch: order-A merge + published resolution" || echo " (commit skipped)"RES=$(git -C "$M" rev-parse HEAD)echo "resolved commit = $(git -C "$M" rev-parse --short HEAD) tree $(git -C "$M" rev-parse --short HEAD^{tree})"
hdr "3 the CI command, taken from the workflow file in the tree under test (not retyped)"CIFILES=$(git -C "$M" cat-file -p "$SC_SHA:.github/workflows/deployment.yml" \ | sed -n 's#^ *\(tests/test_[a-z_]*\.py\) *$#\1#p' | tr '\n' ' ')echo "CI test files ($(echo $CIFILES | wc -w)): $CIFILES"[ -n "$CIFILES" ] || { echo "could not extract the CI file list"; exit 2; }REQ=$SCRATCH/requirements-deployment.txtgit -C "$M" cat-file -p "$SC_SHA:requirements-deployment.txt" > "$REQ"echo "--- requirements-deployment.txt ---"; grep -v '^#' "$REQ" | sed '/^$/d' | sed 's/^/ /'
hdr "4 a venv with the CI dependencies (isolated; robomimic must NOT be in it)"VENV=$SCRATCH/venv_ciif [ ! -x "$VENV/bin/python" ]; then python3 -m venv "$VENV" || { echo "venv creation FAILED"; exit 2; } "$VENV/bin/python" -m pip install --quiet --upgrade pip 2>&1 | tail -2 export PIP_CACHE_DIR=$SCRATCH/pipcache "$VENV/bin/python" -m pip install --quiet -r "$REQ" "pytest==9.0.3" 2>&1 | tail -5 || { echo "pip install of requirements FAILED"; exit 2; } "$VENV/bin/python" -m pip install --quiet torch --index-url https://download.pytorch.org/whl/cpu 2>&1 | tail -5 || { echo "pip install of torch FAILED"; exit 2; }fiPY=$VENV/bin/pythonecho "interpreter: $PY ($("$PY" -V 2>&1)) [CI uses 3.10]""$PY" - <<'PY' || { echo "dependency import FAILED -- inconclusive"; exit 2; }import importlib, sysfor m in ("pytest","yaml","numpy","torch","h5py","cv2","hydra","omegaconf"): mod = importlib.import_module(m) print(" %-10s %s" % (m, getattr(mod, "__version__", "?")))PYif "$PY" -c "import robomimic" 2>/dev/null; then echo " !! robomimic IS importable in the CI venv -- H0/R0 are NOT conclusive"; rc_all=2else echo " robomimic is NOT importable here -- H0/R0 reproduce the Actions runner"fi
hdr "5 worktrees"WH=$SCRATCH/t_head; WR=$SCRATCH/t_resolvedrm -rf "$WH" "$WR"git -C "$M" worktree add --quiet --detach "$WH" "$SC_SHA" || { echo "worktree head FAILED"; exit 2; }git -C "$M" worktree add --quiet --detach "$WR" "$RES" || { echo "worktree resolved FAILED"; exit 2; }
run_case(){ # name dir extra_pythonpath local name=$1 dir=$2 pp=${3:-} hdr "6.$name dir=$(basename "$dir") PYTHONPATH=${pp:-<empty>}" ( cd "$dir" && PYTHONPATH=$pp "$PY" -m pytest -q -p no:cacheprovider $CIFILES 2>&1 ) | tail -40 | sed 's/^/ /'}
hdr "6 EXECUTIONS -- the CI command verbatim"run_case "H0 (#11 head, no robomimic = the Actions runner)" "$WH"H0LINE=$( cd "$WH" && PYTHONPATH= "$PY" -m pytest -q -p no:cacheprovider $CIFILES 2>&1 | tail -1 )run_case "R0 (RESOLVED tree, no robomimic)" "$WR"R0LINE=$( cd "$WR" && PYTHONPATH= "$PY" -m pytest -q -p no:cacheprovider $CIFILES 2>&1 | tail -1 )
hdr "7 reconstruct the patched fork the DOCUMENTED way (upstream pin + our patch) for R1"RM=$SCRATCH/robomimic_forkFORK_OK=0UP=$(git -C "$M" cat-file -p "$RES:rise_stack/robomimic/UPSTREAM_COMMIT.txt" | head -1 | tr -d '[:space:]')URL=$(git -C "$M" cat-file -p "$RES:rise_stack/robomimic/UPSTREAM_COMMIT.txt" | sed -n '2p' | tr -d '[:space:]')echo "pin=$UP url=$URL"if [ ! -f "$RM/robomimic/algo/rsm_scorer.py" ]; then rm -rf "$RM"; git init --quiet "$RM" && git -C "$RM" remote add origin "$URL" git -C "$RM" fetch --quiet --depth 1 origin "$UP" 2>&1 | scrub git -C "$RM" checkout --quiet FETCH_HEAD 2>&1 | scrub git -C "$M" cat-file -p "$RES:rise_stack/robomimic/rise_on_robomimic.patch" > "$SCRATCH/robomimic.patch" echo " patch bytes: $(wc -c < "$SCRATCH/robomimic.patch")" git -C "$RM" apply --whitespace=nowarn "$SCRATCH/robomimic.patch" 2>&1 | scrub && echo " patch APPLIED clean"fiif [ -f "$RM/robomimic/algo/rsm_scorer.py" ] && grep -q '_rsm_libero_dir' "$RM/robomimic/algo/rsm_scorer.py"; then echo " reconstruction carries #8's item-3 fix (_rsm_libero_dir) -- right file for R1"; FORK_OK=1else echo " !! fork reconstruction unusable -- R1 INCONCLUSIVE, not a pass"; rc_all=2fi
R1LINE="(skipped)"if [ "$FORK_OK" = 1 ]; then run_case "R1 (RESOLVED tree + patched fork on PYTHONPATH = what SETUP.md produces)" "$WR" "$RM" R1LINE=$( cd "$WR" && PYTHONPATH=$RM "$PY" -m pytest -q -p no:cacheprovider $CIFILES 2>&1 | tail -1 )fi
hdr "8 SUMMARY"printf " %-62s %s\n" "H0 #11 head, no robomimic (Actions runner)" "$H0LINE"printf " %-62s %s\n" "R0 resolved tree, no robomimic" "$R0LINE"printf " %-62s %s\n" "R1 resolved tree, patched fork importable" "$R1LINE"case "$H0LINE" in *" passed"*) : ;; *) echo " BASELINE DID NOT PASS -- every other line is uninterpretable"; rc_all=2;; esaccase "$H0LINE" in *"no tests ran"*|*"error"*) echo " BASELINE COLLECTED NOTHING"; rc_all=2;; esac
hdr "9 cleanup worktrees"git -C "$M" worktree remove --force "$WH" 2>/dev/null; git -C "$M" worktree remove --force "$WR" 2>/dev/nullhdr "OVERALL rc=$rc_all (2 = something was inconclusive, not a pass)"exit $rc_all123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176#!/usr/bin/env bash# rsm_real#5 -- run 18 follow-up. The first pass (LSF 1895089) reported# H0 #11 head 102 passed, 2 skipped# R0 resolved 101 passed, 4 skipped# R1 resolved+fork 101 passed, 4 skipped# Two things in that table are NOT yet measured, and one of them is a hole in my own guard:# (1) R1 == R0 exactly. R1 was supposed to be the state SETUP.md produces -- the patched fork# importable -- and in that state the two which_scorer tests should PASS naming the fork, not# skip. Identical numbers are the signature of a case that never actually differed: almost# certainly `import robomimic.algo.rsm_scorer` still raises in the CI venv (robomimic has# runtime deps the deployment requirements do not carry), so the tests skip themselves for the# same reason as R0. My guard checked that the FILE was reconstructed, not that it IMPORTS.# That is this project's recorded failure mode one level in, so: import it, print the# exception if it fails, install what is missing, and only then call R1 a result.# (2) 104 collected on the head vs 105 on the resolved tree, and two passes became skips. A count# that moves is a test that changed identity; name it rather than subtracting integers.# Read-only w.r.t. every real repo: fetches from GitHub, works only inside SCRATCH, pushes nothing.set -uo pipefailsource /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_resolve.shSCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run30}VENV=${VENV:-/proj/dmfexp/zwhong/scratch_patchexport/run29/venv_ci}RM=${RM:-/proj/dmfexp/zwhong/scratch_patchexport/run29/robomimic_fork}PRS=${PRS:-"6 7 8 9 10"}SC_PR=${SC_PR:-11}export GIT_TERMINAL_PROMPT=0 PYTHONDONTWRITEBYTECODE=1 OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1scrub(){ sed 's#https://[^@]*@#https://<redacted>@#g'; }hdr(){ echo; echo "=================== $* ==================="; date -u; }rc_all=0mkdir -p "${SCRATCH:?}" || exit 1M=$SCRATCH/mtPY=$VENV/bin/python[ -x "$PY" ] || { echo "no venv at $VENV -- run patchexport_merged_tests.sh first"; exit 2; }[ -f "$RM/robomimic/algo/rsm_scorer.py" ] || { echo "no fork reconstruction at $RM"; exit 2; }
hdr "0 context"echo "host=$(hostname) job=${LSB_JOBID:-none} scratch=$SCRATCH venv=$VENV fork=$RM"
hdr "1 rebuild the resolved tree (same steps as 1895089)"TOK=$(grep -m1 'https://richardrl:' ~/.git-credentials | sed -E 's|https://richardrl:([^@]*)@.*|\1|')[ -n "$TOK" ] || { echo "NO TOKEN"; exit 1; }rm -rf "${M:?}"; git init --quiet "$M" || exit 1printf '[remote "origin"]\n\turl = https://richardrl:%s@github.com/jmarangola/rsm_real.git\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n' "$TOK" >> "$M/.git/config"unset TOKgit -C "$M" fetch --quiet origin main 2>&1 | scrubgit -C "$M" checkout --quiet -b main FETCH_HEAD 2>&1 | scrubgit -C "$M" config user.email noreply@anthropic.com; git -C "$M" config user.name "merged-tests detail"for n in $PRS $SC_PR; do git -C "$M" fetch --quiet origin "pull/$n/head:pr-$n" 2>&1 | scrub; doneSC_SHA=$(git -C "$M" rev-parse "pr-$SC_PR")LIVE=$(git -C "$M" ls-remote origin "refs/pull/$SC_PR/head" 2>/dev/null | awk '{print $1}')[ "$LIVE" = "$SC_SHA" ] || { echo "STALE: $SC_SHA != $LIVE"; exit 2; }echo "staleness guard: OK -- sc == live head of PR #$SC_PR ($(echo "$SC_SHA" | cut -c1-7))"for n in $PRS; do git -C "$M" merge --no-ff -m "Merge PR #$n" "pr-$n" >/dev/null 2>&1 || { echo "#$n UNEXPECTED CONFLICT"; exit 2; }; doneFIVE=$(git -C "$M" rev-parse HEAD)git -C "$M" merge --no-ff -m "Merge PR #$SC_PR" "pr-$SC_PR" >/dev/null 2>&1# run 23: rise_stack/scorers.py joined the conflict set when the union landed on #8 (c945f90).# Its resolution is the same mechanical take-ours, so it goes in this list; the hand patch below is# now only a fallback for a tree that predates that commit.pe_resolve "$M" "$FIVE" scripts/setup_env.sh SETUP.md rise_stack/openpi/README.md scripts/check_env.py rise_stack/scorers.py[ -z "$(git -C "$M" diff --name-only --diff-filter=U)" ] || { echo "RESOLUTION INCOMPLETE"; exit 2; }python3 - "$M/rise_stack/scorers.py" <<'PY'import re, sysp = sys.argv[1]; s = open(p).read()pat = re.compile(r"[ \t]*try:\n[ \t]*from \.rsm\.rsm_scorer import ([^\n]*)\n(?:[^\n]*\n)*?[ \t]*from robomimic\.algo\.rsm_scorer import [^\n]*\n")m = pat.search(s)if not m: if "from robomimic.algo.rsm_scorer import RSMScorer, chain_continuation_p, chain_cap_fn" in s and ".rsm.rsm_scorer" not in s: print("scorers.py already single-source (the union landed on #8) -- nothing to patch") sys.exit(0) print("RESOLUTION PATCH FAILED"); sys.exit(3)names = m.group(1).strip(); indent = re.match(r"[ \t]*", m.group(0)).group(0)open(p,"w").write(s[:m.start()] + f"{indent}from robomimic.algo.rsm_scorer import {names}\n" + s[m.end():])print(f"scorers.py resolved -> single import of robomimic.algo.rsm_scorer ({names})")PY[ $? -eq 0 ] || exit 2git -C "$M" add rise_stack/scorers.pygit -C "$M" rm -rf -f --quiet rise_stack/rsm || exit 2git -C "$M" commit --quiet -m "scratch: order-A merge + published resolution" || trueRES=$(git -C "$M" rev-parse HEAD)echo "resolved commit = $(git -C "$M" rev-parse --short HEAD) tree $(git -C "$M" rev-parse --short HEAD^{tree})"CIFILES=$(git -C "$M" cat-file -p "$SC_SHA:.github/workflows/deployment.yml" | sed -n 's#^ *\(tests/test_[a-z_]*\.py\) *$#\1#p' | tr '\n' ' ')echo "CI test files: $CIFILES"
hdr "2 does the reconstructed fork IMPORT in the CI venv? (the check my guard was missing)"# Run 18 first pass said R1 == R0 to the test. The reason, measured below, is that the fork does not# import at all in the deployment venv (robomimic needs torchvision; requirements-deployment.txt does# not carry it), so R1 silently repeated R0. Resolve dependencies in a LOOP -- install exactly the# module the interpreter names, retry, and stop the moment the error stops being a missing module --# so that "R1 ran" means the fork was really imported and not that the case degraded to R0 again.export PIP_CACHE_DIR=/proj/dmfexp/zwhong/scratch_patchexport/run29/pipcache# Run 18b measured the real dependency chain of the PATCHED fork: torchvision -> matplotlib -># diffusers -> diffusion_policy. The first three are wheels; `diffusion_policy` is NOT on PyPI --# scripts/setup_env.sh clones UWRobotLearning/diffusion_policy at 078ce1e and puts the clone root on# sys.path with a .pth (it is a namespace package: `pip install -e` exits 0 having installed zero# modules). So R1 must reproduce THAT, not a pip install. Clone it and put it on PYTHONPATH.DP=${DP:-/proj/dmfexp/zwhong/scratch_patchexport/run29/diffusion_policy}DP_PIN=078ce1eif [ ! -d "$DP/diffusion_policy" ]; then # `fetch --depth 1 origin <short sha>` fails on github ("couldn't find remote ref 078ce1e") -- # a sha can only be fetched directly when the server allows it and only in full form. clone_at in # setup_env.sh clones whole and then resets to the pin; do the same thing here. rm -rf "$DP" git clone --quiet https://github.com/UWRobotLearning/diffusion_policy.git "$DP" 2>&1 | scrub git -C "$DP" checkout --quiet "$DP_PIN" 2>&1 | scrub || echo " !! checkout of $DP_PIN failed"fiif [ -d "$DP/diffusion_policy" ]; then echo " diffusion_policy clone at $(git -C "$DP" rev-parse --short HEAD) (pin $DP_PIN, the one setup_env.sh uses)" FORKPP="$RM:$DP"else echo " !! diffusion_policy clone FAILED -- R1 will stay inconclusive"; FORKPP="$RM"fipkg_for(){ case "$1" in cv2) echo opencv-python;; PIL) echo pillow;; yaml) echo PyYAML;; egl_probe) echo egl_probe;; *) echo "$1";; esac; }IMP_OK=0for attempt in 1 2 3 4 5 6; do if PYTHONPATH=$FORKPP "$PY" -c "import robomimic.algo.rsm_scorer as m; print('OK -> '+m.__file__)" 2>/dev/null | sed 's/^/ /'; then IMP_OK=1; break; fi MISS=$(PYTHONPATH=$FORKPP "$PY" -c "try: import robomimic.algo.rsm_scorerexcept ModuleNotFoundError as e: print(e.name)except Exception as e: print('NON-MODULE-ERROR:'+type(e).__name__+': '+str(e)[:120])" 2>/dev/null) echo " attempt $attempt: import fails, interpreter names -> ${MISS:-<no name>}" case "$MISS" in ""|NON-MODULE-ERROR*) echo " not a missing dependency; full traceback:" PYTHONPATH=$FORKPP "$PY" -c "import robomimic.algo.rsm_scorer" 2>&1 | tail -8 | sed 's/^/ /' break ;; esac PKG=$(pkg_for "$MISS") echo " installing $PKG (a DIVERGENCE from the Actions runner, which installs no robomimic at all -- recorded, not hidden)" if [ "$PKG" = torchvision ]; then "$PY" -m pip install --quiet torchvision --index-url https://download.pytorch.org/whl/cpu 2>&1 | tail -3 | sed 's/^/ /' else "$PY" -m pip install --quiet "$PKG" 2>&1 | tail -3 | sed 's/^/ /' fidoneecho " fork importable in the CI venv: $IMP_OK"[ "$IMP_OK" = 1 ] || { echo " R1 INCONCLUSIVE -- reported as such, not as a pass"; rc_all=2; }if "$PY" -c "import robomimic" 2>/dev/null; then echo " !! robomimic importable with NO PYTHONPATH -- H0/R0 contaminated"; rc_all=2; else echo " robomimic NOT importable without PYTHONPATH -- H0/R0 still clean"; fi
hdr "3 per-test outcome tables (-v), head vs resolved"WH=$SCRATCH/t_head; WR=$SCRATCH/t_resolvedrm -rf "$WH" "$WR"git -C "$M" worktree add --quiet --detach "$WH" "$SC_SHA" || exit 2git -C "$M" worktree add --quiet --detach "$WR" "$RES" || exit 2tbl(){ # dir pythonpath outfile ( cd "$1" && PYTHONPATH=$2 "$PY" -m pytest -v -p no:cacheprovider $CIFILES 2>&1 ) \ | sed -n 's#^\(tests/[^ ]*\) \(PASSED\|FAILED\|SKIPPED\|ERROR\|XFAIL\|XPASS\).*#\1 \2#p' | sort > "$3" echo " $(wc -l < "$3") test ids -> $(basename "$3")"}tbl "$WH" "" "$SCRATCH/H0.txt"tbl "$WR" "" "$SCRATCH/R0.txt"tbl "$WR" "$FORKPP" "$SCRATCH/R1.txt"for f in H0 R0 R1; do echo " $f: $(awk '{print $2}' "$SCRATCH/$f.txt" | sort | uniq -c | tr '\n' ' ')"done
hdr "4 what actually differs -- named, not subtracted"echo "--- H0 vs R0 (the effect of the merge + my resolution) ---"join -a1 -a2 -e MISSING -o 0,1.2,2.2 "$SCRATCH/H0.txt" "$SCRATCH/R0.txt" 2>/dev/null \ | awk '$2!=$3 {printf " %-88s %s -> %s\n", $1, $2, $3}'echo "--- R0 vs R1 (the effect of having the patched fork importable) ---"join -a1 -a2 -e MISSING -o 0,1.2,2.2 "$SCRATCH/R0.txt" "$SCRATCH/R1.txt" 2>/dev/null \ | awk '$2!=$3 {printf " %-88s %s -> %s\n", $1, $2, $3}'
hdr "5 why does each changed test skip? (the reason string, from -rs)"( cd "$WR" && PYTHONPATH= "$PY" -m pytest -q -rs -p no:cacheprovider $CIFILES 2>&1 | sed -n '/short test summary/,$p' ) | sed 's/^/ R0 /'if [ "$IMP_OK" = 1 ]; then ( cd "$WR" && PYTHONPATH=$FORKPP "$PY" -m pytest -q -rs -p no:cacheprovider $CIFILES 2>&1 | sed -n '/short test summary/,$p' ) | sed 's/^/ R1 /'fi
hdr "6 cleanup"git -C "$M" worktree remove --force "$WH" 2>/dev/null; git -C "$M" worktree remove --force "$WR" 2>/dev/nullhdr "OVERALL rc=$rc_all (2 = something was inconclusive, not a pass)"exit $rc_all12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182#!/usr/bin/env bash# rsm_real#5 run 30 -- the six-way merge SHAPE CHANGED and the runbook refused. Diagnose it.## #11 moved a6c2af21 -> fdfa758f (22:02-22:10Z) and that head modifies real/deployment/models.py# (+35 -5) and tests/test_deployment_models.py (+36). Both are now unmerged and neither is in the# runbook's take-ours list, so pe_resolve_check refused -- the right behaviour, and the reason a# resolution list keyed on five paths has to be re-derived whenever either side moves.## This probe does NOT resolve anything. It measures who changed what, whether the two sides' hunks# are disjoint (union-able) or overlapping (a genuine disagreement someone must choose), and which of# OUR PRs is the other party.set -uo pipefailsource /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_resolve.shSCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run97}export GIT_TERMINAL_PROMPT=0scrub(){ sed 's#https://[^@]*@#https://<redacted>@#g'; }hdr(){ echo; echo "=================== $* ==================="; }die(){ echo "PROBE FAILED: $*"; exit 7; }mkdir -p "${SCRATCH:?}" || exit 1W=$SCRATCH/probeTOK=$(grep -m1 'https://richardrl:' ~/.git-credentials | sed -E 's|https://richardrl:([^@]*)@.*|\1|')[ -n "$TOK" ] || die "no token"rm -rf "${W:?}"; git init --quiet "$W" || exit 1printf '[remote "origin"]\n\turl = https://richardrl:%s@github.com/jmarangola/rsm_real.git\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n' "$TOK" >> "$W/.git/config"unset TOKgit -C "$W" fetch --quiet origin 2>&1 | scrub || die fetchgit -C "$W" config user.email noreply@anthropic.com; git -C "$W" config user.name richardrlfor n in 6 7 8 9 10 11; do git -C "$W" fetch --quiet --force origin "pull/$n/head:pr-$n" 2>&1 | scrub; doneg(){ git -C "$W" "$@"; }FILES="real/deployment/models.py tests/test_deployment_models.py"
hdr "0 heads"echo "main = $(g rev-parse --short origin/main)"for n in 6 7 8 9 10 11; do echo "#$n = $(g rev-parse --short pr-$n)"; done
hdr "1 which side touches the two new conflict paths, relative to main"for f in $FILES; do echo "--- $f" for n in 6 7 8 9 10 11; do st=$(g diff --numstat "origin/main...pr-$n" -- "$f") [ -n "$st" ] && echo " #$n +$(echo "$st" | awk '{print $1}') -$(echo "$st" | awk '{print $2}')" donedone
hdr "2 the five-way head (main + #6..#10), then #11"g checkout --quiet -B probe origin/main 2>&1 | scrubfor n in 6 7 8 9 10; do g merge --no-ff -m "probe #$n" "pr-$n" >/dev/null 2>&1 || die "#$n no longer clean on its own"doneFIVE=$(g rev-parse HEAD); echo "five-way = ${FIVE:0:8}"for f in $FILES; do echo " five-way vs main $f: $(g diff --numstat "origin/main..HEAD" -- "$f" | awk '{print "+"$1" -"$2}')"; doneg merge --no-ff -m "probe #11" pr-11 >/dev/null 2>&1echo "unmerged:"; g diff --name-only --diff-filter=U | sed 's/^/ /'
hdr "3 the conflict hunks, with their line ranges"for f in $FILES; do echo "########## $f" echo " conflict hunk count: $(grep -c '^<<<<<<<' "$W/$f" 2>/dev/null || echo 0)" awk '/^<<<<<<</{inc=1} inc{print FILENAME":"FNR": "$0} /^>>>>>>>/{inc=0}' "$W/$f" | sed 's/^/ /' | head -120done
hdr "4 are the two sides' changes DISJOINT? base/ours/theirs diffs per file"T=$SCRATCH/stage; rm -rf "$T"; mkdir -p "$T"for f in $FILES; do b=$T/$(basename "$f").base; o=$T/$(basename "$f").ours; t=$T/$(basename "$f").theirs g show ":1:$f" > "$b" 2>/dev/null; g show ":2:$f" > "$o" 2>/dev/null; g show ":3:$f" > "$t" 2>/dev/null echo "--- $f base=$(wc -l < "$b") ours=$(wc -l < "$o") theirs=$(wc -l < "$t")" echo " OURS vs base:"; diff -u "$b" "$o" | sed -n '3,$p' | sed 's/^/ /' | head -60 echo " THEIRS vs base:"; diff -u "$b" "$t" | sed -n '3,$p' | sed 's/^/ /' | head -80 echo " diff3 merge attempt (rc says whether a union exists):" if diff3 -m "$o" "$b" "$t" > "$T/$(basename "$f").m3" 2>/dev/null; then echo " diff3 CLEAN union, $(wc -l < "$T/$(basename "$f").m3") lines" else echo " diff3 reports overlap: $(grep -c '^<<<<<<<' "$T/$(basename "$f").m3") region(s)" fidone
hdr "5 what #8 does to rise_stack/rsm (the reason models.py disagrees at all)"echo " files under rise_stack/rsm on the five-way head:"; g ls-tree -r --name-only "$FIVE" -- rise_stack/rsm | sed 's/^/ /'echo " files under rise_stack/rsm on #11:"; g ls-tree -r --name-only pr-11 -- rise_stack/rsm | sed 's/^/ /'g merge --abort 2>/dev/nullhdr "PROBE DONE"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186#!/usr/bin/env python3"""rsm_real#5 run 30 -- union the two rewrites of `dependency_report`'s RSM branch.
#11's head fdfa758f grew two NEW conflicting paths outside the runbook's take-ours five:`real/deployment/models.py` and `tests/test_deployment_models.py`. Both sides rewrote the SAME`if scorer_kind == "rsm":` block, and `diff3 -m` reports a genuine overlap (LSF 1907385), so this isnot a preference to settle by keeping one side -- taking either alone silently drops a fix that wasmeasured:
OURS (#8): the pinned rsm_libero may be INSTALLED as a package, so `RSM_LIBERO_DIR` -- an env var aimed at somebody's research checkout -- must not be a deployment requirement. THEIRS (#11): ASK `which_scorer.resolve()` which implementation will load, instead of demanding the fork unconditionally; on a tree carrying `rise_stack/rsm/` neither the fork nor the env var is required (LSF 1905498 PROBE C: 3 missing deps in an interpreter that then scored).
The two are orthogonal: theirs decides WHICH scorer answers, ours decides what counts as a usablersm_libero SOURCE. The union keeps theirs' structure and transplants ours' source test into both ofits branches -- including the `else:` branch, which on their side is still the old env-var-only demandand is exactly the branch the merged tree takes (#8 deletes `rise_stack/rsm/`, so nothing is vendored).
Every edit is ANCHORED on an exact string that must occur exactly once; a missing or repeated anchoris a refusal, not a best effort. That is the lesson of the `>=` floors and of the four duplicated`deployment.yml` lines: a builder that "mostly finds" its anchor writes a file nobody can reproduce."""from __future__ import annotations
import argparseimport astimport sys
MARKER = "# UNION (rsm_real#5 run 30)"
def die(msg: str) -> None: print(f" !! models union REFUSED: {msg}", file=sys.stderr) raise SystemExit(3)
def once(text: str, anchor: str, what: str) -> None: n = text.count(anchor) if n != 1: die(f"{what}: anchor occurs {n} times, expected exactly 1: {anchor[:70]!r}")
# --------------------------------------------------------------------------------------- models.py# Their clause, verbatim from fdfa758f: a RESOLVED scorer whose rsm_libero source is not one of the# three known-good values is reported missing. Ours adds a fourth good value -- an INSTALLED package.THEIR_SOURCE_TEST = """ if resolved.get("rsm_libero_source") not in ("vendored", "env", "env-invalid"): missing.append( f"a usable rsm_libero for {resolved['module']} " f"(source: {resolved.get('rsm_libero_source')}); set RSM_LIBERO_DIR to a tree with " "model.py, train_rsm.py, is_ope.py, data.py, pinned to the scorer's revision")"""
UNION_SOURCE_TEST = f""" # {MARKER[2:]}: an INSTALLED `rsm_libero` is the fourth resolved source. #8 ships the # pinned gen_q revision to be installed with `pip install -e <clone>`; a deployment machine # that did so has the four modules on `sys.path` under no env var and with nothing vendored, # and `resolve()` reports the source as "unknown" there because it only looks at the # vendored directory and RSM_LIBERO_DIR. Demanding the env var anyway is the same # contradiction in the other direction: a missing row for a module that imports. if (resolved.get("rsm_libero_source") not in ("vendored", "env", "env-invalid") and not _available("rsm_libero")): missing.append( f"a usable rsm_libero for {{resolved['module']}} " f"(source: {{resolved.get('rsm_libero_source')}}): install the gen_q revision in " "rise_stack/rsm_libero/UPSTREAM_COMMIT.txt with `pip install -e <clone>`, or set " "RSM_LIBERO_DIR to a tree with model.py, train_rsm.py, is_ope.py, data.py, " "pinned to the scorer's revision")"""
# Their `else:` branch (nothing resolved) is the UNMODIFIED base text, so it still demands# RSM_LIBERO_DIR. On the merged tree that branch is the live one, which is why ours goes here.THEIR_ELSE_ENVDEMAND = """ rsm_dir = Path(os.environ.get("RSM_LIBERO_DIR", "")) if not os.environ.get("RSM_LIBERO_DIR") or not all((rsm_dir / name).is_file() for name in ("model.py", "train_rsm.py", "is_ope.py")): missing.append("RSM_LIBERO_DIR pointing to the matching rsm_libero tree (model.py, train_rsm.py, is_ope.py); pin its source revision with the scorer")"""
UNION_ELSE_ENVDEMAND = f""" # {MARKER[2:]}: #8's source test, transplanted into the branch the merged tree takes. # The pinned rsm_libero satisfies this either way it was installed: as a package # (`pip install -e <gen_q clone>`, see rise_stack/rsm_libero/) or as a directory pointed # at by RSM_LIBERO_DIR. The installed package is the supported route on a robot. rsm_dir = Path(os.environ.get("RSM_LIBERO_DIR", "")) has_dir = bool(os.environ.get("RSM_LIBERO_DIR")) and all( (rsm_dir / name).is_file() for name in ("model.py", "train_rsm.py", "is_ope.py")) if not (has_dir or _available("rsm_libero")): missing.append("the pinned rsm_libero source (model.py, train_rsm.py, is_ope.py): install the " "gen_q revision in rise_stack/rsm_libero/UPSTREAM_COMMIT.txt with " "`pip install -e <clone>`, or set RSM_LIBERO_DIR pointing to the matching " "rsm_libero tree, pinned to the scorer's revision")"""
def union_models(base: str, ours: str, theirs: str) -> str: if MARKER in theirs or MARKER in ours: die("an input already carries the union marker -- this builder does not run twice") # Sanity on the sides themselves: each must carry the thing it is contributing. if "which_scorer import resolve" not in theirs: die("theirs does not ask which_scorer.resolve -- not the side this union was written for") if '_available("rsm_libero")' not in ours: die("ours does not test for an installed rsm_libero -- not the side this union was written for") out = theirs once(out, THEIR_SOURCE_TEST, "models.py resolved-source clause") out = out.replace(THEIR_SOURCE_TEST, UNION_SOURCE_TEST) once(out, THEIR_ELSE_ENVDEMAND, "models.py else-branch env demand") out = out.replace(THEIR_ELSE_ENVDEMAND, UNION_ELSE_ENVDEMAND) # Self-checks in the units a "does it parse" test cannot see. try: ast.parse(out) except SyntaxError as exc: die(f"the union does not parse: {exc}") for need, what in [ ("which_scorer import resolve", "theirs' resolver question"), ('_available("rsm_libero")', "ours' installed-package test"), ("has_dir or _available", "ours' else-branch test"), ("rise_stack/rsm_libero/UPSTREAM_COMMIT.txt", "ours' install instruction"), ("RSM_LIBERO_DIR", "the env-var route"), ]: if need not in out: die(f"the union lost {what} ({need!r})") n_src = out.count('_available("rsm_libero")') if n_src != 2: die(f"ours' installed-package test must land in BOTH branches (resolved and else), found {n_src}") if "<<<<<<<" in out or ">>>>>>>" in out: die("the union carries conflict markers") if len(out.splitlines()) < max(len(ours.splitlines()), len(theirs.splitlines())): die("the union is shorter than the longer side -- something was dropped") return out
# ------------------------------------------------------------------------- tests/test_deployment_models.pydef _funcs(text: str) -> dict[str, str]: tree = ast.parse(text) lines = text.splitlines(keepends=True) out = {} for node in tree.body: if isinstance(node, ast.FunctionDef): out[node.name] = "".join(lines[node.lineno - 1: node.end_lineno]) return out
def union_tests(base: str, ours: str, theirs: str) -> str: bf, of, tf = _funcs(base), _funcs(ours), _funcs(theirs) ours_new = [n for n in of if n not in bf] theirs_new = [n for n in tf if n not in bf] if not ours_new: die("ours adds no test -- nothing to union") if not theirs_new: die("theirs adds no test -- nothing to union") missing_from_theirs = [n for n in ours_new if n not in tf] if not missing_from_theirs: die("every test ours adds is already on theirs -- take-theirs would do, refusing to rewrite") # Anchor: the first base function that follows the insertion point on BOTH sides. anchor = "def test_rsm_does_not_pad_short_chunks(" once(theirs, anchor, "test file insertion anchor") block = "".join(of[n].rstrip("\n") + "\n\n\n" for n in missing_from_theirs) out = theirs.replace(anchor, f"# {MARKER[2:]}: #8's test, kept alongside #11's two.\n{block}{anchor}") try: ast.parse(out) except SyntaxError as exc: die(f"the test union does not parse: {exc}") got = _funcs(out) for n in set(of) | set(tf): if n not in got: die(f"the test union lost {n}") dupes = [n for n in got if out.count(f"def {n}(") != 1] if dupes: die(f"the test union defines these more than once: {dupes}") if len(got) != len(set(of) | set(tf)): die(f"the test union has {len(got)} tests, expected {len(set(of) | set(tf))}") return out
def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("kind", choices=["models", "tests"]) ap.add_argument("base"); ap.add_argument("ours"); ap.add_argument("theirs") ap.add_argument("-o", "--out", required=True) a = ap.parse_args() b, o, t = (open(p).read() for p in (a.base, a.ours, a.theirs)) if not b.strip() or not o.strip() or not t.strip(): die("one of base/ours/theirs is empty -- a union of nothing is not a resolution") out = union_models(b, o, t) if a.kind == "models" else union_tests(b, o, t) open(a.out, "w").write(out) print(f" models union OK [{a.kind}]: base={len(b.splitlines())} ours={len(o.splitlines())} " f"theirs={len(t.splitlines())} -> union={len(out.splitlines())} lines") return 0
if __name__ == "__main__": raise SystemExit(main())1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192#!/usr/bin/env python3"""Measure the openpi patch's own numbers from the patch file, and check both README tables against it.
rsm_real#5 run 23. #11's 6c1b8d0 ("The openpi patch's own numbers were written in three places; twohad drifted") rewrote the per-file table in rise_stack/openpi/README.md. Our side (#6/#10) carries theOLDER table, which the six-way runbook resolves by taking ours -- so if their correction is right, themerge reinstates numbers they just measured as wrong. Neither table is evidence: this parses the patch.
usage: patchexport_openpi_numbers.py <rise_on_pi05.patch> <ours_README.md> <theirs_README.md>"""import reimport sys
patch_p, ours_p, theirs_p = sys.argv[1], sys.argv[2], sys.argv[3]
# --- 1 truth: parse the unified diff -----------------------------------------------------------files, cur = {}, Nonefor line in open(patch_p, errors="replace"): if line.startswith("+++ "): p = line[4:].strip() cur = None if p == "/dev/null" else re.sub(r"^b/", "", p) files.setdefault(cur, {"ins": 0, "del": 0, "new": False}) elif line.startswith("--- "): prev = line[4:].strip() if prev == "/dev/null": pending_new = True else: pending_new = False globals()["_pending_new"] = pending_new elif cur is not None and line.startswith("+") and not line.startswith("+++"): files[cur]["ins"] += 1 if globals().get("_pending_new"): files[cur]["new"] = True elif cur is not None and line.startswith("-") and not line.startswith("---"): files[cur]["del"] += 1
tot_i = sum(v["ins"] for v in files.values())tot_d = sum(v["del"] for v in files.values())print(f"MEASURED from {patch_p.split('/')[-1]}: {len(files)} files, {tot_i} insertions, {tot_d} deletions")for f, v in sorted(files.items(), key=lambda kv: -kv[1]["ins"]): print(f" {f:<45} +{v['ins']:<5} -{v['del']:<4}{' NEW FILE' if v['new'] else ''}")
# --- 2 what each README claims ------------------------------------------------------------------CLAIM = re.compile(r"\+(\d[\d,]*)")def claims(path): out = {} hdr = None for line in open(path, errors="replace"): if not line.lstrip().startswith("|"): continue cells = [c.strip() for c in line.strip().strip("|").split("|")] # a row is interesting when its first cell names one or more source paths in backticks paths = re.findall(r"`([\w/\.]+\.py)`", cells[0]) if cells else [] if not paths: continue nums = [int(n.replace(",", "")) for c in cells[1:] for n in CLAIM.findall(c)] if nums: out[tuple(paths)] = nums[0] if len(nums) == 1 else nums return out
def totals(path): t = open(path, errors="replace").read() m = re.search(r"(\d+) files?, ([\d,]+) insertions?", t) return (int(m.group(1)), int(m.group(2).replace(",", ""))) if m else None
rc = 0for label, p in (("OURS (#6/#10)", ours_p), ("THEIRS (#11)", theirs_p)): print(f"\n=== {label} ===") tt = totals(p) print(f" headline totals claimed: {tt} measured: ({len(files)}, {tot_i})") if tt and tt != (len(files), tot_i): print(f" !! HEADLINE WRONG") c = claims(p) print(f" {len(c)} per-file row(s) with a +N") for paths, n in sorted(c.items()): want = sum(files.get("src/openpi/" + q.split("openpi/")[-1], files.get(q, {"ins": 0}))["ins"] if False else 0 for q in paths) # resolve each claimed path against the measured set by suffix match got = 0 matched = [] for q in paths: hit = [f for f in files if f.endswith(q) or f.split("/")[-1] == q.split("/")[-1]] if hit: got += files[hit[0]]["ins"] matched.append(hit[0]) n0 = n if isinstance(n, int) else n[0] ok = "OK " if n0 == got else "!! " if n0 != got: rc = 1 print(f" {ok}{'+'.join(paths):<50} claims +{n0:<5} measured +{got} {matched if not matched else ''}")print(f"\nrc={rc} (1 = at least one README row disagrees with the patch)")sys.exit(0)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687#!/usr/bin/env python3"""Fold #11's MEASURED openpi per-file table into our rise_stack/openpi/README.md.
rsm_real#5 run 23. LSF 1900991 parsed rise_on_pi05.patch and found our table wrong in 5 of 7 rows(train.py +232 vs 224, model.py +39 vs 32, data_loader.py +158 vs 156, optimizer.py +41 vs 39,weight_loaders.py +11 vs 9) and #11's right in 9 of 9. The runbook resolves this file by taking ourside, so without this the merge reinstates five numbers #11 has just measured as wrong.
Structural and refuses to guess: exactly one `| file |` table in each side, one `* Our changes:` bulletin each, or it exits 3. Our prose is kept -- #11's document is a shortened rewrite of ours everywhereelse, and the run-22 union already measured that.
usage: patchexport_openpi_readme_fix.py <ours.md> <theirs.md> <out.md>"""import sys
ours_p, theirs_p, out_p = sys.argv[1], sys.argv[2], sys.argv[3]ours = open(ours_p).read().splitlines()theirs = open(theirs_p).read().splitlines()
def one(lines, pred, what): hits = [i for i, l in enumerate(lines) if pred(l)] if len(hits) != 1: print(f"REFUSING: expected exactly 1 {what}, found {len(hits)}", file=sys.stderr) sys.exit(3) return hits[0]
def table(lines): s = one(lines, lambda l: l.startswith("| file |"), "per-file table header") e = s while e + 1 < len(lines) and lines[e + 1].startswith("|"): e += 1 return s, e
def bullet(lines): return one(lines, lambda l: l.startswith("* Our changes:"), "`* Our changes:` bullet")
ob, tb = bullet(ours), bullet(theirs)os_, oe = table(ours)ts, te = table(theirs)# #11 follows its table with a paragraph naming the test that recomputes the numbers; keep it.np_s = te + 1while np_s < len(theirs) and not theirs[np_s].strip(): np_s += 1np_e = np_swhile np_e < len(theirs) and theirs[np_e].strip(): np_e += 1note = theirs[np_s:np_e]if not any("recomputes" in l or "test_rise_stack_openpi_patch_numbers" in l for l in note): print("REFUSING: the paragraph after #11's table is not the one that names the test", file=sys.stderr) sys.exit(3)
print(f"ours: bullet line {ob+1}, table lines {os_+1}..{oe+1} ({oe-os_+1} rows)")print(f"#11 : bullet line {tb+1}, table lines {ts+1}..{te+1} ({te-ts+1} rows), note {np_s+1}..{np_e}")
out = list(ours)# replace the table first (higher line numbers) so the bullet index stays validout[os_:oe + 1] = theirs[ts:te + 1] + [""] + noteout[ob] = theirs[tb]# #11's f3c0713 added a paragraph that its own test pins: the patch DECLARES 12 pi05_cooking_*# TrainConfigs, baselines.yaml WIRES 11, and the twelfth (pi05_cooking_risebn) has never been built.# Our line said "All 11 ... still build under the fixed patch", which is the drifted claim their# docstring names. Replace ours with theirs, or refuse.oi = one(out, lambda l: l.startswith("All 11 `pi05_cooking_*`"), "the `All 11 ...` sentence")ds = one(theirs, lambda l: l.startswith("The patch declares **"), "the `The patch declares` paragraph")de = dswhile de + 1 < len(theirs) and theirs[de + 1].strip(): de += 1para = theirs[ds:de + 1]for must in ("risebn", "wires up"): if not any(must in l for l in para): print(f"REFUSING: #11's paragraph does not mention {must!r}", file=sys.stderr) sys.exit(3)print(f"replacing our line {oi+1} with #11's lines {ds+1}..{de+1} ({len(para)} lines)")out[oi:oi + 1] = para
open(out_p, "w").write("\n".join(out) + "\n")print(f"wrote {out_p}: {len(ours)} -> {len(out)} lines")
# the paragraph we must NOT have dropped: ours explains how the patch is regeneratedkept = "\n".join(out)for must in ("git add -A && git diff --cached", "One thing you must change to *retrain*", "verify_inference_no_split.py"): print(f" kept {must!r}: {must in kept}") if must not in kept: sys.exit(4)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134#!/usr/bin/env bash# SUPERSEDED 2026-09-24 (run 28): this gate trial-merges a SUBSET, not main + #6..#10 + #11.# That hole is a measured failure of this stream -- LSF 1902702 caught a conflict AFTER a push whose# gate merged only `main -> #6 -> #10`. Do not reuse this script for a new push. Copy# scripts/real/patchexport_readme_dedupe_push.sh instead: it does the full merge with pe_resolve, runs# #11's control ledger on the merged tree, and diffs pytest against a baseline MEASURED on main alone# rather than against a hardcoded expectation.# rsm_real#5 run 23 -- fold #11's MEASURED openpi per-file table into our rise_stack/openpi/README.md,# on BOTH branches that add the file (#6 and #10), with the blob identical on the two.## Why: LSF 1900991 parsed rise_on_pi05.patch itself and found our table wrong in 5 of 7 rows and #11's# right in 9 of 9. The runbook resolves this file by taking our side, so leaving it would make the# merge reinstate five numbers #11 has just measured as wrong -- and #11 now ships# tests/test_rise_stack_openpi_patch_numbers.py, which recomputes them, so the merged tree would go red.set -uo pipefailS=${S:-/proj/dmfexp/zwhong/scratch_patchexport/run63}WT_SETUP=${WT_SETUP:-/proj/dmfexp/zwhong/scratch_patchexport/wt_setup} # #10WT_MAIN=${WT_MAIN:-/proj/dmfexp/zwhong/scratch_patchexport/wt_main} # #6DO_PUSH=${DO_PUSH:-0}D=/proj/dmfexp/zwhong/rsm_rise/scripts/realexport GIT_TERMINAL_PROMPT=0scrub(){ sed 's#https://[^@]*@#https://<redacted>@#g'; }hdr(){ echo; echo "=================== $* ==================="; date -u; }mkdir -p "$S"; rc=0
hdr "0 context"echo "host=$(hostname) job=${LSB_JOBID:-none} do_push=$DO_PUSH"for wt in "$WT_SETUP" "$WT_MAIN"; do echo " $wt on $(git -C "$wt" rev-parse --abbrev-ref HEAD) @ $(git -C "$wt" rev-parse --short HEAD)" d=$(git -C "$wt" status --porcelain); [ -z "$d" ] || { echo " DIRTY -- refusing:"; echo "$d"; exit 2; } b=$(git -C "$wt" rev-parse --abbrev-ref HEAD) git -C "$wt" fetch --quiet origin "$b" 2>&1 | scrub || exit 2 L=$(git -C "$wt" rev-parse HEAD); R=$(git -C "$wt" rev-parse FETCH_HEAD) [ "$L" = "$R" ] || { echo " $b: local ${L:0:7} != origin ${R:0:7} -- REFUSING"; exit 2; }doneA=$(git -C "$WT_SETUP" rev-parse HEAD:rise_stack/openpi/README.md)B=$(git -C "$WT_MAIN" rev-parse HEAD:rise_stack/openpi/README.md)echo " current blobs: #10 ${A:0:10} #6 ${B:0:10}"[ "$A" = "$B" ] || { echo " the two branches already differ on this file -- REFUSING"; exit 2; }
hdr "1 live #11 blob + our patch file"git -C "$WT_SETUP" fetch --quiet origin 'pull/11/head:refs/remotes/pr/11-now' --force 2>&1 | scrubSC=$(git -C "$WT_SETUP" rev-parse refs/remotes/pr/11-now)LIVE=$(git -C "$WT_SETUP" ls-remote origin refs/pull/11/head | awk '{print $1}')[ -n "$LIVE" ] && [ "$LIVE" = "$SC" ] || { echo "STALENESS GUARD FAILED"; exit 2; }echo " #11 live head ${SC:0:7}"git -C "$WT_SETUP" show "HEAD:rise_stack/openpi/rise_on_pi05.patch" > "$S/rise_on_pi05.patch"git -C "$WT_SETUP" show "HEAD:rise_stack/openpi/README.md" > "$S/ours_README.md"git -C "$WT_SETUP" show "$SC:rise_stack/openpi/README.md" > "$S/theirs_README.md"
hdr "2 build the corrected README"python3 "$D/patchexport_openpi_readme_fix.py" "$S/ours_README.md" "$S/theirs_README.md" "$S/fixed_README.md" || { echo "transform refused"; exit 3; }
hdr "3 the corrected file must agree with the patch file on EVERY row"python3 "$D/patchexport_openpi_numbers.py" "$S/rise_on_pi05.patch" "$S/fixed_README.md" "$S/theirs_README.md" > "$S/nums_after.log" 2>&1sed -n '/=== OURS/,$p' "$S/nums_after.log"if grep -qE '^ !! ' "$S/nums_after.log"; then echo " a row still disagrees -- REFUSING"; rc=4fin=$(grep -cE '^\s*\|' "$S/fixed_README.md"); f=$(grep -c '^```' "$S/fixed_README.md")echo " table rows=$n code fences=$f (even=$([ $((f%2)) -eq 0 ] && echo yes || echo NO))"[ $((f%2)) -eq 0 ] || rc=4grep -qE '^(<<<<<<<|=======|>>>>>>>)' "$S/fixed_README.md" && { echo " conflict markers!"; rc=4; }[ $rc -eq 0 ] || { echo "not pushing"; exit $rc; }
hdr "4 commit on both branches, same blob"MSG=$(cat <<'EOM'openpi README: take #11's per-file table, because it is the one that matches the patch file
rsm_real#5. The six-way runbook resolves rise_stack/openpi/README.md by taking this side, so anynumber on this page that is wrong here is a number the merge reinstates. #11's 6c1b8d0 rewrote thetable; rather than trust either document, scripts/real/patchexport_openpi_numbers.py parsesrise_stack/openpi/rise_on_pi05.patch and counts the +/- lines per file (LSF 1900991):
measured: 9 files, 1,185 insertions, 21 deletions this side, before: 5 of 7 rows wrong -- train.py +232 (224), model.py +39 (32), data_loader.py +158 (156), optimizer.py +41 (39), weight_loaders.py +11 (9) #11: 9 of 9 rows right
So the table, the "and 21 deletions" headline and the note namingtests/test_rise_stack_openpi_patch_numbers.py come from #11 verbatim; every other paragraph on thispage stays as it is, because #11's document is a shortened rewrite of it everywhere else and therun-22 union already measured that (LSF 1898271). The transform is structural -- exactly one tableand one "* Our changes:" bullet per side or it exits 3 -- and it re-checks that the paragraph onregenerating the patch with `git add -A && git diff --cached`, the retrain section and theverify_inference_no_split.py pointer all survive.
Written identically to patchexport/pi05-bc-inference-sources and patchexport/env-setup: both add thisfile, and they merge cleanly with each other only while the blob is the same. Verified bygit hash-object on both working copies and both committed trees before either is pushed.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>EOM)for wt in "$WT_SETUP" "$WT_MAIN"; do cp "$S/fixed_README.md" "$wt/rise_stack/openpi/README.md" git -C "$wt" add rise_stack/openpi/README.mddoneX=$(git hash-object "$WT_SETUP/rise_stack/openpi/README.md"); Y=$(git hash-object "$WT_MAIN/rise_stack/openpi/README.md")echo " worktree blobs ${X:0:10} / ${Y:0:10}"[ "$X" = "$Y" ] || { echo " BLOBS DIFFER -- refusing"; exit 2; }for wt in "$WT_SETUP" "$WT_MAIN"; do git -C "$wt" commit -q -m "$MSG" || { echo "commit failed in $wt"; exit 2; } echo " $(git -C "$wt" rev-parse --abbrev-ref HEAD) -> $(git -C "$wt" rev-parse --short HEAD)"doneX=$(git -C "$WT_SETUP" rev-parse HEAD:rise_stack/openpi/README.md); Y=$(git -C "$WT_MAIN" rev-parse HEAD:rise_stack/openpi/README.md)echo " committed blobs ${X:0:10} / ${Y:0:10}"[ "$X" = "$Y" ] || { echo " COMMITTED BLOBS DIFFER -- not pushing"; exit 2; }
hdr "5 trial five-way merge"T=$(mktemp -d /proj/dmfexp/zwhong/scratch_patchexport/readmemerge.XXXXXX)git clone --quiet --shared --no-checkout "$WT_SETUP" "$T/r" 2>/dev/nullgit -C "$T/r" fetch --quiet "$WT_SETUP" HEAD:local-setupgit -C "$T/r" fetch --quiet "$WT_MAIN" HEAD:local-maingit -C "$T/r" fetch --quiet "$WT_SETUP" refs/remotes/origin/main:local-mainlinegit -C "$T/r" checkout --quiet -b trial local-mainlinegit -C "$T/r" config user.email noreply@anthropic.com; git -C "$T/r" config user.name "readme merge trial"if git -C "$T/r" merge --no-ff -q -m "trial #6" local-main && git -C "$T/r" merge --no-ff -q -m "trial #10" local-setup; then echo " #6 then #10: MERGED CLEAN"else echo " TRIAL MERGE CONFLICTED"; git -C "$T/r" diff --name-only --diff-filter=U; rc=5firm -rf "$T"[ $rc -eq 0 ] || { echo "not pushing"; exit $rc; }
hdr "6 push"if [ "$DO_PUSH" = "1" ]; then git -C "$WT_MAIN" push origin HEAD:patchexport/pi05-bc-inference-sources 2>&1 | scrub || rc=2 git -C "$WT_SETUP" push origin HEAD:patchexport/env-setup 2>&1 | scrub || rc=2else echo " DO_PUSH=0 -- committed locally only"fihdr "OVERALL rc=$rc"exit $rc123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159#!/usr/bin/env bash# rsm_real#5 -- what does the OTHER merge order cost?## My published recommendation on #5 is: main -> #6 -> #7 -> #8 -> #9 -> #10 -> #11(scaffold).# In that order the whole reconciliation is ONE hand-resolution of 5 add/add files (measured, runs# 10-11). But a human looking at the PR list is at least as likely to merge #11 FIRST -- it is the# biggest PR, it is the successor of the already-merged #1, and its title is the product goal.# Nobody has measured that order. If merging #11 first turns one 5-file resolution into five# separate ones, that is decision-relevant BEFORE the button is clicked, not after.## Method, chosen so that nothing is invented: I do NOT auto-resolve conflicts and then keep merging# on top of a tree I made up. Instead:# base B = main + #11 (expected clean; GitHub reports #11 mergeable_state=clean)# for each N in 6..10: fresh branch from B, merge pr-N, record its conflict set independently.# Each number is then a real measurement against a well-defined base. Caveat recorded in the output:# these are per-PR independent costs; a human resolving #6 first may reduce #7's set where the two# overlap, so the SUM is an upper bound and the OVERLAP table is what says how much it can shrink.## Read-only w.r.t. every real repo: fetches main and pull/N/head from GitHub. Pushes nothing,# writes nothing outside SCRATCH.set -uo pipefailSCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run17}PRS=${PRS:-"6 7 8 9 10"}SC_PR=${SC_PR:-11}export GIT_TERMINAL_PROMPT=0scrub(){ sed 's#https://[^@]*@#https://<redacted>@#g'; }hdr(){ echo; echo "=================== $* ==================="; date -u; }rc_all=0mkdir -p "${SCRATCH:?}" || exit 1M=$SCRATCH/ordercost
hdr "0 context"echo "host=$(hostname) job=${LSB_JOBID:-none} scratch=$SCRATCH prs='$PRS' sc_pr=#$SC_PR"
hdr "1 fresh clone of main"TOK=$(grep -m1 'https://richardrl:' ~/.git-credentials | sed -E 's|https://richardrl:([^@]*)@.*|\1|')[ -n "$TOK" ] || { echo "NO TOKEN"; exit 1; }rm -rf "${M:?}"; git init --quiet "$M" || exit 1printf '[remote "origin"]\n\turl = https://richardrl:%s@github.com/jmarangola/rsm_real.git\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n' "$TOK" >> "$M/.git/config"unset TOKgit -C "$M" fetch --quiet origin main 2>&1 | scrubgit -C "$M" checkout --quiet -b main FETCH_HEAD 2>&1 | scrub[ -f "$M/README.md" ] || { echo "CLONE/FETCH FAILED"; exit 1; }git -C "$M" config user.email noreply@anthropic.comgit -C "$M" config user.name "order cost gate"echo "main = $(git -C "$M" rev-parse --short HEAD) $(git -C "$M" log -1 --pretty=%s)"
hdr "2 fetch every PR head"for n in $PRS $SC_PR; do git -C "$M" fetch --quiet origin "pull/$n/head:pr-$n" 2>&1 | scrub sha=$(git -C "$M" rev-parse --short "pr-$n" 2>/dev/null) [ -n "$sha" ] || { echo " #$n FETCH FAILED"; exit 1; } echo " #$n = $sha"done
# classify one conflicted path: marker count, and whether the two sides are the same blob# (a stage-conflicted file with 0 markers is a MODE conflict, not an edit conflict)classify(){ # $1=repo $2=path local r=$1 p=$2 mk ours theirs om tm mk=$(grep -c '^<<<<<<<' "$r/$p" 2>/dev/null); [ -n "$mk" ] || mk=0 ours=$(git -C "$r" ls-files -u -- "$p" | awk '$3==2{print $2}' | head -1) theirs=$(git -C "$r" ls-files -u -- "$p" | awk '$3==3{print $2}' | head -1) om=$(git -C "$r" ls-files -u -- "$p" | awk '$3==2{print $1}' | head -1) tm=$(git -C "$r" ls-files -u -- "$p" | awk '$3==3{print $1}' | head -1) if [ -n "$ours" ] && [ "$ours" = "$theirs" ]; then echo "$p|markers=$mk|SAME BLOB ${ours:0:10}|mode ours=$om theirs=$tm|MODE-ONLY" else echo "$p|markers=$mk|ours=${ours:0:10} theirs=${theirs:0:10}|mode ours=$om theirs=$tm|EDIT" fi}
hdr "3 ORDER B step 1: main + #$SC_PR (the base a human creates by merging the scaffold PR first)"git -C "$M" checkout --quiet -b orderB mainif git -C "$M" merge --no-ff -m "Merge PR #$SC_PR" "pr-$SC_PR" >/dev/null 2>&1; then echo " #$SC_PR MERGED CLEAN -> base B = $(git -C "$M" rev-parse --short HEAD)"else echo " #$SC_PR CONFLICTS (unexpected -- GitHub says clean):" git -C "$M" diff --name-only --diff-filter=U | sed 's/^/ /' git -C "$M" merge --abort; rc_all=1fiBASEB=$(git -C "$M" rev-parse HEAD)echo " base B tree = $(git -C "$M" rev-parse --short HEAD^{tree})"
hdr "4 ORDER B step 2: each of #$PRS merged into base B, measured INDEPENDENTLY"SUM=0: > "$SCRATCH/orderB_sets.txt"for n in $PRS; do git -C "$M" checkout --quiet -B "tryB-$n" "$BASEB" git -C "$M" reset --hard --quiet "$BASEB" if git -C "$M" merge --no-ff -m "Merge PR #$n into B" "pr-$n" >/dev/null 2>&1; then echo " #$n -> MERGED CLEAN (0 files to resolve)" else files=$(git -C "$M" diff --name-only --diff-filter=U) cnt=$(printf '%s\n' "$files" | grep -c . ) echo " #$n -> $cnt file(s) to resolve:" while IFS= read -r p; do [ -n "$p" ] || continue echo " $(classify "$M" "$p")" echo "$n|$p" >> "$SCRATCH/orderB_sets.txt" done <<< "$files" SUM=$((SUM+cnt)) git -C "$M" merge --abort fidoneecho " ORDER B independent total = $SUM file-resolutions (upper bound; see overlap below)"
hdr "5 overlap across ORDER B conflict sets -- how much sequential resolution can shrink the sum"if [ -s "$SCRATCH/orderB_sets.txt" ]; then python3 - "$SCRATCH/orderB_sets.txt" <<'PY'import sys, collectionsd=collections.defaultdict(list)for line in open(sys.argv[1]): line=line.strip() if not line: continue n,p=line.split('|',1) d[p].append(n)print(f" {'file':60s} appears in PRs")for p,ns in sorted(d.items(), key=lambda kv:(-len(kv[1]),kv[0])): print(f" {p:60s} {','.join('#'+x for x in ns)} (x{len(ns)})")print(f"\n DISTINCT files needing resolution in order B = {len(d)}")print(f" sum over PRs = {sum(len(v) for v in d.values())}")PYelse echo " (no conflicts recorded)"fi
hdr "6 ORDER A for comparison: #$PRS first, then #$SC_PR"git -C "$M" checkout --quiet -B orderA maingit -C "$M" reset --hard --quiet mainok=1for n in $PRS; do if git -C "$M" merge --no-ff -m "Merge PR #$n" "pr-$n" >/dev/null 2>&1; then echo " #$n MERGED CLEAN" else echo " #$n CONFLICTS:"; git -C "$M" diff --name-only --diff-filter=U | sed 's/^/ /' git -C "$M" merge --abort; ok=0; rc_all=1; break fidoneif [ "$ok" = 1 ]; then echo " five-way result = $(git -C "$M" rev-parse --short HEAD) tree $(git -C "$M" rev-parse --short HEAD^{tree})" if git -C "$M" merge --no-ff -m "Merge PR #$SC_PR" "pr-$SC_PR" >/dev/null 2>&1; then echo " #$SC_PR MERGED CLEAN (0 files to resolve)" else files=$(git -C "$M" diff --name-only --diff-filter=U) cnt=$(printf '%s\n' "$files" | grep -c .) echo " #$SC_PR -> $cnt file(s) to resolve:" while IFS= read -r p; do [ -n "$p" ] || continue echo " $(classify "$M" "$p")" done <<< "$files" echo " ORDER A total = $cnt file-resolutions, in ONE merge" git -C "$M" merge --abort fifi
hdr "7 verdict"echo "rc_all=$rc_all"echo "Compare: ORDER A total (one merge) vs ORDER B distinct/sum (five merges) above."exit 0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190#!/usr/bin/env bash# rsm_real#5 run 26 -- the owner shipped his OWN installer to main (54c054e, 2026-09-24 19:03-19:11Z)# and it consumes THIS STREAM'S export by pinned revision + sha256:## real/scripts/setup_bc.py:# OPENPI_REVISION = 215abfb217dbac7d5f1273282331b9b1866c0479# HANDOFF_REVISION = a373756093472e145072bb9e3cfef3151022e0d8 <- our commit, PR #6/#10# PATCH_SHA256 = 33b37d55...8fec4# git show $HANDOFF_REVISION:rise_stack/openpi/rise_on_pi05.patch -> verify sha256 -> git apply# then apply requirements/openpi-real.patch (his: makes ALOHA sim optional)## So issue #5's deliverable is no longer "a PR the owner might read": it is an EXECUTED dependency of# his deployment installer. This script runs that dependency path -- and only that path -- for real:# no conda, no pip, no checkpoint download, nothing outside $SCRATCH. Read-only w.r.t. GitHub.set -uo pipefailSCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run81}ROOT=/proj/dmfexp/zwhong/rsm_riseVENV=${VENV:-/proj/dmfexp/zwhong/scratch_patchexport/run29/venv_ci}OPENPI_REVISION=215abfb217dbac7d5f1273282331b9b1866c0479HANDOFF_REVISION=a373756093472e145072bb9e3cfef3151022e0d8PATCH_SHA256=33b37d559c31823fc350fb15e4216a062273550fd580f890eaf1626063a8fec4export GIT_TERMINAL_PROMPT=0 PYTHONDONTWRITEBYTECODE=1scrub(){ sed 's#https://[^@]*@#https://<redacted>@#g'; }hdr(){ echo; echo "=================== $* ==================="; date -u; }rc_all=0fail(){ echo "!! $*"; rc_all=1; }PY=$VENV/bin/python; [ -x "$PY" ] || PY=$(command -v python3)mkdir -p "${SCRATCH:?}" || exit 1
hdr "0 context"echo "host=$(hostname) job=${LSB_JOBID:-none} scratch=$SCRATCH py=$PY ($($PY -V 2>&1))"
TOK=$(grep -m1 'https://richardrl:' ~/.git-credentials | sed -E 's|https://richardrl:([^@]*)@.*|\1|')[ -n "$TOK" ] || { echo "NO TOKEN"; exit 1; }URL="https://richardrl:$TOK@github.com/jmarangola/rsm_real.git"
hdr "1 a DEFAULT clone of rsm_real -- can the installer reach HANDOFF_REVISION?"D=$SCRATCH/full; rm -rf "${D:?}"git clone --quiet "$URL" "$D" 2>&1 | scrubecho " main = $(git -C "$D" rev-parse --short HEAD) $(git -C "$D" log -1 --format=%s | cut -c1-60)"echo " branches fetched: $(git -C "$D" branch -r | wc -l)"if git -C "$D" cat-file -e "$HANDOFF_REVISION" 2>/dev/null; then echo " cat-file -e HANDOFF_REVISION: OK (no fetch needed -- the PR branches live in this repo)"else fail "cat-file -e HANDOFF_REVISION: MISSING in a default clone"fiecho -n " is it an ancestor of main? "git -C "$D" merge-base --is-ancestor "$HANDOFF_REVISION" HEAD 2>/dev/null && echo "YES" || echo "NO <- it lives only on the PR branches"echo -n " reachable from which branches: "git -C "$D" branch -r --contains "$HANDOFF_REVISION" 2>/dev/null | tr -d ' ' | tr '\n' ' '; echo
hdr "2 the installer's OWN fallback: a single-branch clone, then git fetch origin <sha>"S=$SCRATCH/single; rm -rf "${S:?}"git clone --quiet --single-branch --branch main "$URL" "$S" 2>&1 | scrubecho -n " cat-file -e before fetch: "git -C "$S" cat-file -e "$HANDOFF_REVISION" 2>/dev/null && echo "present" || echo "ABSENT (expected -- this is the branch setup_bc.py takes)"git -C "$S" fetch --quiet origin "$HANDOFF_REVISION" 2>&1 | scrub; fr=${PIPESTATUS[0]}echo " git fetch origin \$HANDOFF_REVISION -> rc=$fr"if [ "$fr" -eq 0 ] && git -C "$S" cat-file -e "$HANDOFF_REVISION" 2>/dev/null; then echo " FALLBACK WORKS: the sha is fetchable by sha from a single-branch clone"else fail "FALLBACK BROKEN: setup_bc.py cannot obtain the cooking patch from a single-branch clone"fi
hdr "3 the patch payload and its pinned sha256"git -C "$S" show "$HANDOFF_REVISION:rise_stack/openpi/rise_on_pi05.patch" > "$SCRATCH/cooking.patch" 2>/dev/null || fail "git show failed"got=$(sha256sum "$SCRATCH/cooking.patch" | cut -d' ' -f1)echo " payload = $(wc -l < "$SCRATCH/cooking.patch") lines, sha256 $got"[ "$got" = "$PATCH_SHA256" ] && echo " MATCHES setup_bc.py's PATCH_SHA256" || fail "sha256 MISMATCH: want $PATCH_SHA256"echo -n " is the item-1 inference fix inside it? episodes_required_from x"; grep -c 'episodes_required_from' "$SCRATCH/cooking.patch"echo -n " does it supply cooking_policy.py? "; grep -q 'src/openpi/policies/cooking_policy.py' "$SCRATCH/cooking.patch" && echo YES || fail "cooking_policy.py NOT in the pinned patch"git -C "$D" show "54c054e:requirements/openpi-real.patch" > "$SCRATCH/hardware.patch" 2>/dev/null || fail "no requirements/openpi-real.patch on main"echo " his hardware patch = $(wc -l < "$SCRATCH/hardware.patch") lines"
hdr "4 a clean openpi at the pinned revision (from our local mirror, offline)"O=$SCRATCH/openpi; rm -rf "${O:?}"git clone --quiet --no-local "$ROOT/third_party/openpi" "$O" 2>&1 | scrubgit -C "$O" checkout --quiet --detach "$OPENPI_REVISION" 2>&1 | scrub || fail "cannot check out $OPENPI_REVISION"echo " HEAD = $(git -C "$O" rev-parse HEAD)"[ "$(git -C "$O" rev-parse HEAD)" = "$OPENPI_REVISION" ] || fail "openpi HEAD != OPENPI_REVISION"echo -n " tree clean? "; [ -z "$(git -C "$O" status --porcelain)" ] && echo yes || { git -C "$O" status --porcelain | head -5; fail "openpi clone is not clean"; }
# setup_bc.py's apply_once(), reimplemented exactlyapply_once(){ local src=$1 p=$2 label=$3 if git -C "$src" apply --reverse --check "$p" >/dev/null 2>&1; then echo " $label: ALREADY APPLIED (reverse-check passed) -> no-op"; return 0 fi git -C "$src" apply --check "$p" 2>&1 | sed 's/^/ /'; local c=${PIPESTATUS[0]} echo " $label: git apply --check rc=$c" [ "$c" -eq 0 ] || { fail "$label does not apply"; return 1; } git -C "$src" apply "$p" 2>&1 | sed 's/^/ /'; local a=${PIPESTATUS[0]} echo " $label: git apply rc=$a"; [ "$a" -eq 0 ] || fail "$label apply failed" return $a}
hdr "5 apply, in setup_bc.py's order: our cooking patch, then his hardware patch"apply_once "$O" "$SCRATCH/cooking.patch" "cooking (ours, $HANDOFF_REVISION)"apply_once "$O" "$SCRATCH/hardware.patch" "hardware (his, requirements/openpi-real.patch)"
hdr "6 idempotency -- setup_bc.py is re-runnable, so apply_once must no-op the second time"apply_once "$O" "$SCRATCH/cooking.patch" "cooking 2nd"apply_once "$O" "$SCRATCH/hardware.patch" "hardware 2nd"
hdr "7 post-conditions on the installed tree"f=$O/src/openpi/policies/cooking_policy.py[ -f "$f" ] && echo " cooking_policy.py present ($(wc -l < "$f") lines)" || fail "cooking_policy.py MISSING after apply"echo -n " config.py carries the inference fix: "grep -c 'episodes_required_from' "$O/src/openpi/training/config.py" 2>/dev/null || fail "episodes_required_from absent"# NB: the first version of this check grepped for `exists()` / `is_file()` -- literal empty parens,# which the real call `os.path.exists(self.split_json)` can never match. It reported 0 against# correct code (LSF 1904259). Assert on the guard's STRUCTURE instead, and require the body to be# the one the fix documents: the no-split branch must return None rather than raise.echo " episode_subset() guards the split file:"$PY - "$O/src/openpi/training/config.py" <<'PYEOF' || fail "episode_subset guard not found"import ast, syssrc = open(sys.argv[1]).read()fn = next(n for n in ast.walk(ast.parse(src)) if isinstance(n, ast.FunctionDef) and n.name == "episode_subset")body = ast.get_source_segment(src, fn)guard = [n for n in ast.walk(fn) if isinstance(n, ast.If) and "exists" in ast.dump(n.test) and "split_json" in ast.dump(n.test)]assert guard, "no `if not <...>exists(<...>split_json)` guard in episode_subset"g = guard[0]rets = [n for n in ast.walk(g) if isinstance(n, ast.Return)]raises = [n for n in ast.walk(g) if isinstance(n, ast.Raise)]assert rets and all(isinstance(r.value, ast.Constant) and r.value.value is None for r in rets), \ "the missing-split branch does not return None"assert not raises, "the missing-split branch still raises"warns = [n for n in ast.walk(g) if isinstance(n, ast.Call) and getattr(getattr(n.func, "attr", None), "lower", lambda: "")() == "warning"]print(" guard present at line %d; missing split -> return None, no raise, warning=%s" % (g.lineno, bool(warns)))PYEOFecho " pyproject, after his patch:"$PY - "$O/pyproject.toml" <<'EOF' || exit_code=1import sys, tomllibd = tomllib.load(open(sys.argv[1], 'rb'))base = d['project']['dependencies']opt = d['project'].get('optional-dependencies', {})ga_base = [x for x in base if 'gym-aloha' in x]ga_opt = {k: [x for x in v if 'gym-aloha' in x] for k, v in opt.items()}print(" parses OK; %d base deps" % len(base))print(" gym-aloha in base deps :", ga_base or "NO (his patch removed it)")print(" gym-aloha in optional-deps :", {k: v for k, v in ga_opt.items() if v} or "NO")print(" optional-dependency groups :", sorted(opt))assert not ga_base, "gym-aloha still a hard dependency -- MuJoCo <3 would fight aiofranka 0.4"assert ga_opt.get('simulation'), "no [project.optional-dependencies] simulation group"EOF[ $? -eq 0 ] || fail "pyproject post-condition failed"
hdr "8 informative: does his patch also apply BEFORE ours? (order-independence)"O2=$SCRATCH/openpi_rev; rm -rf "${O2:?}"git clone --quiet --no-local "$ROOT/third_party/openpi" "$O2" 2>&1 | scrubgit -C "$O2" checkout --quiet --detach "$OPENPI_REVISION" 2>&1 | scrubgit -C "$O2" apply --check "$SCRATCH/hardware.patch" 2>&1 | sed 's/^/ /'; a=${PIPESTATUS[0]}git -C "$O2" apply "$SCRATCH/hardware.patch" >/dev/null 2>&1git -C "$O2" apply --check "$SCRATCH/cooking.patch" 2>&1 | sed 's/^/ /'; b=${PIPESTATUS[0]}echo " hardware-then-cooking: hardware --check rc=$a, cooking --check rc=$b (informative only; the installer's order is 5)"
hdr "9 do the owner's pinned constants agree with the pins WE recorded?"$PY - "$D" "$SCRATCH" <<'EOF'import re, subprocess, sysrepo, scratch = sys.argv[1], sys.argv[2]def show(rev, path): try: return subprocess.check_output(["git","-C",repo,"show",f"{rev}:{path}"],text=True,stderr=subprocess.DEVNULL) except Exception: return ""bc = show("54c054e","real/scripts/setup_bc.py")rsm = show("54c054e","real/scripts/setup_rsm.py")def const(src, name): m = re.search(rf'^{name}\s*=\s*"([^"]+)"', src, re.M); return m.group(1) if m else Nonehis = {"openpi": const(bc,"OPENPI_REVISION"), "gen_q": const(rsm,"GEN_Q_REVISION"), "dinov2": const(rsm,"DINO_REVISION")}ours = {}ours["openpi"] = show("5a0c682","rise_stack/openpi/UPSTREAM_COMMIT.txt").split("\n")[0].strip()lib = show("5a0c682","rise_stack/rsm_libero/UPSTREAM_COMMIT.txt")for key, pat in (("gen_q", r'^commit\s*=\s*(\S+)'), ("dinov2", r'^dino_commit\s*=\s*(\S+)')): m = re.search(pat, lib, re.M); ours[key] = m.group(1) if m else Nonebad = 0for k in ("openpi","gen_q","dinov2"): ok = his[k] == ours[k] and his[k] print(f" {k:8s} his={his[k]} ours={ours[k]} {'AGREE' if ok else 'DISAGREE'}") bad += 0 if ok else 1print(" PIN CROSS-CHECK:", "OK -- three independently written pins agree" if not bad else f"{bad} DISAGREE")sys.exit(1 if bad else 0)EOF[ $? -eq 0 ] || fail "pin cross-check disagreed"
hdr "OVERALL rc=$rc_all"exit $rc_all123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120#!/usr/bin/env python"""rsm_real#5 item 1: dump stock pi0.5 BC actions for a few replay frames from ONE openpi source tree.
Run once per source tree (pre-fix patch / post-fix patch) and compare the npz files bit-for-bit.The policy rng is jax.random.key(0) split per infer() call (openpi/policies/policy.py:65), so theaction sequence is a deterministic function of (weights, transforms, frames, call order).
python patchexport_pi05_infer.py --src <tree>/src --ckpt <ckpt dir> --out a.npz [--split-json PATH]
--split-json overrides LeRobotCookingDataConfig.split_json, which is how the deployment case (thetraining split file simply not present) is exercised: point it at a path that does not exist."""import argparse, dataclasses, json, sys, timefrom pathlib import Path
import numpy as np
ROOT = "/proj/dmfexp/zwhong/rsm_rise"DATA = f"{ROOT}/data/real/rsm_cooking_v5"PROMPT = "Follow the displayed cooking state sequence"
def decode_upto(path, last): """Decode frames 0..last inclusive and return them stacked (avoids decoding a whole episode).""" import av out = [] with av.open(str(path)) as c: st = c.streams.video[0] st.thread_type = "AUTO" for i, fr in enumerate(c.decode(st)): out.append(fr.to_ndarray(format="rgb24")) if i >= last: break return np.stack(out)
def main(): ap = argparse.ArgumentParser() ap.add_argument("--src", required=True, help="openpi source dir to put FIRST on sys.path") ap.add_argument("--ckpt", required=True) ap.add_argument("--out", required=True) ap.add_argument("--config", default="pi05_cooking_stock") ap.add_argument("--ep", type=int, default=0) ap.add_argument("--stride", type=int, default=10) ap.add_argument("--frames", type=int, default=8) ap.add_argument("--horizon", type=int, default=10) ap.add_argument("--split-json", default=None, help="override split_json (use a missing path to " "simulate a deployment machine)") args = ap.parse_args()
src = str(Path(args.src).resolve()) sys.path.insert(0, src) import openpi got = str(Path(openpi.__file__).resolve()) print(f"[infer] openpi.__file__ = {got}", flush=True) if not got.startswith(src): # the venv installs the research fork editable via a .pth; if that won this test is void raise SystemExit(f"FATAL: imported openpi from {got}, not from {src}") import jax print(f"[infer] jax {jax.__version__} devices={jax.devices()}", flush=True)
from openpi.policies import policy_config as _policy_config from openpi.training import config as _config
cfg = _config.get_config(args.config) note = "default" if args.split_json is not None: cfg = dataclasses.replace(cfg, data=dataclasses.replace(cfg.data, split_json=args.split_json)) note = f"split_json={args.split_json} exists={Path(args.split_json).exists()}" print(f"[infer] config={args.config} data={type(cfg.data).__name__} {note}", flush=True)
# the acceptance check: build the inference transforms the way create_trained_policy does t0 = time.time() dc = cfg.data.create(cfg.assets_dirs, cfg.model) eps = dc.episodes print(f"[infer] data.create() OK in {time.time()-t0:.2f}s episodes=" f"{'None' if eps is None else f'{len(eps)} ids, first {list(eps)[:5]}'} " f"episodes_required_from={getattr(dc, 'episodes_required_from', '<field absent>')}", flush=True) print(f"[infer] norm_stats keys={sorted(dc.norm_stats) if dc.norm_stats else None} asset_id={dc.asset_id}", flush=True)
policy = _policy_config.create_trained_policy(cfg, args.ckpt) print(f"[infer] policy built in {time.time()-t0:.1f}s", flush=True)
import pyarrow.parquet as pq tab = pq.read_table(f"{DATA}/data/chunk-000/episode_{args.ep:06d}.parquet").to_pandas() S = np.stack(tab["observation.state"].values).astype(np.float32) A = np.stack(tab["action"].values).astype(np.float32) T = len(tab) idxs = [i for i in range(0, T - args.horizon, args.stride)][: args.frames] last = max(idxs) g = decode_upto(f"{DATA}/videos/chunk-000/observation.images.global/episode_{args.ep:06d}.mp4", last) w = decode_upto(f"{DATA}/videos/chunk-000/observation.images.wrist/episode_{args.ep:06d}.mp4", last) print(f"[infer] ep {args.ep} T={T} frames={idxs} imgs={g.shape}/{w.shape}", flush=True)
preds = [] for k, i in enumerate(idxs): obs = {"observation/image": g[i], "observation/wrist_image": w[i], "observation/state": S[i], "prompt": PROMPT} t1 = time.time() pred = np.asarray(policy.infer(obs)["actions"])[: args.horizon, :10] preds.append(pred) print(f"[infer] frame {i} ({k+1}/{len(idxs)}) {time.time()-t1:.1f}s " f"a0={np.array2string(pred[0], precision=8)}", flush=True) # write after every frame so a truncated run is still comparable np.savez(args.out, pred=np.stack(preds), idx=np.array(idxs[: len(preds)]), gt=np.stack([A[i: i + args.horizon] for i in idxs[: len(preds)]])) P = np.stack(preds) print(f"[infer] wrote {args.out} pred{P.shape} dtype={P.dtype} " f"sha=({float(P.sum()):.10g}) xyz_first_l2_cm=" f"{100*float(np.linalg.norm((P-np.stack([A[i:i+args.horizon] for i in idxs]))[:,0,:3],axis=-1).mean()):.3f}", flush=True) json.dump({"src": src, "openpi_file": got, "config": args.config, "ckpt": args.ckpt, "split_json": args.split_json, "episodes": (None if eps is None else len(eps)), "ep": args.ep, "idxs": idxs, "shape": list(P.shape), "dtype": str(P.dtype)}, open(args.out + ".json", "w"), indent=1)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147#!/usr/bin/env bash# SUPERSEDED 2026-09-24 (run 28): this gate trial-merges a SUBSET, not main + #6..#10 + #11.# That hole is a measured failure of this stream -- LSF 1902702 caught a conflict AFTER a push whose# gate merged only `main -> #6 -> #10`. Do not reuse this script for a new push. Copy# scripts/real/patchexport_readme_dedupe_push.sh instead: it does the full merge with pe_resolve, runs# #11's control ledger on the merged tree, and diffs pytest against a baseline MEASURED on main alone# rather than against a hardcoded expectation.# rsm_real#5 run 25 -- repair a conflict THIS STREAM introduced, and close the gate hole that let it out.## 9605cfc (LSF 1902365) rewrote two rows of rise_stack/UPSTREAM_PINS.md on #10: `diffusion_policy`# (line 13) and DINOv2 (line 18). PR #9 rewrites the mimicgen row (line 19). The two edits are# semantically independent -- different rows of the same table -- but line 18 and line 19 are# ADJACENT, so git's three-way merge cannot separate them and the five-way merge of #6..#10 now# conflicts (LSF 1902702: "#10 9605cfc CONFLICTS: rise_stack/UPSTREAM_PINS.md").## Why the push gate missed it: its step 8 trial merge was `main -> #6 -> #10` only. #7, #8 and #9# were never in the trial, and #9 is the branch that collides. A trial merge that omits branches is# the same class of defect as a check that never reaches its comparison -- it passes by not looking.# Step 4 below is now the FULL five-way, and step 5 the six-way with #11.## The fix keeps every fact and moves the DINOv2 sentence off the adjacent row: the `diffusion_policy`# row keeps its inline link (line 13 is 5 lines from the collision and already merged clean), and the# DINOv2 note becomes a short paragraph ABOVE the table, 11 lines away from the mimicgen row.# Verified with `git merge-file` before this job existed: current #10 -> rc=1, 1 conflict hunk;# fixed #10 -> rc=0, 0 markers, and the merged file keeps #9's mimicgen row AND both of our rows.set -uo pipefailS=${S:-/proj/dmfexp/zwhong/scratch_patchexport/run78}WT=${WT:-/proj/dmfexp/zwhong/scratch_patchexport/wt_setup}BR=${BR:-patchexport/env-setup}DO_PUSH=${DO_PUSH:-0}F=rise_stack/UPSTREAM_PINS.mdexport GIT_TERMINAL_PROMPT=0scrub(){ sed 's#https://[^@]*@#https://<redacted>@#g'; }hdr(){ echo; echo "=================== $* ==================="; date -u; }mkdir -p "$S"; rc=0
hdr "0 in-sync guard"echo "host=$(hostname) job=${LSB_JOBID:-none} do_push=$DO_PUSH"[ "$(git -C "$WT" rev-parse --abbrev-ref HEAD)" = "$BR" ] || { echo " wrong branch -- REFUSING"; exit 2; }git -C "$WT" fetch --quiet origin "$BR" 2>&1 | scrub || exit 2L=$(git -C "$WT" rev-parse HEAD); R=$(git -C "$WT" rev-parse FETCH_HEAD)[ "$L" = "$R" ] || { echo " local ${L:0:7} != origin ${R:0:7} -- REFUSING"; exit 2; }DIRT=$(git -C "$WT" status --porcelain)[ -z "$DIRT" ] || { echo " tree not clean -- REFUSING:"; echo "$DIRT"; exit 2; }echo " on $BR @ ${L:0:7}, clean"
hdr "1 the transform: DINOv2 row back to its pre-9605cfc text, the note moved above the table"python3 - "$WT/$F" <<'PY' || exit 3import pathlib, sys, rep = pathlib.Path(sys.argv[1]); lines = p.read_text().split("\n")dino = [i for i, l in enumerate(lines) if l.startswith("| DINOv2 (image featuriser)")]assert len(dino) == 1, f"DINOv2 row appears {len(dino)}x"i = dino[0]tail = ". The commit is recorded ONCE, as `dino_commit`"assert tail in lines[i], "the DINOv2 row does not carry the 9605cfc sentence -- already fixed?"lines[i] = lines[i][:lines[i].index(tail)] + " |"assert lines[i].count("|") >= 6, lines[i]anchor = [j for j, l in enumerate(lines) if l.startswith("`cooking_policy.py` went missing")]assert len(anchor) == 1, f"anchor appears {len(anchor)}x"note = ["", "**Where each pin is recorded.** Every pin above lives in exactly one file,", "`rise_stack/<name>/UPSTREAM_COMMIT.txt`, and `scripts/setup_env.sh` and `scripts/check_env.py` both read", "it from there rather than carrying a copy -- a script that hardcodes the value it is checking reports a", "correctly-cloned tree as wrong the moment the pin moves. DINOv2 is the one exception to the one-file-per-", "name rule: its commit is `dino_commit` in [`rise_stack/rsm_libero/UPSTREAM_COMMIT.txt`](rsm_libero/UPSTREAM_COMMIT.txt),", "because DINOv2 is the featuriser those checkpoints were built against."]lines[anchor[0]+1:anchor[0]+1] = notep.write_text("\n".join(lines))print(f" DINOv2 row restored (line {i+1}); note inserted after line {anchor[0]+1}")PYgit -C "$WT" --no-pager diff --stat -- "$F" | sed 's/^/ /'
hdr "2 every fact that was in 9605cfc is still in the file"python3 - "$WT/$F" <<'PY' || rc=4import pathlib, syst = pathlib.Path(sys.argv[1]).read_text()need = ["diffusion_policy/UPSTREAM_COMMIT.txt", "dino_commit", "rsm_libero/UPSTREAM_COMMIT.txt", "scripts/setup_env.sh", "scripts/check_env.py"]miss = [n for n in need if n not in t]for n in need: print(f" {'ok ' if n not in miss else 'MISSING'} {n}")raise SystemExit(1 if miss else 0)PY[ $rc -eq 0 ] || { echo " a fact was dropped -- REFUSING"; exit $rc; }
hdr "3 commit"git -C "$WT" add "$F"git -C "$WT" commit --quiet -F - <<'EOM'Move the DINOv2 pin note off the row that PR #9 also edits
rsm_real#5. 9605cfc rewrote two rows of rise_stack/UPSTREAM_PINS.md, `diffusion_policy` and DINOv2.PR #9 rewrites the mimicgen row. The two edits are semantically independent -- different rows of thesame table, describing different dependencies -- but the DINOv2 row and the mimicgen row are ADJACENTlines, so git's three-way merge cannot separate them, and the five-way merge of #6..#10 conflicted(LSF 1902702). The five-way merge of our own stack must be clean; a conflict between two of our ownPRs is our problem to remove, not the reviewer's to resolve.
Nothing is dropped. The `diffusion_policy` row keeps its inline link to the new pin file -- it isfive lines from the collision and already merged clean -- and the DINOv2 sentence becomes a short"Where each pin is recorded" paragraph above the table, eleven lines from the mimicgen row, whichsays the same thing for every dependency instead of only for DINOv2.
Measured with `git merge-file` on the three blobs: the pushed 9605cfc version against #9 gives rc=1and one conflict hunk; this version gives rc=0 and zero markers, and the merged file keeps #9'srewritten mimicgen row alongside both of ours.
The gate that let this out has been fixed in the same run: its trial merge was `main -> #6 -> #10`,so #7, #8 and #9 -- the branch that actually collides -- were never in it. A trial merge that omitsbranches passes by not looking. Steps 4 and 5 of scripts/real/patchexport_pins_doc_fix_push.sh arethe full five-way and the six-way with #11.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>EOMgit -C "$WT" --no-pager log --oneline -1 | sed 's/^/ /'NEW=$(git -C "$WT" rev-parse HEAD)
hdr "4 the FULL five-way merge -- the step the previous gate did not have"M=$S/five; rm -rf "$M"; git clone --quiet --shared "$WT" "$M" 2>&1 | scrub || exit 5git -C "$M" remote set-url origin "$(git -C "$WT" remote get-url origin)"git -C "$M" fetch --quiet origin main 2>&1 | scrub || exit 5for n in 6 7 8 9 11; do git -C "$M" fetch --quiet origin "pull/$n/head:pr-$n" 2>&1 | scrub || exit 5; donegit -C "$M" checkout --quiet -B trial origin/maingit -C "$M" config user.email noreply@anthropic.com; git -C "$M" config user.name "pins-doc gate"for n in 6 7 8 9; do if git -C "$M" merge --no-ff -m "trial #$n" "pr-$n" >/dev/null 2>&1; then echo " #$n MERGED CLEAN" else echo " #$n CONFLICTS: $(git -C "$M" diff --name-only --diff-filter=U | tr '\n' ' ')"; rc=6; git -C "$M" merge --abort 2>/dev/null; fidoneif git -C "$M" merge --no-ff -m "trial #10" "$NEW" >/dev/null 2>&1; then echo " #10 (this commit) MERGED CLEAN"else echo " #10 CONFLICTS: $(git -C "$M" diff --name-only --diff-filter=U | tr '\n' ' ')"; rc=6; fi[ $rc -eq 0 ] || { echo " the five-way is not clean -- REFUSING"; exit $rc; }echo " five-way $F keeps #9's mimicgen row: $(grep -c 'mimicgen/rise_on_mimicgen.patch' "$M/$F") and our pin file link: $(grep -c 'diffusion_policy/UPSTREAM_COMMIT.txt' "$M/$F")"grep -c '^<<<<<<<' "$M/$F" | sed 's/^/ conflict markers left in the merged file: /'
hdr "5 the six-way with #11 -- $F must NOT be in the conflict set"git -C "$M" merge --no-ff -m "trial #11" pr-11 >/dev/null 2>&1U=$(git -C "$M" diff --name-only --diff-filter=U)echo " conflicted: $(echo "$U" | tr '\n' ' ')"if echo "$U" | grep -qx "$F"; then echo " !! $F is STILL conflicted against #11 -- REFUSING"; exit 7; fiecho " $F is not in the six-way conflict set"
hdr "6 push"if [ "$DO_PUSH" = 1 ]; then git -C "$WT" push origin "$BR" 2>&1 | scrub || { echo " push FAILED"; exit 8; }else echo " DO_PUSH=0 -- not pushing"fihdr "OVERALL rc=$rc"exit $rc123456#!/usr/bin/env bash# Can a compute node reach PyPI, and does the CI venv accept the two pins it is missing?V=/proj/dmfexp/zwhong/scratch_patchexport/run29/venv_ciset -x$V/bin/python -m pip install --disable-pip-version-check msgpack==1.1.0 pyzmq==26.4.0 2>&1 | tail -20$V/bin/python -c "import msgpack, zmq; print('msgpack', msgpack.version, 'zmq', zmq.__version__)"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110#!/usr/bin/env bash# rsm_real#5 -- a consequence of my OWN published scorer resolution that I had not measured.## The resolution drops rise_stack/rsm/ and single-sources the scorer from the patched fork as# `robomimic.algo.rsm_scorer`. #11's replay quickstart advertises "no openpi, no robomimic" and# installs only requirements/rise-stack-replay.txt, on the stated premise that the scorer is VENDORED.# If the vendored copy goes, does that quickstart still run? Measured, not argued:# A. is the fork copy the same module as the vendored copy (modulo a vendoring header)?# B. does the module body need the robomimic package at all?# C. what does `import robomimic.algo.rsm_scorer` drag in, vs loading the SAME file by path?# D. execute a by-path load with ONLY numpy+torch importable, and instantiate nothing else.# Read-only: scratch + the research checkout, read. Pushes nothing.set -uo pipefailSCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run20}M=${M:-/proj/dmfexp/zwhong/scratch_patchexport/run19/setupenv}RISE=${RISE:-/proj/dmfexp/zwhong/rsm_rise}hdr(){ echo; echo "=================== $* ==================="; date -u; }rc_all=0mkdir -p "${SCRATCH:?}" || exit 1[ -d "$M/.git" ] || { echo "no resolved tree at $M"; exit 1; }
hdr "0 context"echo "host=$(hostname) job=${LSB_JOBID:-none} scratch=$SCRATCH resolved_tree_repo=$M"
hdr "A fork copy vs vendored copy -- same module?"git -C "$M" show HEAD:rise_stack/rsm/rsm_scorer.py > "$SCRATCH/vendored.py"# reconstruct the fork's copy by applying the robomimic patch to an empty dir is overkill; the patch# adds the file whole, so extract the added lines of exactly that file.git -C "$M" show HEAD:rise_stack/robomimic/rise_on_robomimic.patch > "$SCRATCH/robomimic.patch"python3 - "$SCRATCH/robomimic.patch" "$SCRATCH/fork.py" <<'PY'import syssrc,dst=sys.argv[1],sys.argv[2]out=[];inside=Falsefor line in open(src,encoding='utf-8',errors='replace'): if line.startswith('diff --git'): inside = 'robomimic/algo/rsm_scorer.py' in line continue if not inside: continue if line.startswith(('--- ','+++ ','index ','new file','@@','old mode','new mode')): continue if line.startswith('+'): out.append(line[1:])open(dst,'w',encoding='utf-8').writelines(out)print(f"extracted {len(out)} lines of robomimic/algo/rsm_scorer.py from the patch")PYecho "vendored: $(wc -lc < "$SCRATCH/vendored.py" | tr -s ' ') (lines chars)"echo "fork : $(wc -lc < "$SCRATCH/fork.py" | tr -s ' ') (lines chars)"echo "--- diff fork vs vendored (first 40 lines) ---"diff "$SCRATCH/fork.py" "$SCRATCH/vendored.py" | head -40echo "--- diff size: $(diff "$SCRATCH/fork.py" "$SCRATCH/vendored.py" | grep -c '^[<>]') differing line(s) ---"
hdr "B does the module body need the robomimic package?"echo "occurrences of 'robomimic' in the fork copy:"grep -n "robomimic" "$SCRATCH/fork.py" | head -20echo "count: $(grep -c robomimic "$SCRATCH/fork.py")"
hdr 'C what import robomimic.algo.rsm_scorer drags in, before it ever reaches the module'INIT=$RISE/code/rise_robomimic/robomimic/algo/__init__.pyecho "robomimic/algo/__init__.py imports $(grep -cE '^from robomimic' "$INIT") sibling algo module(s):"grep -E '^from robomimic' "$INIT" | sed 's/^/ /'echo "--- third-party imports those siblings pull in (static scan) ---"python3 - "$RISE/code/rise_robomimic/robomimic" <<'PY'import os,sys,re,ast,collectionsroot=sys.argv[1]std=set(sys.stdlib_module_names)tops=collections.Counter()algo=os.path.join(root,'algo')for fn in sorted(os.listdir(algo)): if not fn.endswith('.py'): continue try: tree=ast.parse(open(os.path.join(algo,fn),encoding='utf-8',errors='replace').read()) except SyntaxError: continue for n in ast.walk(tree): if isinstance(n,ast.Import): for a in n.names: tops[a.name.split('.')[0]]+=1 elif isinstance(n,ast.ImportFrom) and n.level==0 and n.module: tops[n.module.split('.')[0]]+=1ext={k:v for k,v in tops.items() if k not in std and k not in ('robomimic',)}print(" non-stdlib top-level modules imported across robomimic/algo/*.py:")for k,v in sorted(ext.items(),key=lambda kv:-kv[1]): print(f" {k:<20} {v}")PY
hdr "D EXECUTE: load the fork copy BY PATH with only numpy+torch, no robomimic package"QS_PY=${QS_PY:-/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python}echo " interpreter: $QS_PY"cd "$SCRATCH"mkdir -p bypath && cp fork.py bypath/rsm_scorer_fork.py"$QS_PY" - "$SCRATCH/bypath/rsm_scorer_fork.py" <<'PY'import sys, importlib.util, typespath=sys.argv[1]# prove robomimic is NOT importable in this interpreter, so a hidden package import would fail loudlyimport importlibtry: importlib.import_module('robomimic'); print(" robomimic IS importable here -- test is not conclusive"); sys.exit(2)except ImportError: print(" robomimic is NOT importable in this interpreter (as on a labmate's quickstart venv)")spec=importlib.util.spec_from_file_location("rsm_scorer_bypath", path)mod=importlib.util.module_from_spec(spec)sys.modules["rsm_scorer_bypath"]=modtry: spec.loader.exec_module(mod)except Exception as e: print(f" !! by-path load FAILED: {type(e).__name__}: {e}"); sys.exit(1)names=[n for n in dir(mod) if 'Scorer' in n or 'scorer' in n]print(f" by-path load OK -- module {mod.__name__}, scorer symbols: {names}")import numpy, torchprint(f" numpy {numpy.__version__}, torch {torch.__version__}")PYrc=$?[ $rc -eq 0 ] || rc_all=$rc
hdr "OVERALL rc=$rc_all"exit $rc_all12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576#!/usr/bin/env bash# rsm_real#5 run 28 -- the one open runbook question: should rise_stack/openpi/README.md flip from# take-OURS to take-THEIRS (#11), with our unique passages folded into their document?## It has stayed open for four runs because it was framed as a preference ("each of their pushes costs# us a re-merge"). It is not a preference. SELFCONTAINED's 17:05Z note says their 6c1b8d0 corrected# two things on that page that are WRONG on our side, and a CI test now enforces them. So the# question has a measurable answer: for each numeric claim on each side, compare it to the ground# truth -- `git apply --numstat` on the shipped patch and the TrainConfigs the patch declares -- and# then measure the fold-in cost in both directions. Whichever side is factually right is the base.## Measures, never edits. Exit 3 only if its own parse is inconsistent.set -uo pipefailSCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run93}R=/proj/dmfexp/zwhong/rsm_risescrub(){ sed 's#https://[^@]*@#https://<redacted>@#g'; }hdr(){ echo; echo "=================== $* ==================="; date -u; }W=$SCRATCH/wmkdir -p "${SCRATCH:?}" || exit 1
hdr "0 clone and fetch the three heads"TOK=$(grep -m1 'https://richardrl:' ~/.git-credentials | sed -E 's|https://richardrl:([^@]*)@.*|\1|')[ -n "$TOK" ] || { echo "no token"; exit 1; }rm -rf "${W:?}"; git init --quiet "$W" || exit 1printf '[remote "origin"]\n\turl = https://richardrl:%s@github.com/jmarangola/rsm_real.git\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n' "$TOK" >> "$W/.git/config"unset TOKfor n in 6 10 11; do git -C "$W" fetch --quiet origin "pull/$n/head:pr-$n" 2>&1 | scrub || { echo "fetch #$n failed"; exit 1; }; donefor n in 6 10 11; do echo " pr-$n = $(git -C "$W" rev-parse --short pr-$n)"; done
P=rise_stack/openpi/README.mdPATCH=rise_stack/openpi/rise_on_pi05.patchmkdir -p "$SCRATCH/x"git -C "$W" show "pr-10:$P" > "$SCRATCH/x/ours.md" || { echo "no $P on #10"; exit 1; }git -C "$W" show "pr-11:$P" > "$SCRATCH/x/theirs.md" || { echo "no $P on #11"; exit 1; }git -C "$W" show "pr-6:$P" > "$SCRATCH/x/pr6.md" || { echo "no $P on #6"; exit 1; }git -C "$W" show "pr-10:$PATCH" > "$SCRATCH/x/ours.patch" || { echo "no patch on #10"; exit 1; }git -C "$W" show "pr-11:$PATCH" > "$SCRATCH/x/theirs.patch" || { echo "no patch on #11"; exit 1; }echo " README bytes: ours=$(wc -c < "$SCRATCH/x/ours.md") theirs=$(wc -c < "$SCRATCH/x/theirs.md") pr6=$(wc -c < "$SCRATCH/x/pr6.md")"echo " #6 README == #10 README ? $(cmp -s "$SCRATCH/x/ours.md" "$SCRATCH/x/pr6.md" && echo YES || echo NO)"echo " patch bytes identical on #10 and #11 ? $(cmp -s "$SCRATCH/x/ours.patch" "$SCRATCH/x/theirs.patch" && echo YES || echo NO)"echo " patch sha256 = $(sha256sum "$SCRATCH/x/ours.patch" | cut -c1-16)"
hdr "1 GROUND TRUTH from the shipped patch: numstat + declared TrainConfigs"git -C "$W" apply --numstat "$SCRATCH/x/ours.patch" > "$SCRATCH/x/numstat.txt" 2>"$SCRATCH/x/numstat.err" \ || { echo " git apply --numstat FAILED:"; cat "$SCRATCH/x/numstat.err"; exit 3; }awk '{i+=$1; d+=$2; n++} END{printf " %d file(s), +%d insertions, -%d deletions\n", n, i, d}' "$SCRATCH/x/numstat.txt"sed 's/^/ /' "$SCRATCH/x/numstat.txt"echo " --- pi05_cooking_* TrainConfigs DECLARED by the patch (added lines only) ---"grep -E '^\+' "$SCRATCH/x/ours.patch" | grep -oE 'name="pi05_cooking_[A-Za-z0-9_]*"' | sort -u | sed 's/^/ /'NCFG=$(grep -E '^\+' "$SCRATCH/x/ours.patch" | grep -oE 'name="pi05_cooking_[A-Za-z0-9_]*"' | sort -u | wc -l)echo " declared count = $NCFG"
hdr "2 every numeric claim on each README, against that ground truth"python3 "$R/scripts/real/patchexport_readme_numbers.py" \ "$SCRATCH/x/numstat.txt" "$NCFG" ours:"$SCRATCH/x/ours.md" theirs:"$SCRATCH/x/theirs.md"NRC=$?echo " numbers checker rc=$NRC"
hdr "3 fold-in cost in BOTH directions (the existing residual tool)"echo "--- if OURS is the base: what of THEIRS would have to be folded in ---"python3 "$R/scripts/real/patchexport_union_residual.py" "$SCRATCH/x/ours.md:$SCRATCH/x/ours.md:$SCRATCH/x/theirs.md"echo "--- if THEIRS is the base: what of OURS would have to be folded in ---"python3 "$R/scripts/real/patchexport_union_residual.py" "$SCRATCH/x/theirs.md:$SCRATCH/x/ours.md:$SCRATCH/x/theirs.md"
hdr "4 does #11 ship a test that PINS that page, and what does it assert about?"git -C "$W" grep -l "openpi/README" pr-11 -- tests/ | sed 's/^/ /'for f in $(git -C "$W" grep -l "openpi/README" pr-11 -- tests/ | sed 's#^pr-11:##'); do echo " --- $f (on #11) ---" git -C "$W" show "pr-11:$f" | grep -nE "openpi/README|def test_|assert " | head -30 | sed 's/^/ /'doneecho " --- do those files exist on #10? ---"for f in $(git -C "$W" grep -l "openpi/README" pr-11 -- tests/ | sed 's#^pr-11:##'); do git -C "$W" cat-file -e "pr-10:$f" 2>/dev/null && echo " present on #10: $f" || echo " ABSENT on #10: $f"done
hdr "DONE"rsm_rise/scripts/real/patchexport_checkenv_capdiff.shAdded+102
rsm_rise/scripts/real/patchexport_cibaseline_verify.shAdded+221
rsm_rise/scripts/real/patchexport_clean_checks.pyAdded+171
rsm_rise/scripts/real/patchexport_clean_inference_env.shAdded+91
rsm_rise/scripts/real/patchexport_deploy_checks.shAdded+50
rsm_rise/scripts/real/patchexport_deploy_nosplit.pyAdded+41
rsm_rise/scripts/real/patchexport_deployment_yml_union.pyAdded+170
rsm_rise/scripts/real/patchexport_dotted_selector.shAdded+139
rsm_rise/scripts/real/patchexport_dp_pin.pyAdded+198
rsm_rise/scripts/real/patchexport_dp_pin_push.shAdded+220
rsm_rise/scripts/real/patchexport_dp_pin_readers.pyAdded+58
rsm_rise/scripts/real/patchexport_envc_probe.shAdded+55
rsm_rise/scripts/real/patchexport_genq_sparse.shAdded+98
rsm_rise/scripts/real/patchexport_guard_controls_merged.shAdded+128
rsm_rise/scripts/real/patchexport_import_winner.pyAdded+73
rsm_rise/scripts/real/patchexport_item1.shAdded+253
rsm_rise/scripts/real/patchexport_item2_checks.pyAdded+135
rsm_rise/scripts/real/patchexport_item2_export.shAdded+165
rsm_rise/scripts/real/patchexport_item2_probe.pyAdded+175
rsm_rise/scripts/real/patchexport_item2_probe.shAdded+43
rsm_rise/scripts/real/patchexport_item2_validate.shAdded+96
rsm_rise/scripts/real/patchexport_item3_apply_fix.pyAdded+91
rsm_rise/scripts/real/patchexport_item3_checks.pyAdded+157
rsm_rise/scripts/real/patchexport_item3_genq_pack.pyAdded+75
rsm_rise/scripts/real/patchexport_item3_probe.pyAdded+90
rsm_rise/scripts/real/patchexport_item3_probe.shAdded+94
rsm_rise/scripts/real/patchexport_item3_provenance.shAdded+37
rsm_rise/scripts/real/patchexport_item3_repatch.shAdded+81
rsm_rise/scripts/real/patchexport_item3_validate.shAdded+124
rsm_rise/scripts/real/patchexport_item4_mimicgen.shAdded+145
rsm_rise/scripts/real/patchexport_livemark.patchAdded+117
rsm_rise/scripts/real/patchexport_livemark.pyAdded+132
rsm_rise/scripts/real/patchexport_livemark.shAdded+230
rsm_rise/scripts/real/patchexport_livemark_ci.shAdded+74
rsm_rise/scripts/real/patchexport_merge_gate.shAdded+141
rsm_rise/scripts/real/patchexport_merge_order_probe.shAdded+125
rsm_rise/scripts/real/patchexport_merged_tests.shAdded+181
rsm_rise/scripts/real/patchexport_merged_tests_detail.shAdded+176
rsm_rise/scripts/real/patchexport_models_conflict_probe.shAdded+82
rsm_rise/scripts/real/patchexport_models_union.pyAdded+186
rsm_rise/scripts/real/patchexport_openpi_numbers.pyAdded+92
rsm_rise/scripts/real/patchexport_openpi_readme_fix.pyAdded+87
rsm_rise/scripts/real/patchexport_openpi_readme_push.shAdded+134
rsm_rise/scripts/real/patchexport_order_cost.shAdded+159
rsm_rise/scripts/real/patchexport_owner_handoff.shAdded+190
rsm_rise/scripts/real/patchexport_pi05_infer.pyAdded+120
rsm_rise/scripts/real/patchexport_pins_doc_fix_push.shAdded+147
rsm_rise/scripts/real/patchexport_pipprobe.shAdded+6
rsm_rise/scripts/real/patchexport_quickstart_weight.shAdded+110
rsm_rise/scripts/real/patchexport_readme_decide.shAdded+76