rli14 commited on
Commit
fa4fc7d
·
verified ·
1 Parent(s): 9999d98

rsm_rise code snapshot (HF_PUSH_ALL) (part 9)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. rsm_rise/scripts/real/patchexport_checkenv_capdiff.sh +102 -0
  2. rsm_rise/scripts/real/patchexport_cibaseline_verify.sh +221 -0
  3. rsm_rise/scripts/real/patchexport_clean_checks.py +171 -0
  4. rsm_rise/scripts/real/patchexport_clean_inference_env.sh +91 -0
  5. rsm_rise/scripts/real/patchexport_deploy_checks.sh +50 -0
  6. rsm_rise/scripts/real/patchexport_deploy_nosplit.py +41 -0
  7. rsm_rise/scripts/real/patchexport_deployment_yml_union.py +170 -0
  8. rsm_rise/scripts/real/patchexport_dotted_selector.sh +139 -0
  9. rsm_rise/scripts/real/patchexport_dp_pin.py +198 -0
  10. rsm_rise/scripts/real/patchexport_dp_pin_push.sh +220 -0
  11. rsm_rise/scripts/real/patchexport_dp_pin_readers.py +58 -0
  12. rsm_rise/scripts/real/patchexport_envc_probe.sh +55 -0
  13. rsm_rise/scripts/real/patchexport_genq_sparse.sh +98 -0
  14. rsm_rise/scripts/real/patchexport_guard_controls_merged.sh +128 -0
  15. rsm_rise/scripts/real/patchexport_import_winner.py +73 -0
  16. rsm_rise/scripts/real/patchexport_item1.sh +253 -0
  17. rsm_rise/scripts/real/patchexport_item2_checks.py +135 -0
  18. rsm_rise/scripts/real/patchexport_item2_export.sh +165 -0
  19. rsm_rise/scripts/real/patchexport_item2_probe.py +175 -0
  20. rsm_rise/scripts/real/patchexport_item2_probe.sh +43 -0
  21. rsm_rise/scripts/real/patchexport_item2_validate.sh +96 -0
  22. rsm_rise/scripts/real/patchexport_item3_apply_fix.py +91 -0
  23. rsm_rise/scripts/real/patchexport_item3_checks.py +157 -0
  24. rsm_rise/scripts/real/patchexport_item3_genq_pack.py +75 -0
  25. rsm_rise/scripts/real/patchexport_item3_probe.py +90 -0
  26. rsm_rise/scripts/real/patchexport_item3_probe.sh +94 -0
  27. rsm_rise/scripts/real/patchexport_item3_provenance.sh +37 -0
  28. rsm_rise/scripts/real/patchexport_item3_repatch.sh +81 -0
  29. rsm_rise/scripts/real/patchexport_item3_validate.sh +124 -0
  30. rsm_rise/scripts/real/patchexport_item4_mimicgen.sh +145 -0
  31. rsm_rise/scripts/real/patchexport_livemark.patch +117 -0
  32. rsm_rise/scripts/real/patchexport_livemark.py +132 -0
  33. rsm_rise/scripts/real/patchexport_livemark.sh +230 -0
  34. rsm_rise/scripts/real/patchexport_livemark_ci.sh +74 -0
  35. rsm_rise/scripts/real/patchexport_merge_gate.sh +141 -0
  36. rsm_rise/scripts/real/patchexport_merge_order_probe.sh +125 -0
  37. rsm_rise/scripts/real/patchexport_merged_tests.sh +181 -0
  38. rsm_rise/scripts/real/patchexport_merged_tests_detail.sh +176 -0
  39. rsm_rise/scripts/real/patchexport_models_conflict_probe.sh +82 -0
  40. rsm_rise/scripts/real/patchexport_models_union.py +186 -0
  41. rsm_rise/scripts/real/patchexport_openpi_numbers.py +92 -0
  42. rsm_rise/scripts/real/patchexport_openpi_readme_fix.py +87 -0
  43. rsm_rise/scripts/real/patchexport_openpi_readme_push.sh +134 -0
  44. rsm_rise/scripts/real/patchexport_order_cost.sh +159 -0
  45. rsm_rise/scripts/real/patchexport_owner_handoff.sh +190 -0
  46. rsm_rise/scripts/real/patchexport_pi05_infer.py +120 -0
  47. rsm_rise/scripts/real/patchexport_pins_doc_fix_push.sh +147 -0
  48. rsm_rise/scripts/real/patchexport_pipprobe.sh +6 -0
  49. rsm_rise/scripts/real/patchexport_quickstart_weight.sh +110 -0
  50. rsm_rise/scripts/real/patchexport_readme_decide.sh +76 -0
rsm_rise/scripts/real/patchexport_checkenv_capdiff.sh ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # rsm_real#5 -- the add/add resolution for scripts/check_env.py, measured as CAPABILITIES, not lines.
3
+ #
4
+ # Run 21 established that the 4 "hand-merge" files are two independently written versions, and that
5
+ # every gate I have run resolves them by taking the #6-#10 side whole. A line diff cannot say whether
6
+ # that loses anything that MATTERS: ours generalised the patch-completeness check to every repo, so a
7
+ # line present only on #11's side may be the same check in different words. The unit that matters is
8
+ # the capability the report prints. So RUN both implementations on the same tree and diff the report.
9
+ #
10
+ # check_env.py is by design a report that always exits 0, so both sides run anywhere; the MISSING lines
11
+ # are as informative as the PASS lines because the question is which capabilities are NAMED at all.
12
+ set -uo pipefail
13
+ source /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_resolve.sh
14
+ SCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run38}
15
+ PRS=${PRS:-"6 7 8 9 10"}
16
+ SC_PR=${SC_PR:-11}
17
+ export GIT_TERMINAL_PROMPT=0
18
+ scrub(){ sed 's#https://[^@]*@#https://<redacted>@#g'; }
19
+ hdr(){ echo; echo "=================== $* ==================="; }
20
+ mkdir -p "${SCRATCH:?}" || exit 1
21
+ M=$SCRATCH/capdiff
22
+
23
+ hdr "0 context"
24
+ echo "host=$(hostname) job=${LSB_JOBID:-none} scratch=$SCRATCH python=$(python3 -V 2>&1)"
25
+
26
+ hdr "1 order-A merge, then the PUBLISHED resolution (take the #6-#10 side of the 4 add/add files)"
27
+ TOK=$(grep -m1 'https://richardrl:' ~/.git-credentials | sed -E 's|https://richardrl:([^@]*)@.*|\1|')
28
+ [ -n "$TOK" ] || { echo "NO TOKEN"; exit 1; }
29
+ rm -rf "${M:?}"; git init --quiet "$M" || exit 1
30
+ printf '[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"
31
+ unset TOK
32
+ git -C "$M" fetch --quiet origin main 2>&1 | scrub
33
+ git -C "$M" checkout --quiet -b main FETCH_HEAD 2>&1 | scrub
34
+ [ -f "$M/README.md" ] || { echo "CLONE FAILED"; exit 1; }
35
+ git -C "$M" config user.email noreply@anthropic.com; git -C "$M" config user.name "capdiff gate"
36
+ for n in $PRS $SC_PR; do git -C "$M" fetch --quiet origin "pull/$n/head:pr-$n" 2>&1 | scrub || exit 1; done
37
+ SC_SHA=$(git -C "$M" rev-parse "pr-$SC_PR")
38
+ LIVE=$(git -C "$M" ls-remote origin "refs/pull/$SC_PR/head" 2>/dev/null | awk '{print $1}')
39
+ [ -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; }
40
+ echo "staleness guard: OK -- sc == live head of PR #$SC_PR ($(echo "$LIVE"|cut -c1-7))"
41
+ 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; }; done
42
+ FIVE=$(git -C "$M" rev-parse HEAD)
43
+ git -C "$M" merge --no-ff -m "Merge PR #$SC_PR" "pr-$SC_PR" >/dev/null 2>&1
44
+ # keep BOTH sides of check_env.py before resolving, so each can be executed against the same tree
45
+ git -C "$M" show ":2:scripts/check_env.py" > "$SCRATCH/ours.py" || exit 2
46
+ git -C "$M" show ":3:scripts/check_env.py" > "$SCRATCH/theirs.py" || exit 2
47
+ pe_resolve "$M" "$FIVE" scripts/setup_env.sh SETUP.md rise_stack/openpi/README.md scripts/check_env.py
48
+ [ -z "$(git -C "$M" diff --name-only --diff-filter=U)" ] || { echo "RESOLUTION INCOMPLETE"; exit 2; }
49
+ git -C "$M" commit --quiet -m "scratch: order-A merge + take-ours resolution" || true
50
+ echo "resolved tree = $(git -C "$M" rev-parse --short HEAD^{tree})"
51
+ echo "shipped scripts/check_env.py == ours side: $(cmp -s "$M/scripts/check_env.py" "$SCRATCH/ours.py" && echo YES || echo NO)"
52
+
53
+ hdr "2 run BOTH implementations on the SAME resolved tree"
54
+ cp "$SCRATCH/ours.py" "$M/scripts/_ce_ours.py"
55
+ cp "$SCRATCH/theirs.py" "$M/scripts/_ce_theirs.py"
56
+ for s in ours theirs; do
57
+ echo "--- $s: python3 scripts/_ce_$s.py ---"
58
+ ( cd "$M" && python3 "scripts/_ce_$s.py" > "$SCRATCH/report_$s.txt" 2> "$SCRATCH/report_$s.err" )
59
+ rc=$?
60
+ echo " rc=$rc stdout=$(wc -l < "$SCRATCH/report_$s.txt") lines stderr=$(wc -l < "$SCRATCH/report_$s.err") lines"
61
+ 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/^/ /'; fi
62
+ done
63
+
64
+ hdr "3 the reports, verbatim"
65
+ for s in ours theirs; do echo; echo "----- $s -----"; cat "$SCRATCH/report_$s.txt"; done
66
+
67
+ hdr "4 CAPABILITY-NAME diff -- what the published resolution stops REPORTING"
68
+ python3 - "$SCRATCH/report_ours.txt" "$SCRATCH/report_theirs.txt" <<'PY'
69
+ import re, sys
70
+ def caps(p):
71
+ out=[]
72
+ for l in open(p,encoding='utf-8',errors='replace'):
73
+ m=re.match(r"^ (PASS|MISSING|n/a|INFO|)\s{2,}(\S.*?)\s{2,}", l)
74
+ if m and m.group(2).strip(): out.append((m.group(1).strip() or '-', m.group(2).strip()))
75
+ return out
76
+ o,t=caps(sys.argv[1]),caps(sys.argv[2])
77
+ def norm(n): return re.sub(r"\s+"," ",n.lstrip('^ ').strip()).lower()
78
+ no={norm(n) for _,n in o}; nt={norm(n) for _,n in t}
79
+ print(f"capability lines: ours={len(o)} theirs={len(t)}")
80
+ print(f"\nREPORTED ONLY BY #11's SIDE -- lost when the resolution takes ours ({len(nt-no)}):")
81
+ for st,n in t:
82
+ if norm(n) in nt-no: print(f" [{st}] {n}")
83
+ print(f"\nREPORTED ONLY BY THE #6-#10 SIDE -- gained ({len(no-nt)}):")
84
+ for st,n in o:
85
+ if norm(n) in no-nt: print(f" [{st}] {n}")
86
+ print(f"\nin both ({len(no&nt)}): {sorted(no&nt)}")
87
+ print("\nVERDICT:", "take-ours loses NO named capability" if not (nt-no)
88
+ else f"take-ours stops reporting {len(nt-no)} capability name(s) listed above")
89
+ PY
90
+
91
+ hdr "5 structural diff of the two docs (headings, not lines)"
92
+ for f in SETUP.md rise_stack/openpi/README.md; do
93
+ s=$(echo "$f" | tr '/' '_')
94
+ git -C "$M" show ":2:$f" > "$SCRATCH/$s.ours" 2>/dev/null || git -C "$M" show "$FIVE:$f" > "$SCRATCH/$s.ours"
95
+ git -C "$M" show "$SC_SHA:$f" > "$SCRATCH/$s.theirs"
96
+ echo; echo "--- $f headings ---"
97
+ echo " ours:"; grep -nE '^#+ ' "$SCRATCH/$s.ours" | sed 's/^/ /'
98
+ echo " theirs:"; grep -nE '^#+ ' "$SCRATCH/$s.theirs" | sed 's/^/ /'
99
+ done
100
+
101
+ hdr "OVERALL rc=0"
102
+ exit 0
rsm_rise/scripts/real/patchexport_cibaseline_verify.sh ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # rsm_real#5 run 30 -- (a) prove the CI-baseline differ extraction is BEHAVIOUR-PRESERVING, and
3
+ # (b) re-measure the six-way merged tree now that #11's head moved to fdfa758f, which VENDORS four
4
+ # rsm_libero modules under rise_stack/rsm/ -- the directory #8 deletes and pe_trial_merge asserts
5
+ # gone. If #11's two new rsm_libero tests are in the merged workflow but their subject is deleted
6
+ # by #8, the merged tree fails tests neither side fails alone. That is a cross-PR interaction
7
+ # nobody has measured yet, and it is exactly what this differ exists to catch.
8
+ #
9
+ # The extraction is only worth doing if it cannot change what the gates saw, so the OLD inline block
10
+ # (copied verbatim out of run 28's setup_md gate) and the NEW pe_ci_baseline run against the SAME two
11
+ # trees and must agree on all four derived sets AND on the verdict -- not "both printed OK".
12
+ set -uo pipefail
13
+ source /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_resolve.sh
14
+ SCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run96}
15
+ VENV=${VENV:-/proj/dmfexp/zwhong/scratch_patchexport/run29/venv_ci}
16
+ export GIT_TERMINAL_PROMPT=0 PYTHONDONTWRITEBYTECODE=1 OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1
17
+ scrub(){ sed 's#https://[^@]*@#https://<redacted>@#g'; }
18
+ hdr(){ echo; echo "=================== $* ==================="; date -u; }
19
+ die(){ echo "VERIFY FAILED: $*"; exit 7; }
20
+ PY=$VENV/bin/python; [ -x "$PY" ] || die "no venv at $VENV"
21
+ export PE_PY=$PY
22
+ mkdir -p "${SCRATCH:?}" || exit 1
23
+
24
+ hdr "0 context"
25
+ echo "host=$(hostname) job=${LSB_JOBID:-none} scratch=$SCRATCH py=$("$PY" -V 2>&1)"
26
+
27
+ clone(){
28
+ local W=$1 TOK
29
+ TOK=$(grep -m1 'https://richardrl:' ~/.git-credentials | sed -E 's|https://richardrl:([^@]*)@.*|\1|')
30
+ [ -n "$TOK" ] || die "no token"
31
+ rm -rf "${W:?}"; git init --quiet "$W" || exit 1
32
+ 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"
33
+ unset TOK
34
+ git -C "$W" fetch --quiet origin 2>&1 | scrub || die "fetch failed"
35
+ git -C "$W" config user.email noreply@anthropic.com
36
+ git -C "$W" config user.name "richardrl"
37
+ }
38
+
39
+ hdr "1 live heads"
40
+ W=$SCRATCH/merged
41
+ clone "$W"
42
+ MAIN=$(git -C "$W" rev-parse origin/main)
43
+ echo " main = ${MAIN:0:8} $(git -C "$W" log -1 --format='%ad %an | %s' --date=iso origin/main)"
44
+ for n in 6 7 8 9 10 11; do
45
+ echo " #$n head = $(git -C "$W" ls-remote origin "refs/pull/$n/head" | cut -c1-8)"
46
+ done
47
+ SC_HEAD=$(git -C "$W" ls-remote origin "refs/pull/11/head" | awk '{print $1}')
48
+
49
+ hdr "2 the full six-way trial merge (shared pe_trial_merge)"
50
+ pe_trial_merge "$W" origin/main || die "trial merge refused/failed"
51
+ echo " shape:"; printf '%s' "$PE_TRIAL_SHAPE" | sed 's/^/ /'
52
+ echo " merged head = ${PE_TRIAL_HEAD:0:12} tree = $(git -C "$W" rev-parse --short 'HEAD^{tree}')"
53
+ printf '%s' "$PE_TRIAL_SHAPE" | grep -q "^11 conflicted" || die "shape changed: #11 no longer conflicts -- re-derive the runbook"
54
+ 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
55
+
56
+ hdr "3 what #11's new head brought, and what the merge does with it"
57
+ echo " #11 head = ${SC_HEAD:0:8}"
58
+ git -C "$W" fetch --quiet --force origin "pull/11/head:pr-11" 2>&1 | scrub
59
+ echo " files #11 adds under rise_stack/rsm/ :"
60
+ git -C "$W" ls-tree -r --name-only pr-11 -- rise_stack/rsm | sed 's/^/ /'
61
+ echo " the SAME paths on the merged tree (#8 deletes the directory):"
62
+ got=$(git -C "$W" ls-tree -r --name-only HEAD -- rise_stack/rsm)
63
+ echo "${got:- (absent -- as pe_trial_merge asserts)}" | sed 's/^/ /'
64
+ echo " #11's rsm_libero tests, present on the merged tree?"
65
+ for t in tests/test_rise_stack_rsm_libero_closure.py tests/test_rise_stack_rsm_libero_live.py; do
66
+ if git -C "$W" cat-file -e "HEAD:$t" 2>/dev/null; then echo " PRESENT $t"; else echo " absent $t"; fi
67
+ done
68
+ echo " named by the merged workflow?"
69
+ pe_ci_set "$W" | tr ' ' '\n' | grep -E 'rsm_libero' | sed 's/^/ /' || echo " (not named)"
70
+
71
+ hdr "3b the models.py / test_deployment_models.py UNION on the merged tree"
72
+ # #11's new head rewrote the same dependency_report RSM branch that #8 did, so the runbook grew a
73
+ # semantic union (patchexport_models_union.py). Assert the merged file carries BOTH sides, not one.
74
+ for need in "which_scorer import resolve" "_available(\"rsm_libero\")" "has_dir or _available" "rise_stack/rsm_libero/UPSTREAM_COMMIT.txt"; do
75
+ grep -qF "$need" "$W/real/deployment/models.py" || die "the merged models.py lost: $need"
76
+ echo " OK merged models.py carries: $need"
77
+ done
78
+ [ "$(grep -cF '_available("rsm_libero")' "$W/real/deployment/models.py")" = 2 ] \
79
+ || die "ours' installed-package test is not in BOTH branches of the merged models.py"
80
+ "$PY" -c "import ast,sys; ast.parse(open(sys.argv[1]).read())" "$W/real/deployment/models.py" || die "merged models.py does not parse"
81
+ "$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"
82
+ NT=$("$PY" - "$W/tests/test_deployment_models.py" <<'PYX'
83
+ import ast,sys
84
+ t=ast.parse(open(sys.argv[1]).read())
85
+ names=[n.name for n in t.body if isinstance(n,ast.FunctionDef)]
86
+ assert len(names)==len(set(names)), "duplicate test definitions: %s"%names
87
+ print(len(names))
88
+ PYX
89
+ ) || die "the merged test file has duplicate definitions"
90
+ echo " merged test_deployment_models.py defines $NT unique tests"
91
+ for t in test_installed_rsm_libero_satisfies_the_scorer_source_requirement test_rsm_dependencies_are_satisfied_by_the_vendored_scorer; do
92
+ grep -q "def $t(" "$W/tests/test_deployment_models.py" || die "the merged test file lost $t"
93
+ echo " OK merged test file keeps $t"
94
+ done
95
+
96
+ hdr "4 baseline worktree: main alone"
97
+ MW=$SCRATCH/mainonly
98
+ rm -rf "${MW:?}"
99
+ git -C "$W" worktree add --quiet --detach "$MW" origin/main 2>&1 | scrub || die "cannot check out main alone"
100
+ echo " main alone at $(git -C "$W" rev-parse --short origin/main) in $MW"
101
+
102
+ hdr "5 sync the gate venv to the MERGED tree's requirements-deployment.txt (shared pe_ci_venv_sync)"
103
+ pe_ci_venv_sync "$W" || die "venv sync failed"
104
+
105
+ # ---- the OLD inline block, copied verbatim from run 28's setup_md gate --------------------------
106
+ # Only difference: `die` becomes a recorded verdict, so the two implementations can be compared on
107
+ # their outputs instead of one of them exiting the harness.
108
+ legacy_ci(){
109
+ local W=$1 MW=$2
110
+ L_RC=0; L_FILES=""; L_BASE=""; L_FAILED=""; L_NEW=""
111
+ ci_set(){ sed -n 's#^ *\(tests/test_[a-z_]*\.py\) *$#\1#p' "$1/.github/workflows/deployment.yml" | sort -u | tr '\n' ' '; }
112
+ run_ci(){ ( cd "$1" && PYTHONPATH= "$PY" -m pytest -q -p no:cacheprovider $2 2>&1 ); }
113
+ newfailures(){ comm -23 <(printf '%s\n' "$1" | sed '/^$/d' | sort -u) <(printf '%s\n' "$2" | sed '/^$/d' | sort -u); }
114
+ L_FILES=$(ci_set "$W"); [ -n "$L_FILES" ] || { L_RC=1; return; }
115
+ local f; for f in $L_FILES; do [ -e "$W/$f" ] || { L_RC=1; return; }; done
116
+ local MFILES BOUT OUT CTRL_NEW
117
+ MFILES=$(ci_set "$MW")
118
+ BOUT=$(run_ci "$MW" "$MFILES")
119
+ L_BASE=$(echo "$BOUT" | grep -E "^(FAILED|ERROR)" | awk '{print $2}' | sort -u)
120
+ OUT=$(run_ci "$W" "$L_FILES")
121
+ L_FAILED=$(echo "$OUT" | grep -E "^(FAILED|ERROR)" | awk '{print $2}' | sort -u)
122
+ CTRL_NEW=$(newfailures "$L_FAILED
123
+ tests/test_FABRICATED.py::nope" "$L_BASE")
124
+ echo "$CTRL_NEW" | grep -q FABRICATED || { L_RC=1; return; }
125
+ [ -z "$L_BASE" ] || { echo "$CTRL_NEW" | grep -qF "$(echo "$L_BASE" | head -1)" && { L_RC=1; return; }; }
126
+ L_NEW=$(newfailures "$L_FAILED" "$L_BASE")
127
+ [ -z "$L_NEW" ] || L_RC=1
128
+ }
129
+
130
+ hdr "6 the OLD inline block"
131
+ legacy_ci "$W" "$MW"
132
+ echo " legacy rc=$L_RC"
133
+ echo " legacy CI set : $L_FILES"
134
+ echo " legacy baseline: $(echo $L_BASE)"
135
+ echo " legacy merged : $(echo $L_FAILED)"
136
+ echo " legacy NEW : $(echo $L_NEW)"
137
+
138
+ hdr "7 the NEW pe_ci_baseline, same two trees"
139
+ pe_ci_baseline "$W" "$MW"; N_RC=$?
140
+ echo " new rc=$N_RC"
141
+
142
+ hdr "8 equivalence: all four derived sets and the verdict must match"
143
+ eq(){ [ "$(echo $2)" = "$(echo $3)" ] && echo " OK $1 identical" || die "$1 DIFFERS: legacy=[$(echo $2)] new=[$(echo $3)]"; }
144
+ eq "CI set" "$L_FILES" "$PE_CI_FILES"
145
+ eq "baseline" "$L_BASE" "$PE_CI_BASE"
146
+ eq "merged" "$L_FAILED" "$PE_CI_FAILED"
147
+ eq "NEW" "$L_NEW" "$PE_CI_NEW"
148
+ [ "$L_RC" = "$N_RC" ] || die "verdict differs: legacy rc=$L_RC new rc=$N_RC"
149
+ echo " OK verdict identical (rc=$N_RC)"
150
+
151
+ hdr "9 controls on the NEW function -- it must not be inert"
152
+ # 9a a fabricated failing test, named by the workflow, must come back as a NEW failure.
153
+ CW=$SCRATCH/ctrl; rm -rf "${CW:?}"
154
+ cp -a "$W" "$CW" 2>/dev/null || die "cannot copy the merged tree"
155
+ rm -rf "$CW/.git/worktrees" 2>/dev/null
156
+ cat > "$CW/tests/test_pe_ctrl_planted.py" <<'PY'
157
+ def test_planted_must_be_reported_as_new():
158
+ assert False, "planted by patchexport_cibaseline_verify.sh step 9a"
159
+ PY
160
+ "$PY" - "$CW/.github/workflows/deployment.yml" <<'PY'
161
+ import sys,re
162
+ p=sys.argv[1]; s=open(p).read()
163
+ m=re.search(r'^([ \t]+)tests/test_[a-z_]*\.py *$', s, re.M)
164
+ assert m, "no CI test line to anchor to"
165
+ s=s[:m.end()]+"\n"+m.group(1)+"tests/test_pe_ctrl_planted.py"+s[m.end():]
166
+ open(p,'w').write(s)
167
+ print(" anchored the planted test after", m.group(0).strip())
168
+ PY
169
+ pe_ci_set "$CW" | tr ' ' '\n' | grep -q test_pe_ctrl_planted || die "control 9a did not land in the CI set"
170
+ if pe_ci_baseline "$CW" "$MW" >"$SCRATCH/ctrl9a.log" 2>&1; then
171
+ sed 's/^/ /' "$SCRATCH/ctrl9a.log" | tail -20; die "control 9a: a planted failing test was NOT reported"
172
+ fi
173
+ grep -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"; }
174
+ echo " OK 9a planted failure reported as NEW: $(echo $PE_CI_NEW)"
175
+ # 9b a workflow naming a test file that does not exist must be a refusal, not a silent empty set.
176
+ rm -f "$CW/tests/test_pe_ctrl_planted.py"
177
+ pe_ci_baseline "$CW" "$MW" >"$SCRATCH/ctrl9b.log" 2>&1 && die "control 9b: a missing named test file passed"
178
+ grep -q "which does not exist" "$SCRATCH/ctrl9b.log" || { tail -5 "$SCRATCH/ctrl9b.log" | sed 's/^/ /'; die "control 9b refused for the wrong reason"; }
179
+ echo " OK 9b workflow naming a missing test file is refused"
180
+ # 9c an empty/absent workflow must refuse rather than measure nothing.
181
+ : > "$CW/.github/workflows/deployment.yml"
182
+ pe_ci_baseline "$CW" "$MW" >"$SCRATCH/ctrl9c.log" 2>&1 && die "control 9c: an empty workflow passed"
183
+ 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"; }
184
+ echo " OK 9c empty workflow is refused"
185
+ # 9d the union builder must refuse to run twice (its output carries the marker).
186
+ U=$SCRATCH/union; rm -rf "$U"; mkdir -p "$U"
187
+ git -C "$W" show "origin/main:real/deployment/models.py" > "$U/base"
188
+ git -C "$W" show "pr-11:real/deployment/models.py" > "$U/theirs"
189
+ git -C "$W" show "pr-8:real/deployment/models.py" > "$U/ours" 2>/dev/null || \
190
+ 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"
191
+ "$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"
192
+ "$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"
193
+ grep -q "does not run twice" "$U/e9d" || { cat "$U/e9d" | sed 's/^/ /'; die "control 9d refused for the wrong reason"; }
194
+ echo " OK 9d the union refuses to run on its own output"
195
+ # 9e a side missing its own contribution must be refused, not silently half-applied.
196
+ sed 's/from rise_stack.which_scorer import resolve as _resolve_scorer/pass # stripped by control 9e/' "$U/theirs" > "$U/theirs_stripped"
197
+ "$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"
198
+ 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"; }
199
+ echo " OK 9e a side without its own contribution is refused"
200
+ # 9f a moved anchor must refuse rather than write a file that lost one side.
201
+ sed 's/"vendored", "env", "env-invalid"/"vendored", "env"/' "$U/theirs" > "$U/theirs_moved"
202
+ "$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"
203
+ grep -q "anchor occurs 0 times" "$U/e9f" || { cat "$U/e9f" | sed 's/^/ /'; die "control 9f refused for the wrong reason"; }
204
+ echo " OK 9f a moved anchor is refused"
205
+ rm -rf "$CW"
206
+
207
+ hdr "10 #11's negative-control ledger on the merged tree"
208
+ if [ -x "$W/tests/controls/run_guard_controls.sh" ]; then
209
+ ( cd "$W" && PYTHONPATH= PY=$PY bash tests/controls/run_guard_controls.sh 2>&1 ) | tail -25
210
+ echo " controls ledger rc=${PIPESTATUS[0]}"
211
+ else
212
+ echo " no tests/controls/run_guard_controls.sh on the merged tree"
213
+ fi
214
+
215
+ hdr "11 re-poll: did anything move while this ran?"
216
+ git -C "$W" fetch --quiet origin 2>&1 | scrub
217
+ echo " main now = $(git -C "$W" rev-parse --short origin/main) (was ${MAIN:0:7})"
218
+ echo " #11 now = $(git -C "$W" ls-remote origin refs/pull/11/head | cut -c1-8) (was ${SC_HEAD:0:8})"
219
+ git -C "$W" worktree remove --force "$MW" >/dev/null 2>&1 || true
220
+
221
+ hdr "VERIFY OK"
rsm_rise/scripts/real/patchexport_clean_checks.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """rsm_real#5 item 1 acceptance checks, run INSIDE the freshly built pinned openpi env.
3
+
4
+ C1 provenance: what was actually imported, and from where (a hidden research checkout must not be
5
+ able to satisfy the test silently).
6
+ C2 get_config("pi05_cooking_stock") + data.create() with the training split file ABSENT.
7
+ C3 the real stock BC checkpoint through the deployment adapter (rise_stack.policies), on a real
8
+ replay observation, with the split file still absent -> candidates [1, 10, 10], finite.
9
+ """
10
+ import argparse, dataclasses, hashlib, json, os, sys, time
11
+ from pathlib import Path
12
+
13
+ import numpy as np
14
+
15
+ RESEARCH = "/proj/dmfexp/zwhong/rsm_rise"
16
+ DATA = f"{RESEARCH}/data/real/rsm_cooking_v5"
17
+ PROMPT = "Follow the displayed cooking state sequence"
18
+
19
+
20
+ def md5(path, limit=None):
21
+ h = hashlib.md5()
22
+ with open(path, "rb") as fh:
23
+ while True:
24
+ b = fh.read(1 << 20)
25
+ if not b:
26
+ break
27
+ h.update(b)
28
+ if limit and fh.tell() > limit:
29
+ break
30
+ return h.hexdigest()
31
+
32
+
33
+ def real_frame(ep=0, i=0):
34
+ """One logged observation: both cameras + the 10-d absolute EE state, and the logged action."""
35
+ import av, pyarrow.parquet as pq
36
+ tab = pq.read_table(f"{DATA}/data/chunk-000/episode_{ep:06d}.parquet").to_pandas()
37
+ state = np.stack(tab["observation.state"].values).astype(np.float32)[i]
38
+ action = np.stack(tab["action"].values).astype(np.float32)[i: i + 10]
39
+ imgs = {}
40
+ for cam, key in (("global", "observation.images.global"), ("wrist", "observation.images.wrist")):
41
+ with av.open(f"{DATA}/videos/chunk-000/{key}/episode_{ep:06d}.mp4") as c:
42
+ st = c.streams.video[0]; st.thread_type = "AUTO"
43
+ for k, fr in enumerate(c.decode(st)):
44
+ if k == i:
45
+ imgs[cam] = fr.to_ndarray(format="rgb24")
46
+ break
47
+ return {"images": imgs, "state": state}, action
48
+
49
+
50
+ def main():
51
+ ap = argparse.ArgumentParser()
52
+ ap.add_argument("--repo", required=True)
53
+ ap.add_argument("--ckpt", required=True)
54
+ ap.add_argument("--missing-split", required=True)
55
+ ap.add_argument("--out", required=True)
56
+ ap.add_argument("--config", default="pi05_cooking_stock")
57
+ args = ap.parse_args()
58
+ rep = {"argv": sys.argv, "when": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())}
59
+
60
+ print("=== C1 provenance ===")
61
+ print("sys.executable =", sys.executable)
62
+ print("sys.prefix =", sys.prefix)
63
+ for v in ("RISE_ROOT", "RSM_LIBERO_DIR", "PYTHONPATH", "HF_HUB_OFFLINE"):
64
+ print(f"env {v:16s}= {os.environ.get(v, '<unset>')!r}")
65
+ sys.path.insert(0, args.repo)
66
+ mods = {}
67
+ import openpi, jax, numpy
68
+ import openpi.training.config as C
69
+ for m in (openpi, jax, numpy):
70
+ mods[m.__name__] = {"file": str(Path(m.__file__).resolve()),
71
+ "version": getattr(m, "__version__", None)}
72
+ import rise_stack
73
+ mods["rise_stack"] = {"file": str(Path(rise_stack.__file__).resolve()), "version": None}
74
+ for k, v in mods.items():
75
+ print(f"{k:12s} {v['version'] or '':10s} {v['file']}")
76
+ if v["file"].startswith(RESEARCH + "/third_party") or "/rsm_rise/env/" in v["file"]:
77
+ raise SystemExit(f"FATAL: {k} was imported from the research checkout: {v['file']}")
78
+ print("jax devices =", jax.devices())
79
+ rep["modules"] = mods
80
+ rep["jax_devices"] = [str(d) for d in jax.devices()]
81
+
82
+ print("\n=== C2 config + inference transforms with NO training split file ===")
83
+ missing = args.missing_split
84
+ print("missing split path:", missing, "exists =", Path(missing).exists())
85
+ orig_get = C.get_config
86
+
87
+ def split_free(name):
88
+ cfg = orig_get(name)
89
+ if hasattr(cfg.data, "split_json"):
90
+ cfg = dataclasses.replace(cfg, data=dataclasses.replace(cfg.data, split_json=missing))
91
+ return cfg
92
+
93
+ C.get_config = split_free # every consumer, incl. the deployment adapter, now gets it
94
+ cfg = C.get_config(args.config)
95
+ print("data factory =", type(cfg.data).__name__, "split_json =", cfg.data.split_json)
96
+ t0 = time.time()
97
+ dc = cfg.data.create(cfg.assets_dirs, cfg.model)
98
+ print(f"data.create() OK in {time.time()-t0:.2f}s")
99
+ print(" episodes =", dc.episodes)
100
+ print(" episodes_required_from =", getattr(dc, "episodes_required_from", "<field absent>"))
101
+ print(" norm_stats from config =", None if dc.norm_stats is None else sorted(dc.norm_stats),
102
+ f"(loaded from assets_base_dir={cfg.assets_base_dir!r}, which exists on THIS machine; on a "
103
+ "deployment machine it does not and _load_norm_stats logs 'skipping' -- either way "
104
+ "create_trained_policy takes the norm stats from <checkpoint>/assets)")
105
+ print(" data_transforms.inputs =", [type(t).__name__ for t in dc.data_transforms.inputs])
106
+ print(" data_transforms.outputs=", [type(t).__name__ for t in dc.data_transforms.outputs])
107
+ print(" model_transforms.inputs=", [type(t).__name__ for t in dc.model_transforms.inputs])
108
+ print(" action_sequence_keys =", dc.action_sequence_keys, "asset_id =", dc.asset_id)
109
+ rep["C2"] = {"episodes": dc.episodes, "episodes_required_from": getattr(dc, "episodes_required_from", None),
110
+ "data_inputs": [type(t).__name__ for t in dc.data_transforms.inputs],
111
+ "data_outputs": [type(t).__name__ for t in dc.data_transforms.outputs],
112
+ "model_inputs": [type(t).__name__ for t in dc.model_transforms.inputs],
113
+ "asset_id": dc.asset_id}
114
+
115
+ print("\n=== C3 real stock BC checkpoint through the deployment adapter ===")
116
+ ck = Path(args.ckpt)
117
+ ident = {"path": str(ck),
118
+ "metadata_md5": md5(ck / "_CHECKPOINT_METADATA") if (ck / "_CHECKPOINT_METADATA").is_file() else None,
119
+ "norm_stats": None}
120
+ ns = list(ck.glob("assets/*/*/norm_stats.json"))
121
+ if ns:
122
+ ident["norm_stats"] = {"path": str(ns[0].relative_to(ck)), "md5": md5(ns[0]),
123
+ "bytes": ns[0].stat().st_size}
124
+ print("checkpoint identity:", json.dumps(ident, indent=1))
125
+ rep["checkpoint"] = ident
126
+
127
+ from rise_stack.policies import build # the deployment factory used by real/deployment/models.py
128
+ t0 = time.time()
129
+ # openpi owns its normalisation inside the checkpoint, so action_norm is None for this kind
130
+ pol = build(f"openpi:{args.config}:{args.ckpt}", None, seed=0, device="cpu", openpi_batch=0)
131
+ print(f"policy built in {time.time()-t0:.1f}s: kind={pol.kind} H={pol.H} D={pol.D} "
132
+ f"jax_device={getattr(pol, 'jax_device', None)} batch={pol.batch}")
133
+ print("loaded openpi module (after construction) =", sys.modules['openpi'].__file__)
134
+
135
+ try:
136
+ obs, logged = real_frame()
137
+ src = "logged replay frame: episode 0, frame 0"
138
+ except Exception as e:
139
+ print("replay frame unavailable (%s: %s) -- falling back to a synthetic observation" % (type(e).__name__, e))
140
+ obs = {"images": {"global": np.zeros((224, 224, 3), np.uint8),
141
+ "wrist": np.zeros((224, 224, 3), np.uint8)},
142
+ "state": np.zeros(10, np.float32)}
143
+ logged, src = None, "synthetic zero observation"
144
+ print("observation:", src, {k: v.shape for k, v in obs["images"].items()}, "state", obs["state"].shape)
145
+
146
+ t0 = time.time()
147
+ cand = pol.candidates(obs, 1, 10)
148
+ dt = time.time() - t0
149
+ cand = np.asarray(cand)
150
+ print(f"candidates shape={cand.shape} dtype={cand.dtype} finite={bool(np.isfinite(cand).all())} "
151
+ f"in {dt:.1f}s ({dt*1000:.0f} ms, CPU)")
152
+ print("first action =", np.array2string(cand[0, 0], precision=6))
153
+ if logged is not None:
154
+ print("logged action =", np.array2string(logged[0], precision=6))
155
+ print("xyz L2 first action vs logged = %.3f cm" % (100 * float(np.linalg.norm(cand[0, 0, :3] - logged[0, :3]))))
156
+ print("per-dim min/max over the chunk:",
157
+ np.array2string(cand[0].min(0), precision=4), np.array2string(cand[0].max(0), precision=4))
158
+ ok = cand.shape == (1, 10, 10) and bool(np.isfinite(cand).all())
159
+ rep["C3"] = {"shape": list(cand.shape), "dtype": str(cand.dtype), "finite": bool(np.isfinite(cand).all()),
160
+ "latency_s": dt, "obs_source": src, "first_action": cand[0, 0].tolist(),
161
+ "logged_first_action": None if logged is None else logged[0].tolist(),
162
+ "xyz_l2_first_cm": None if logged is None else 100 * float(np.linalg.norm(cand[0, 0, :3] - logged[0, :3]))}
163
+ print("C3 VERDICT:", "PASS -- finite absolute actions [1, 10, 10]" if ok else "FAIL")
164
+ rep["ok"] = ok
165
+ Path(args.out).write_text(json.dumps(rep, indent=1, default=str))
166
+ print("wrote", args.out)
167
+ sys.exit(0 if ok else 1)
168
+
169
+
170
+ if __name__ == "__main__":
171
+ main()
rsm_rise/scripts/real/patchexport_clean_inference_env.sh ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # rsm_real#5 item 1, validation half: build the pinned openpi INFERENCE environment from scratch
3
+ # (uv venv, openpi's own uv.lock, network) with RISE_ROOT / RSM_LIBERO_DIR / PYTHONPATH scrubbed, then
4
+ # C1 report the actually loaded module paths and revisions
5
+ # C2 get_config("pi05_cooking_stock") + data.create() with NO training split file
6
+ # C3 the real stock BC checkpoint through the deployment adapter -> candidates [1,10,10], finite
7
+ # C4/C5 python -m real.deploy proposer=openpi real.algorithm=vanilla_bc real.simulate=true real.dry_run=true
8
+ # Nothing is written inside the rsm_rise tree or the rsm_real checkout.
9
+ set -uo pipefail
10
+ ROOT=/proj/dmfexp/zwhong/rsm_rise
11
+ SCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run2}
12
+ SRC=${SRC:-/proj/dmfexp/zwhong/scratch_patchexport/wt_main} # the PR worktree (or a github clone)
13
+ PIN=215abfb217dbac7d5f1273282331b9b1866c0479
14
+ CKPT=${CKPT:-$ROOT/hf_ckpt_root/pi05_bc_rsm_real_stock_s1_29999}
15
+ PATCHED=${PATCHED:-} # optional: an already-patched openpi tree to copy instead of re-patching
16
+ UV=${UV:-/u/zwhong/.local/bin/uv}
17
+
18
+ # ---- the scrub the issue asks for ---------------------------------------------------------------
19
+ unset RISE_ROOT RSM_LIBERO_DIR PYTHONPATH HF_TOKEN HF_HUB_OFFLINE OPENPI_DATA_HOME HF_LEROBOT_HOME
20
+ export PYTHONNOUSERSITE=1 PYTHONUNBUFFERED=1 TOKENIZERS_PARALLELISM=false
21
+ export UV_CACHE_DIR=$SCRATCH/uv_cache
22
+ export OPENPI_DATA_HOME=$SCRATCH/openpi_assets
23
+ export HF_HOME=$SCRATCH/hf_home
24
+ export JAX_PLATFORMS=${JAX_PLATFORMS:-cpu}
25
+
26
+ hdr(){ echo; echo "=================== $* ==================="; date -u; }
27
+ rc_all=0
28
+ chk(){ if [ "$1" -ne 0 ]; then echo "STEP FAILED rc=$1: $2"; rc_all=1; fi; }
29
+
30
+ hdr "0 context + env scrub"
31
+ echo "host=$(hostname) job=${LSB_JOBID:-none} scratch=$SCRATCH src=$SRC ckpt=$CKPT"
32
+ for v in RISE_ROOT RSM_LIBERO_DIR PYTHONPATH HF_HUB_OFFLINE; do echo " $v='${!v:-<unset>}'"; done
33
+ mkdir -p "${SCRATCH:?}" || exit 1
34
+ cd "${SCRATCH:?}" || exit 1
35
+
36
+ hdr "1 the repo under test"
37
+ rm -rf "${SCRATCH:?}/rsm_real"
38
+ git clone --quiet "$SRC" "${SCRATCH:?}/rsm_real" || exit 1
39
+ REPO=$SCRATCH/rsm_real
40
+ echo "rsm_real HEAD: $(git -C "$REPO" rev-parse HEAD) $(git -C "$REPO" log -1 --pretty=%s)"
41
+ ls "$REPO/rise_stack/openpi/" && md5sum "$REPO/rise_stack/openpi/rise_on_pi05.patch"
42
+
43
+ hdr "2 upstream openpi at the recorded pin, then the repo's patch"
44
+ rm -rf "${SCRATCH:?}/openpi"
45
+ if git clone --quiet https://github.com/Physical-Intelligence/openpi.git "${SCRATCH:?}/openpi"; then
46
+ echo "cloned openpi from GitHub"
47
+ else
48
+ echo "GitHub clone failed; falling back to the local mirror $ROOT/third_party/openpi (shallow at the pin)"
49
+ git clone --quiet --no-local "$ROOT/third_party/openpi" "${SCRATCH:?}/openpi" \
50
+ || git clone --quiet "$ROOT/third_party/openpi" "${SCRATCH:?}/openpi" || exit 1
51
+ fi
52
+ git -C "$SCRATCH/openpi" checkout --quiet "$(cat "$REPO/rise_stack/openpi/UPSTREAM_COMMIT.txt" | head -1)" || exit 1
53
+ echo "openpi HEAD: $(git -C "$SCRATCH/openpi" rev-parse HEAD)"
54
+ ( cd "$SCRATCH/openpi" && git apply "$REPO/rise_stack/openpi/rise_on_pi05.patch" && echo "git apply: OK" \
55
+ && git status --porcelain | sed -n '1,20p' )
56
+ chk $? "apply the committed patch"
57
+
58
+ hdr "3 the pinned inference environment (uv sync from openpi's own lock, then the deployment deps)"
59
+ ( cd "$SCRATCH/openpi" && "$UV" sync --frozen 2>&1 | tail -6 )
60
+ chk $? "uv sync"
61
+ VENV=$SCRATCH/openpi/.venv
62
+ PY=$VENV/bin/python
63
+ # rsm_real/requirements-deployment.txt pins numpy==2.2.6 but openpi caps numpy<2.0.0 -> install the
64
+ # deployment deps WITHOUT that pin (reported in the PR as a genuine incompatibility).
65
+ "$UV" pip install --python "$PY" hydra-core==1.3.2 omegaconf==2.3.0 PyYAML==6.0.2 h5py av pyarrow 2>&1 | tail -4
66
+ chk $? "deployment deps"
67
+ "$PY" -c "import numpy;print('numpy',numpy.__version__)"
68
+ "$UV" pip freeze --python "$PY" > "$SCRATCH/pip_freeze.txt"; wc -l "$SCRATCH/pip_freeze.txt"
69
+ grep -E "^(jax|jaxlib|jax-cuda|flax|orbax|numpy|torch|transformers|lerobot|hydra-core|omegaconf|opencv|openpi)" "$SCRATCH/pip_freeze.txt"
70
+
71
+ hdr "4 C1/C2/C3: provenance, split-free config construction, real checkpoint forward pass"
72
+ MISSING=$SCRATCH/no_such_dir/cooking_v5_split.json
73
+ "$PY" "$ROOT/scripts/real/patchexport_clean_checks.py" --repo "$REPO" --ckpt "$CKPT" \
74
+ --missing-split "$MISSING" --out "$SCRATCH/clean_checks.json"
75
+ chk $? "clean checks"
76
+
77
+ hdr "5 C4: real.deploy --print-config (openpi proposer, vanilla_bc, hardware-free)"
78
+ ( cd "$REPO" && "$PY" -m real.deploy --print-config proposer=openpi real.algorithm=vanilla_bc \
79
+ real.simulate=true real.dry_run=true real.device=cpu "real.proposer.checkpoint=$CKPT" 2>&1 | sed -n '1,60p' )
80
+ chk $? "real.deploy --print-config"
81
+
82
+ hdr "6 C5: real.deploy run, hardware-free (SyntheticEnvironment), 1 episode"
83
+ ( cd "$REPO" && timeout 3000 "$PY" -m real.deploy proposer=openpi real.algorithm=vanilla_bc \
84
+ real.simulate=true real.dry_run=true real.device=cpu "real.proposer.checkpoint=$CKPT" \
85
+ real.proposer.batch_size=0 real.evaluation.episodes=1 real.evaluation.max_episode_seconds=20 \
86
+ real.evaluation.auto_start=true 2>&1 | tail -60 )
87
+ chk $? "real.deploy simulate+dry_run"
88
+
89
+ hdr "done"
90
+ echo "OVERALL rc=$rc_all"
91
+ exit $rc_all
rsm_rise/scripts/real/patchexport_deploy_checks.sh ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # rsm_real#5 item 1, deployment-entrypoint half. Reuses the clean env built by
3
+ # patchexport_clean_inference_env.sh (default: run2b) -- no rebuild, no network.
4
+ # C5b real.deploy with proposer=openpi, vanilla_bc, simulate+dry_run, split file forced ABSENT
5
+ # C6 the same with dry_run=false, so recording + latency accounting actually run
6
+ set -uo pipefail
7
+ ROOT=/proj/dmfexp/zwhong/rsm_rise
8
+ SCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run2b}
9
+ CKPT=${CKPT:-$ROOT/hf_ckpt_root/pi05_bc_rsm_real_stock_s1_29999}
10
+ SECS=${SECS:-90}
11
+ PY=$SCRATCH/openpi/.venv/bin/python
12
+ REPO=$SCRATCH/rsm_real
13
+ unset RISE_ROOT RSM_LIBERO_DIR PYTHONPATH HF_TOKEN HF_HUB_OFFLINE
14
+ export PYTHONNOUSERSITE=1 PYTHONUNBUFFERED=1 TOKENIZERS_PARALLELISM=false
15
+ export OPENPI_DATA_HOME=$SCRATCH/openpi_assets HF_HOME=$SCRATCH/hf_home
16
+ export UV_CACHE_DIR=$SCRATCH/uv_cache JAX_PLATFORMS=${JAX_PLATFORMS:-cpu}
17
+ hdr(){ echo; echo "=================== $* ==================="; date -u; }
18
+ rc_all=0
19
+ chk(){ if [ "$1" -ne 0 ]; then echo "STEP FAILED rc=$1: $2"; rc_all=1; fi; }
20
+
21
+ hdr "0 context (reusing the prebuilt env; nothing is installed here)"
22
+ echo "host=$(hostname) job=${LSB_JOBID:-none} py=$PY repo=$REPO"
23
+ test -x "$PY" || { echo "no prebuilt env at $PY -- run patchexport_clean_inference_env.sh first"; exit 2; }
24
+ git -C "$REPO" pull --quiet 2>&1 | tail -2
25
+ echo "repo HEAD: $(git -C "$REPO" rev-parse --short HEAD) $(git -C "$REPO" log -1 --pretty=%s)"
26
+ "$PY" -c "import sys,openpi,jax;print('python',sys.executable);print('openpi',openpi.__file__);print('jax',jax.__version__,jax.devices())"
27
+
28
+ hdr "1 C5b real.deploy, openpi proposer, vanilla_bc, simulate+dry_run, SPLIT FILE ABSENT"
29
+ ( cd "$REPO" && timeout 1200 "$PY" "$ROOT/scripts/real/patchexport_deploy_nosplit.py" \
30
+ proposer=openpi real.algorithm=vanilla_bc real.simulate=true real.dry_run=true real.device=cpu \
31
+ "real.proposer.checkpoint=$CKPT" real.proposer.batch_size=0 real.evaluation.episodes=1 \
32
+ "real.evaluation.max_episode_seconds=$SECS" real.evaluation.auto_start=true 2>&1 | tail -40 )
33
+ chk $? "C5b deploy dry_run"
34
+
35
+ hdr "2 C6 the same with dry_run=false: recording, provenance and latency accounting"
36
+ ( cd "$REPO" && timeout 1800 "$PY" "$ROOT/scripts/real/patchexport_deploy_nosplit.py" \
37
+ proposer=openpi real.algorithm=vanilla_bc real.simulate=true real.dry_run=false real.device=cpu \
38
+ "real.proposer.checkpoint=$CKPT" real.proposer.batch_size=0 real.evaluation.episodes=1 \
39
+ "real.evaluation.max_episode_seconds=$SECS" real.evaluation.auto_start=true \
40
+ real.evaluation.run_name=pxclean_openpi_smoke 2>&1 | tail -50 )
41
+ chk $? "C6 deploy with recording"
42
+
43
+ hdr "3 what C6 wrote"
44
+ find "$REPO/outputs" -maxdepth 4 -newermt "-40 minutes" | head -30
45
+ for f in $(find "$REPO/outputs" -name "*.json" -newermt "-40 minutes" | head -4); do
46
+ echo "--- $f ---"; head -c 3000 "$f"; echo; done
47
+
48
+ hdr "done"
49
+ echo "OVERALL rc=$rc_all"
50
+ exit $rc_all
rsm_rise/scripts/real/patchexport_deploy_nosplit.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Run `python -m real.deploy` with the openpi cooking config's training split file forced ABSENT.
3
+
4
+ `real.deploy` builds the proposer through openpi's `create_trained_policy`, which builds the data
5
+ config; this wrapper points `split_json` at a path that does not exist before that happens, so the
6
+ deployment entry point is exercised exactly as it would be on a machine that has no training split.
7
+ Usage: patchexport_deploy_nosplit.py <hydra overrides...> (run with cwd = the repo root)
8
+ """
9
+ import dataclasses
10
+ import os
11
+ import sys
12
+ from pathlib import Path
13
+
14
+ # this script lives outside the repo, so sys.path[0] is its own directory; the repo root is the cwd
15
+ sys.path.insert(0, os.getcwd())
16
+
17
+ MISSING = "/nonexistent-deployment-machine/cooking_v5_split.json"
18
+
19
+
20
+ def main() -> int:
21
+ assert not Path(MISSING).exists(), MISSING
22
+ import openpi.training.config as C
23
+
24
+ original = C.get_config
25
+
26
+ def split_free(name):
27
+ cfg = original(name)
28
+ if hasattr(cfg.data, "split_json"):
29
+ cfg = dataclasses.replace(cfg, data=dataclasses.replace(cfg.data, split_json=MISSING))
30
+ return cfg
31
+
32
+ C.get_config = split_free
33
+ print(f"[nosplit] openpi.training.config.get_config patched: split_json -> {MISSING} "
34
+ f"(exists={Path(MISSING).exists()})", flush=True)
35
+ from real.deploy import main as deploy_main
36
+ deploy_main(sys.argv[1:])
37
+ return 0
38
+
39
+
40
+ if __name__ == "__main__":
41
+ raise SystemExit(main())
rsm_rise/scripts/real/patchexport_deployment_yml_union.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """rsm_real#5 run 26 -- the SEVENTH entry in the merge runbook: .github/workflows/deployment.yml.
3
+
4
+ It appeared the moment the owner pushed `dc2d40d`/`54c054e` to main (2026-09-24 19:03-19:11Z). Until
5
+ then the workflow was one-sided and merged silently. Now BOTH sides edit it:
6
+
7
+ main (owner) +'requirements/**', +'pyproject.toml' in both path filters;
8
+ +`pip install --no-deps -e .`; +test_deployment_actions.py, +test_deployment_startup.py
9
+ #11 (scaffold) +'tests/controls/**', +'tests/test_rise_stack_*.py', +'QUICKSTART.md', +'SETUP.md';
10
+ +5 rise_stack test files; +a whole `guard-negative-controls` job
11
+
12
+ The two sets are DISJOINT -- nobody changed a line the other also changed; they appended at the same
13
+ anchors, which is all git needs to refuse. So the resolution is a UNION, and unlike the other six
14
+ runbook entries it is NOT take-ours: dropping either side silently switches CI checks off. This
15
+ builds that union deterministically and refuses to emit one it cannot verify.
16
+
17
+ patchexport_deployment_yml_union.py <base.yml> <ours.yml> <theirs.yml> [-o out.yml]
18
+
19
+ `ours` is the five-way side (which carries main's edits); `theirs` is #11.
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import argparse
24
+ import re
25
+ import sys
26
+ from pathlib import Path
27
+
28
+ PATH_ITEM = re.compile(r"^(\s*)- '([^']+)'\s*$")
29
+ TEST_ITEM = re.compile(r"^(\s*)(tests/\S+\.py)\s*$")
30
+
31
+
32
+ def path_filter_items(text: str) -> list[str]:
33
+ return [m.group(2) for m in (PATH_ITEM.match(l) for l in text.splitlines()) if m]
34
+
35
+
36
+ def test_items(text: str) -> list[str]:
37
+ return [m.group(2) for m in (TEST_ITEM.match(l) for l in text.splitlines()) if m]
38
+
39
+
40
+ def jobs(text: str) -> list[str]:
41
+ out, in_jobs = [], False
42
+ for line in text.splitlines():
43
+ if line.rstrip() == "jobs:":
44
+ in_jobs = True
45
+ continue
46
+ if in_jobs:
47
+ m = re.match(r"^ ([A-Za-z0-9_-]+):\s*$", line)
48
+ if m:
49
+ out.append(m.group(1))
50
+ elif line and not line.startswith(" "):
51
+ in_jobs = False
52
+ return out
53
+
54
+
55
+ def build_union(base: str, ours: str, theirs: str) -> str:
56
+ """Start from THEIRS (it is the superset in structure -- it adds a whole job) and re-apply the
57
+ additions main made that theirs does not have. Each insertion is anchored on a line that must
58
+ occur an exact number of times, so a drifted input fails instead of producing a plausible file."""
59
+ # dedupe, ORDER-PRESERVING. main's workflow repeats each new path in BOTH of its path filters, so
60
+ # the raw difference lists every addition twice; the block is then inserted at each of the two
61
+ # anchors, which multiplied it to four. Caught in run 27 by diffing this builder's output against
62
+ # #11's own independent resolution (9fefc57): 93 lines vs 89, exactly the four duplicates.
63
+ def uniq(xs):
64
+ return list(dict.fromkeys(xs))
65
+ add_paths = uniq(p for p in path_filter_items(ours) if p not in path_filter_items(base))
66
+ add_tests = uniq(t for t in test_items(ours) if t not in test_items(base))
67
+ add_steps = [l for l in ours.splitlines()
68
+ if l.strip().startswith("python -m pip install") and l not in base.splitlines()]
69
+ out = theirs
70
+ # 1. path filters: main's new entries go just before the workflow's own path, in BOTH triggers.
71
+ anchor = " - '.github/workflows/deployment.yml'"
72
+ n = out.count(anchor)
73
+ if n != 2:
74
+ raise SystemExit(f"anchor {anchor!r} occurs {n} times, expected 2")
75
+ missing = [p for p in add_paths if p not in path_filter_items(theirs)]
76
+ if missing:
77
+ block = "".join(f" - '{p}'\n" for p in missing)
78
+ out = out.replace(anchor + "\n", block + anchor + "\n")
79
+ # 2. the editable install, before the torch line it must precede.
80
+ torch = [l for l in out.splitlines() if "download.pytorch.org" in l]
81
+ if len(torch) != 1:
82
+ raise SystemExit(f"expected exactly 1 torch install line, found {len(torch)}")
83
+ for step in add_steps:
84
+ if step not in out:
85
+ out = out.replace(torch[0] + "\n", step + "\n" + torch[0] + "\n")
86
+ # 3. main's new deployment tests, appended to the deployment pytest invocation. They must land
87
+ # in the SAME list as the other test_deployment_*.py entries, not in the rise_stack list.
88
+ anchor_t = [l for l in out.splitlines() if l.strip() == "tests/test_deployment_runtime.py"]
89
+ if len(anchor_t) != 1:
90
+ raise SystemExit("expected exactly 1 tests/test_deployment_runtime.py line")
91
+ add_t = [t for t in add_tests if t not in test_items(theirs)]
92
+ if add_t:
93
+ block = "".join(f"{anchor_t[0][:len(anchor_t[0]) - len(anchor_t[0].lstrip())]}{t}\n" for t in add_t)
94
+ out = out.replace(anchor_t[0] + "\n", anchor_t[0] + "\n" + block)
95
+ return out
96
+
97
+
98
+ def verify(base: str, ours: str, theirs: str, union: str) -> int:
99
+ bad = 0
100
+
101
+ def check(label, ok, detail=""):
102
+ nonlocal bad
103
+ print(f" {'OK ' if ok else 'FAIL'} {label}{(' -- ' + detail) if detail else ''}")
104
+ bad += 0 if ok else 1
105
+
106
+ up, tp, op = set(path_filter_items(union)), set(path_filter_items(theirs)), set(path_filter_items(ours))
107
+ check("path filters are a superset of #11's", tp <= up, f"missing {sorted(tp - up)}")
108
+ check("path filters are a superset of main's", op <= up, f"missing {sorted(op - up)}")
109
+ ut, tt, ot = set(test_items(union)), set(test_items(theirs)), set(test_items(ours))
110
+ check("every test file #11 runs still runs", tt <= ut, f"lost {sorted(tt - ut)}")
111
+ check("every test file main runs still runs", ot <= ut, f"lost {sorted(ot - ut)}")
112
+ check("no test file invented", ut <= (tt | ot), f"extra {sorted(ut - tt - ot)}")
113
+ uj, tj, oj = set(jobs(union)), set(jobs(theirs)), set(jobs(ours))
114
+ check("every job from both sides is present", (tj | oj) <= uj, f"missing {sorted((tj | oj) - uj)}")
115
+ check("no conflict markers", not re.search(r"^(<<<<<<<|=======|>>>>>>>)", union, re.M))
116
+ # Every check above is a SET comparison, which is exactly why the duplicate-entry defect this
117
+ # builder had survived a run that printed UNION OK. A repeated glob is harmless to GitHub and
118
+ # invisible to a subset test, so it needs its own check, per filter block and not globally (the
119
+ # same path legitimately appears in both the pull_request and the push filter).
120
+ dups = []
121
+ for block in re.split(r"^\s*(?:pull_request|push|workflow_dispatch):\s*$", union, flags=re.M)[1:]:
122
+ items = path_filter_items(block)
123
+ dups += [i for i in set(items) if items.count(i) > 1]
124
+ check("no path filter entry repeats within one filter", not dups, f"repeated {sorted(set(dups))}")
125
+ try:
126
+ import yaml # noqa
127
+ d = yaml.safe_load(union)
128
+ check("parses as YAML", isinstance(d, dict) and "jobs" in d)
129
+ check("every job has steps", all("steps" in v for v in d["jobs"].values()))
130
+ except ImportError:
131
+ print(" SKIP yaml not importable -- structural checks only")
132
+ # nothing may be LOST relative to either side: every non-blank line of each side survives
133
+ for label, side in (("main", ours), ("#11", theirs)):
134
+ lost = [l for l in side.splitlines() if l.strip() and l not in union.splitlines()]
135
+ check(f"no line of {label}'s workflow dropped", not lost, f"{len(lost)} line(s): {lost[:3]}")
136
+ return bad
137
+
138
+
139
+ def main() -> int:
140
+ ap = argparse.ArgumentParser()
141
+ ap.add_argument("base"); ap.add_argument("ours"); ap.add_argument("theirs")
142
+ ap.add_argument("-o", "--out")
143
+ # run 27: #11 resolved this conflict on its own branch (merge 9fefc57), so the question stopped
144
+ # being "what union would I build" and became "does THEIR file satisfy the same invariants".
145
+ # Same checks, a candidate supplied instead of constructed -- otherwise a resolution that quietly
146
+ # took one side is indistinguishable from a real union in any log.
147
+ ap.add_argument("--verify-only", metavar="CANDIDATE",
148
+ help="verify an existing resolved workflow instead of building the union")
149
+ a = ap.parse_args()
150
+ base, ours, theirs = (Path(p).read_text() for p in (a.base, a.ours, a.theirs))
151
+ if a.verify_only:
152
+ union = Path(a.verify_only).read_text()
153
+ print(f"candidate = {a.verify_only}, {len(union.splitlines())} lines "
154
+ f"(base {len(base.splitlines())}, main {len(ours.splitlines())}, #11 {len(theirs.splitlines())})")
155
+ bad = verify(base, ours, theirs, union)
156
+ print("CANDIDATE OK" if not bad else f"CANDIDATE REFUSED: {bad} check(s) failed")
157
+ return 0 if not bad else 3
158
+ union = build_union(base, ours, theirs)
159
+ print(f"union = {len(union.splitlines())} lines "
160
+ f"(base {len(base.splitlines())}, main {len(ours.splitlines())}, #11 {len(theirs.splitlines())})")
161
+ bad = verify(base, ours, theirs, union)
162
+ if a.out and not bad:
163
+ Path(a.out).write_text(union)
164
+ print(f"wrote {a.out}")
165
+ print("UNION OK" if not bad else f"UNION REFUSED: {bad} check(s) failed")
166
+ return 0 if not bad else 3
167
+
168
+
169
+ if __name__ == "__main__":
170
+ sys.exit(main())
rsm_rise/scripts/real/patchexport_dotted_selector.sh ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # rsm_real#5 -- run 27. ATTRIBUTE THE ONE FAILING TEST ON THE MERGED TREE.
3
+ #
4
+ # 1904471 (citest2, the first merged-tree pytest run on the owner's new main dc2d40d/54c054e) reported
5
+ # H0 #11 head 163 PASSED 2 SKIPPED 0 failed
6
+ # R0 resolved 1 FAILED 197 PASSED 4 SKIPPED
7
+ # and named the one that moved:
8
+ # tests/test_deployment_config.py::test_dotted_selector_loads_algorithm_components[rsm-rsm-128]
9
+ # PASSED -> FAILED
10
+ # That is a RED merged CI, and the outcome table does not say why: the detail script records verdicts,
11
+ # not tracebacks. Two questions, and neither may be answered by reading a diff:
12
+ # (a) WHAT is the assertion? -> run the single node with --tb=long and print it verbatim.
13
+ # (b) WHOSE change causes it? -> run that same node on main alone, on #11's live head alone, and on
14
+ # main + each of #6..#11 INDIVIDUALLY, then on the full resolved six-way. A test that fails on
15
+ # main alone is the owner's and I must tell him; one that fails only in combination is ours.
16
+ # Both suspects are measured, not assumed: #8 rewrites real/deployment/models.py's rsm branch, and the
17
+ # published resolution runs `git rm -rf rise_stack/rsm` -- deleting the vendored scorer that main's
18
+ # own tests may still name by dotted path. If the single-PR sweep is clean and only the resolved tree
19
+ # fails, the resolution itself is the cause, so the tree is re-tested with the deletion put back.
20
+ # Read-only w.r.t. every real repo: fetches from GitHub, works only inside SCRATCH, pushes nothing.
21
+ set -uo pipefail
22
+ source /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_resolve.sh
23
+ SCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run89}
24
+ VENV=${VENV:-/proj/dmfexp/zwhong/scratch_patchexport/run29/venv_ci}
25
+ NODE='tests/test_deployment_config.py::test_dotted_selector_loads_algorithm_components'
26
+ PRS="6 7 8 9 10"
27
+ SC_PR=11
28
+ export GIT_TERMINAL_PROMPT=0 PYTHONDONTWRITEBYTECODE=1 OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1
29
+ scrub(){ sed 's#https://[^@]*@#https://<redacted>@#g'; }
30
+ hdr(){ echo; echo "=================== $* ==================="; date -u; }
31
+ rc_all=0
32
+ PY=$VENV/bin/python
33
+ [ -x "$PY" ] || { echo "no venv at $VENV"; exit 2; }
34
+ mkdir -p "${SCRATCH:?}" || exit 1
35
+ M=$SCRATCH/mt
36
+
37
+ hdr "0 context"
38
+ echo "host=$(hostname) job=${LSB_JOBID:-none} scratch=$SCRATCH venv=$VENV"
39
+ echo "node=$NODE"
40
+
41
+ hdr "1 clone + fetch every side"
42
+ TOK=$(grep -m1 'https://richardrl:' ~/.git-credentials | sed -E 's|https://richardrl:([^@]*)@.*|\1|')
43
+ [ -n "$TOK" ] || { echo "NO TOKEN"; exit 1; }
44
+ rm -rf "${M:?}"; git init --quiet "$M" || exit 1
45
+ printf '[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"
46
+ unset TOK
47
+ git -C "$M" fetch --quiet origin main 2>&1 | scrub
48
+ git -C "$M" checkout --quiet -b main FETCH_HEAD 2>&1 | scrub
49
+ git -C "$M" config user.email noreply@anthropic.com; git -C "$M" config user.name "dotted-selector attribution"
50
+ for n in $PRS $SC_PR; do git -C "$M" fetch --quiet origin "pull/$n/head:pr-$n" 2>&1 | scrub; done
51
+ MAIN=$(git -C "$M" rev-parse main)
52
+ echo " main = $(echo "$MAIN" | cut -c1-7) $(git -C "$M" log -1 --format=%s main)"
53
+ for n in $PRS $SC_PR; do
54
+ L=$(git -C "$M" ls-remote origin "refs/pull/$n/head" 2>/dev/null | awk '{print $1}')
55
+ H=$(git -C "$M" rev-parse "pr-$n")
56
+ S=same; [ "$L" = "$H" ] || S="STALE(live=$(echo "$L"|cut -c1-7))"
57
+ echo " #$n = $(echo "$H" | cut -c1-7) $S"
58
+ done
59
+
60
+ # run1 <label> <treeish-or-CURRENT> -- run the node, print verdict and, when it fails, the traceback.
61
+ run1(){
62
+ local label=$1 out rc
63
+ # cwd on sys.path is how the repo's own CI imports `real` (see patchexport_merged_tests_detail.sh:168):
64
+ # PYTHONPATH is emptied on purpose so nothing leaks in from this login environment.
65
+ out=$(cd "$M" && PYTHONPATH= "$PY" -m pytest "$NODE" -p no:cacheprovider --tb=long -q -rf 2>&1)
66
+ rc=$?
67
+ local line
68
+ line=$(printf '%s\n' "$out" | grep -E '^[0-9]+ (passed|failed)|passed|failed' | tail -1)
69
+ printf ' %-34s rc=%s %s\n' "$label" "$rc" "$line"
70
+ if [ "$rc" -ne 0 ]; then
71
+ printf '%s\n' "$out" | sed -n '/=\+ FAILURES/,/short test summary/p' | sed 's/^/ | /'
72
+ fi
73
+ return $rc
74
+ }
75
+
76
+ hdr "2 the node on MAIN alone -- is this failure already on the owner's main?"
77
+ git -C "$M" checkout --quiet main
78
+ run1 "main $(echo "$MAIN"|cut -c1-7)"
79
+ MAIN_RC=$?
80
+
81
+ hdr "3 the node on #11's LIVE head alone (it merged main in as 9fefc57 this evening)"
82
+ git -C "$M" checkout --quiet "pr-$SC_PR"
83
+ run1 "#11 head"
84
+
85
+ hdr "4 the node on main + EACH PR individually"
86
+ for n in $PRS $SC_PR; do
87
+ git -C "$M" checkout --quiet -B probe main >/dev/null 2>&1
88
+ if ! git -C "$M" merge --no-ff -m "probe #$n" "pr-$n" >/dev/null 2>&1; then
89
+ echo " main+#$n CONFLICTS -- resolving with the runbook helper"
90
+ FIVE=$(git -C "$M" rev-parse main)
91
+ pe_resolve "$M" "$FIVE" scripts/setup_env.sh SETUP.md rise_stack/openpi/README.md scripts/check_env.py rise_stack/scorers.py
92
+ pe_resolve_check "$M" || { echo " main+#$n UNRESOLVED -- skipped"; continue; }
93
+ git -C "$M" commit --quiet -m "probe #$n resolved" || true
94
+ fi
95
+ run1 "main+#$n"
96
+ done
97
+
98
+ hdr "5 the full resolved six-way, exactly as the runbook builds it"
99
+ git -C "$M" checkout --quiet -B sixway main >/dev/null 2>&1
100
+ 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; }; done
101
+ FIVE=$(git -C "$M" rev-parse HEAD)
102
+ git -C "$M" merge --no-ff -m "Merge PR #$SC_PR" "pr-$SC_PR" >/dev/null 2>&1
103
+ pe_resolve "$M" "$FIVE" scripts/setup_env.sh SETUP.md rise_stack/openpi/README.md scripts/check_env.py rise_stack/scorers.py
104
+ pe_resolve_check "$M" || { echo " RESOLUTION INCOMPLETE -- stopping"; exit 2; }
105
+ HAD_RSM=no
106
+ if [ -d "$M/rise_stack/rsm" ]; then HAD_RSM=yes; git -C "$M" rm -rf -f --quiet rise_stack/rsm || exit 2; fi
107
+ git -C "$M" commit --quiet -m "scratch: six-way + published resolution" || true
108
+ echo " resolved = $(git -C "$M" rev-parse --short HEAD) vendored rise_stack/rsm was present and deleted: $HAD_RSM"
109
+ run1 "resolved six-way"
110
+ SIX_RC=$?
111
+
112
+ hdr "6 if only the resolved tree fails: is the CAUSE the rise_stack/rsm deletion?"
113
+ if [ "$SIX_RC" -ne 0 ] && [ "$HAD_RSM" = yes ]; then
114
+ git -C "$M" checkout --quiet HEAD~0 >/dev/null 2>&1
115
+ git -C "$M" checkout --quiet "$FIVE" -- rise_stack/rsm 2>/dev/null \
116
+ || git -C "$M" checkout --quiet "pr-$SC_PR" -- rise_stack/rsm 2>/dev/null
117
+ if [ -d "$M/rise_stack/rsm" ]; then
118
+ echo " put rise_stack/rsm back ($(ls "$M/rise_stack/rsm" | tr '\n' ' '))"
119
+ run1 "resolved + rsm/ restored"
120
+ [ $? -eq 0 ] && echo " => the DELETION of the vendored scorer is the cause" \
121
+ || echo " => the deletion is NOT the cause; look at the traceback above"
122
+ else
123
+ echo " could not restore rise_stack/rsm -- inconclusive"
124
+ fi
125
+ # And the other suspect, independent of the deletion: #8's models.py rsm branch.
126
+ git -C "$M" checkout --quiet -B m8probe "$FIVE" >/dev/null 2>&1
127
+ git -C "$M" checkout --quiet main -- real/deployment/models.py
128
+ echo " reverted real/deployment/models.py to main's copy on the five-way"
129
+ run1 "five-way + main's models.py"
130
+ else
131
+ echo " not applicable (six-way rc=$SIX_RC, vendored dir present=$HAD_RSM)"
132
+ fi
133
+
134
+ hdr "7 cleanup"
135
+ rm -rf "${M:?}"
136
+ echo "removed $M"
137
+
138
+ hdr "OVERALL rc=$rc_all (main alone rc=$MAIN_RC, resolved rc=$SIX_RC)"
139
+ exit $rc_all
rsm_rise/scripts/real/patchexport_dp_pin.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """rsm_real#5 -- move the LAST hardcoded upstream pins out of our two scripts and into pin files.
3
+
4
+ Two pins were still written as literals after run 23 replaced the two DINOv2 shas in
5
+ ``setup_env.sh`` with ``dino_pin()``:
6
+
7
+ * ``diffusion_policy`` -- the short sha ``078ce1e``, three times in two files
8
+ (``scripts/setup_env.sh`` twice, once per --env branch, and ``scripts/check_env.py`` once),
9
+ with **no** ``rise_stack/diffusion_policy/UPSTREAM_COMMIT.txt`` at all. Nothing compared the
10
+ three, and ``check_tree`` compares ``HEAD.startswith(pin[:12])`` -- so a 7-character pin
11
+ silently degraded the check it exists to perform to a 7-character compare.
12
+ * ``dinov2`` -- the full 40-hex sha, in ``scripts/check_env.py``, while the same commit is
13
+ recorded as ``dino_commit`` in ``rise_stack/rsm_libero/UPSTREAM_COMMIT.txt`` and read from
14
+ there by ``setup_env.sh``. A *checker* carrying its own copy of the value it checks fails in
15
+ the direction that wastes the most time: edit the pin, clone the new commit correctly, and the
16
+ checker reports the correct tree as wrong. #11's
17
+ ``tests/test_rise_stack_openpi_patch_numbers.py`` guards ``setup_env.sh`` against hardcoded
18
+ shas and does not look at ``check_env.py``, so this copy was unguarded.
19
+
20
+ Every edit is anchored on text that must appear EXACTLY the expected number of times; anything else
21
+ exits 3 rather than guessing, and the caller does not push. Run against a clean checkout of
22
+ ``patchexport/env-setup``; ``--check`` verifies an already-transformed tree instead of writing.
23
+
24
+ usage: patchexport_dp_pin.py <worktree> <dp_full_sha> [--check]
25
+ """
26
+ from __future__ import annotations
27
+
28
+ import pathlib
29
+ import re
30
+ import sys
31
+
32
+ DP_SHORT = "078ce1e"
33
+ DINO_FULL = "7764ea0f912e53c92e82eb78a2a1631e92725fc8"
34
+
35
+ CLONE_OLD = ("clone_at diffusion_policy https://github.com/UWRobotLearning/diffusion_policy.git "
36
+ + DP_SHORT)
37
+ CLONE_NEW = ('clone_at diffusion_policy https://github.com/UWRobotLearning/diffusion_policy.git '
38
+ '"$(pin_of diffusion_policy)"')
39
+ COMMENT_OLD = " # diffusion_policy: upstream is UNCHANGED by us, so it is a pin with no patch.\n"
40
+ COMMENT_NEW = (
41
+ " # diffusion_policy: upstream is UNCHANGED by us, so it is a pin with no patch -- and the pin\n"
42
+ " # therefore lives in rise_stack/diffusion_policy/UPSTREAM_COMMIT.txt, not in this script.\n")
43
+
44
+ TREES_OLD = (f'dp_tree = check_tree("diffusion_policy", "diffusion_policy", "{DP_SHORT}")\n'
45
+ f'dino_tree = check_tree("dinov2", "dinov2", "{DINO_FULL}")\n')
46
+ TREES_NEW = ('dp_tree = check_tree("diffusion_policy", "diffusion_policy", pin_of("diffusion_policy"))\n'
47
+ 'dino_tree = check_tree("dinov2", "dinov2", dino_pin())\n')
48
+
49
+ PIN_OF_TAIL = ''' if re.fullmatch(r"[0-9a-fA-F]{7,40}", line):
50
+ return line
51
+ return ""
52
+ '''
53
+
54
+ DINO_FN = PIN_OF_TAIL + '''
55
+
56
+ def dino_pin() -> str:
57
+ """The DINOv2 backbone commit, read from the ONE place it is recorded.
58
+
59
+ It is `dino_commit` in rise_stack/rsm_libero/UPSTREAM_COMMIT.txt, because DINOv2 is the
60
+ featuriser that library's checkpoints were built against. This function exists because the
61
+ sha was ALSO written out in full here, so a checker whose whole job is to catch drift carried
62
+ its own copy of the thing that drifts: change the pin and this file would have reported the
63
+ correctly-cloned tree as wrong. scripts/setup_env.sh reads the same key the same way.
64
+ """
65
+ f = REPO / "rise_stack" / "rsm_libero" / "UPSTREAM_COMMIT.txt"
66
+ if not f.is_file():
67
+ return ""
68
+ m = re.search(r"^dino_commit\\s*=\\s*([0-9a-fA-F]{7,40})\\b", f.read_text(), re.M)
69
+ return m.group(1) if m else ""
70
+ '''
71
+
72
+ PINS_DP_OLD = ("| `code/diffusion_policy` | `UWRobotLearning/diffusion_policy` | `078ce1e` | **none** "
73
+ "| pin only; needed for `LowdimMaskGenerator`. Cannot be pip-installed -- see the "
74
+ "robomimic README |")
75
+ PINS_DP_NEW = ("| `code/diffusion_policy` | `UWRobotLearning/diffusion_policy` | `078ce1e` "
76
+ "([full sha](diffusion_policy/UPSTREAM_COMMIT.txt)) | **none** | pin only; needed for "
77
+ "`LowdimMaskGenerator`. Cannot be pip-installed -- see the robomimic README. The pin is "
78
+ "recorded in [`rise_stack/diffusion_policy/UPSTREAM_COMMIT.txt`]"
79
+ "(diffusion_policy/UPSTREAM_COMMIT.txt) and read from there by `scripts/setup_env.sh` "
80
+ "and `scripts/check_env.py`; neither hardcodes it |")
81
+ PINS_DINO_OLD = "Weights: the published `dinov2_vits14_pretrain.pth`, sha256 `b938bf1b…` |"
82
+ PINS_DINO_NEW = ("Weights: the published `dinov2_vits14_pretrain.pth`, sha256 `b938bf1b…`. The commit is "
83
+ "recorded ONCE, as `dino_commit` in [`rise_stack/rsm_libero/UPSTREAM_COMMIT.txt`]"
84
+ "(rsm_libero/UPSTREAM_COMMIT.txt) (DINOv2 is the featuriser those checkpoints were built "
85
+ "against); `setup_env.sh` and `check_env.py` both read it from there |")
86
+
87
+ PIN_FILE = """# diffusion_policy -- pin only, no patch. Our checkout has ZERO diff against upstream (measured
88
+ # 2026-09-23: 0 modified, 0 untracked source files), so there is no .patch beside this file: the
89
+ # pin IS the whole story, which is exactly why the pin has to be recorded somewhere a reader can
90
+ # find and a script can parse.
91
+ #
92
+ # It is recorded HERE, once, because the sha used to be written down three times in two files --
93
+ # scripts/setup_env.sh twice (--env a and --env b) and scripts/check_env.py once -- and nothing
94
+ # compared any two of them. That is the duplication class that already cost this repo a pin:
95
+ # see `dino_commit` in rise_stack/rsm_libero/UPSTREAM_COMMIT.txt.
96
+ #
97
+ # Only the short form `{short}` was ever written down before. check_env.py's tree check compares
98
+ # HEAD against `pin[:12]`, so a 7-character pin silently degraded that to a 7-character compare.
99
+ repo = https://github.com/UWRobotLearning/diffusion_policy.git
100
+ commit = {full}
101
+ date = 2025-01-27T12:42:52Z
102
+ patch = none -- upstream is used unmodified
103
+ needed_for = diffusion_policy.model.diffusion.mask_generator.LowdimMaskGenerator, imported by the
104
+ robomimic fork's diffusion-policy algos (environment B). Cannot be pip-installed:
105
+ its setup.py installs no package and fails silently -- see scripts/setup_env.sh.
106
+ """
107
+
108
+
109
+ def refuse(msg: str) -> None:
110
+ print(f"REFUSING: {msg}")
111
+ raise SystemExit(3)
112
+
113
+
114
+ def main() -> int:
115
+ if len(sys.argv) < 3:
116
+ print(__doc__)
117
+ return 2
118
+ w = pathlib.Path(sys.argv[1])
119
+ full = sys.argv[2].strip().lower()
120
+ check_only = "--check" in sys.argv[3:]
121
+ if not re.fullmatch(r"[0-9a-f]{40}", full):
122
+ refuse(f"{full!r} is not a 40-character sha")
123
+ if not full.startswith(DP_SHORT):
124
+ refuse(f"{full[:12]} does not start with the pin {DP_SHORT} every document quotes")
125
+
126
+ se = w / "scripts" / "setup_env.sh"
127
+ ce = w / "scripts" / "check_env.py"
128
+ pins = w / "rise_stack" / "UPSTREAM_PINS.md"
129
+ pinf = w / "rise_stack" / "diffusion_policy" / "UPSTREAM_COMMIT.txt"
130
+ for f in (se, ce, pins):
131
+ if not f.is_file():
132
+ refuse(f"{f} is missing -- wrong branch?")
133
+
134
+ if check_only:
135
+ s, c, p = se.read_text(), ce.read_text(), pins.read_text()
136
+ bare = re.compile(r"(?<![0-9a-f])[0-9a-f]{40}(?![0-9a-f])")
137
+ problems = []
138
+ if DP_SHORT in s or DP_SHORT in c:
139
+ problems.append("a literal 078ce1e survives in a script")
140
+ if DINO_FULL in c:
141
+ problems.append("the dinov2 literal survives in check_env.py")
142
+ for f, body in ((se, s), (ce, c)):
143
+ if bare.findall(body):
144
+ problems.append(f"{f.name} carries a bare 40-hex sha {bare.findall(body)}")
145
+ if 'pin_of diffusion_policy' not in s:
146
+ problems.append("setup_env.sh does not call pin_of diffusion_policy")
147
+ if s.count(CLONE_NEW) != 2:
148
+ problems.append(f"setup_env.sh has {s.count(CLONE_NEW)} pin_of clone sites, expected 2")
149
+ if "def dino_pin(" not in c:
150
+ problems.append("check_env.py has no dino_pin()")
151
+ if not pinf.is_file():
152
+ problems.append("the pin file was not written")
153
+ elif not re.search(rf"^commit\s*=\s*{full}$", pinf.read_text(), re.M):
154
+ problems.append("the pin file does not record the full sha as `commit = ...`")
155
+ if PINS_DP_NEW not in p or PINS_DINO_NEW not in p:
156
+ problems.append("UPSTREAM_PINS.md does not name where the pins live")
157
+ for x in problems:
158
+ print(f" !! {x}")
159
+ print("CHECK " + ("FAILED" if problems else "OK"))
160
+ return 4 if problems else 0
161
+
162
+ s = se.read_text()
163
+ if s.count(CLONE_OLD) != 2:
164
+ refuse(f"expected 2 inline diffusion_policy pins in setup_env.sh, found {s.count(CLONE_OLD)}")
165
+ if s.count(COMMENT_OLD) != 1:
166
+ refuse("the 'pin with no patch' comment is not present exactly once")
167
+ s = s.replace(CLONE_OLD, CLONE_NEW).replace(COMMENT_OLD, COMMENT_NEW)
168
+ if DP_SHORT in s:
169
+ refuse("a literal 078ce1e survives in setup_env.sh after the rewrite")
170
+
171
+ c = ce.read_text()
172
+ if c.count(TREES_OLD) != 1:
173
+ refuse("the diffusion_policy/dinov2 check_tree pair is not present verbatim exactly once")
174
+ if c.count(PIN_OF_TAIL) != 1:
175
+ refuse("pin_of()'s tail is not present exactly once -- cannot place dino_pin() safely")
176
+ c = c.replace(TREES_OLD, TREES_NEW).replace(PIN_OF_TAIL, DINO_FN)
177
+ if DINO_FULL in c or DP_SHORT in c:
178
+ refuse("a literal sha survives in check_env.py after the rewrite")
179
+
180
+ p = pins.read_text()
181
+ if p.count(PINS_DP_OLD) != 1 or p.count(PINS_DINO_OLD) != 1:
182
+ refuse("UPSTREAM_PINS.md rows are not present verbatim exactly once each")
183
+ p = p.replace(PINS_DP_OLD, PINS_DP_NEW).replace(PINS_DINO_OLD, PINS_DINO_NEW)
184
+
185
+ se.write_text(s)
186
+ ce.write_text(c)
187
+ pins.write_text(p)
188
+ pinf.parent.mkdir(parents=True, exist_ok=True)
189
+ pinf.write_text(PIN_FILE.format(short=DP_SHORT, full=full))
190
+ print(f" setup_env.sh : 2 inline pins -> $(pin_of diffusion_policy), comment updated")
191
+ print(f" check_env.py : dp -> pin_of(), dinov2 -> dino_pin() (new, reads dino_commit)")
192
+ print(f" pin file : {pinf.relative_to(w)} commit = {full}")
193
+ print(f" UPSTREAM_PINS.md: both rows now name where the pin lives")
194
+ return 0
195
+
196
+
197
+ if __name__ == "__main__":
198
+ raise SystemExit(main())
rsm_rise/scripts/real/patchexport_dp_pin_push.sh ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # SUPERSEDED 2026-09-24 (run 28): this gate trial-merges a SUBSET, not main + #6..#10 + #11.
3
+ # That hole is a measured failure of this stream -- LSF 1902702 caught a conflict AFTER a push whose
4
+ # gate merged only `main -> #6 -> #10`. Do not reuse this script for a new push. Copy
5
+ # scripts/real/patchexport_readme_dedupe_push.sh instead: it does the full merge with pe_resolve, runs
6
+ # #11's control ledger on the merged tree, and diffs pytest against a baseline MEASURED on main alone
7
+ # rather than against a hardcoded expectation.
8
+ # rsm_real#5 run 24 -- the last two hardcoded upstream pins leave our scripts, gated and pushed.
9
+ #
10
+ # What it changes (via scripts/real/patchexport_dp_pin.py, which refuses to guess):
11
+ # * new rise_stack/diffusion_policy/UPSTREAM_COMMIT.txt with the FULL sha; setup_env.sh's two
12
+ # inline `078ce1e` literals become $(pin_of diffusion_policy) and check_env.py's one becomes
13
+ # pin_of("diffusion_policy").
14
+ # * check_env.py's full-length dinov2 sha becomes dino_pin(), reading the `dino_commit` already
15
+ # recorded in rise_stack/rsm_libero/UPSTREAM_COMMIT.txt -- the same key setup_env.sh reads
16
+ # since run 23. #11's tests/test_rise_stack_openpi_patch_numbers.py guards setup_env.sh
17
+ # against hardcoded shas and never looks at check_env.py, so this copy was unguarded.
18
+ #
19
+ # Only PR #10 (patchexport/env-setup) carries these files. Measured, not assumed: #6's tree has no
20
+ # scripts/ directory at all (GitHub trees API on 49d68ec), so this is a one-branch change and the
21
+ # "identical blob on both branches" guard the openpi-README push needed does not apply here.
22
+ #
23
+ # The gate refuses to push unless, in order: the branch is in sync with origin, the transform
24
+ # reproduces from a CLEAN tree, --check passes, the pinned commit EXISTS upstream and `078ce1e` is
25
+ # its prefix, `bash -n` + `py_compile` pass, all four --print-pin answers are right with the three
26
+ # pre-existing ones BYTE-IDENTICAL to the pushed head, check_env.py actually prints both resolved
27
+ # pins when executed, no bare 40-hex survives in either script, and the five-way merge is clean.
28
+ set -uo pipefail
29
+ S=${S:-/proj/dmfexp/zwhong/scratch_patchexport/run69}
30
+ WT=${WT:-/proj/dmfexp/zwhong/scratch_patchexport/wt_setup} # #10, patchexport/env-setup
31
+ BR=${BR:-patchexport/env-setup}
32
+ WT_MAIN=${WT_MAIN:-/proj/dmfexp/zwhong/scratch_patchexport/wt_main} # #6, merge trial only
33
+ DP_FULL=${DP_FULL:-078ce1ee2064cde28074db239ff0af2f9254069b}
34
+ DINO_FULL=7764ea0f912e53c92e82eb78a2a1631e92725fc8
35
+ DO_PUSH=${DO_PUSH:-0}
36
+ D=/proj/dmfexp/zwhong/rsm_rise/scripts/real
37
+ export GIT_TERMINAL_PROMPT=0
38
+ scrub(){ sed 's#https://[^@]*@#https://<redacted>@#g'; }
39
+ hdr(){ echo; echo "=================== $* ==================="; date -u; }
40
+ mkdir -p "$S"; rc=0
41
+ FILES="scripts/setup_env.sh scripts/check_env.py rise_stack/UPSTREAM_PINS.md"
42
+
43
+ hdr "0 context and the in-sync guard"
44
+ echo "host=$(hostname) job=${LSB_JOBID:-none} do_push=$DO_PUSH wt=$WT"
45
+ echo " on $(git -C "$WT" rev-parse --abbrev-ref HEAD) @ $(git -C "$WT" rev-parse --short HEAD)"
46
+ [ "$(git -C "$WT" rev-parse --abbrev-ref HEAD)" = "$BR" ] || { echo " wrong branch -- REFUSING"; exit 2; }
47
+ git -C "$WT" fetch --quiet origin "$BR" 2>&1 | scrub || exit 2
48
+ L=$(git -C "$WT" rev-parse HEAD); R=$(git -C "$WT" rev-parse FETCH_HEAD)
49
+ [ "$L" = "$R" ] || { echo " local ${L:0:7} != origin ${R:0:7} -- REFUSING"; exit 2; }
50
+ # The tree may carry this run's own edits; anything ELSE is someone else's work and stops the job.
51
+ 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/)$')
52
+ [ -z "$DIRT" ] || { echo " unexpected dirty paths -- REFUSING:"; echo "$DIRT"; exit 2; }
53
+
54
+ hdr "1 baseline --print-pin on the PUSHED head, before anything is rewritten"
55
+ git -C "$WT" checkout --quiet -- $FILES 2>/dev/null
56
+ rm -rf "$WT/rise_stack/diffusion_policy"
57
+ [ -z "$(git -C "$WT" status --porcelain)" ] || { echo " tree not clean after reset -- REFUSING"; exit 2; }
58
+ for d in openpi robomimic rsm_libero; do
59
+ printf '%s %s\n' "$d" "$(cd "$WT" && PRINT_PIN=$d bash scripts/setup_env.sh 2>&1 | tail -1)"
60
+ done | tee "$S/pins_before.txt"
61
+
62
+ hdr "2 the transform, from the clean tree"
63
+ python3 "$D/patchexport_dp_pin.py" "$WT" "$DP_FULL" || { echo " transform refused"; exit 3; }
64
+ python3 "$D/patchexport_dp_pin.py" "$WT" "$DP_FULL" --check || { echo " --check failed"; exit 4; }
65
+
66
+ hdr "3 the pinned commit EXISTS upstream, and 078ce1e is its prefix"
67
+ TOK=$(grep -m1 'https://richardrl:' ~/.git-credentials | sed -E 's|https://richardrl:([^@]*)@.*|\1|')
68
+ [ -n "$TOK" ] || { echo "NO TOKEN"; exit 2; }
69
+ curl -s -H "Authorization: token $TOK" \
70
+ "https://api.github.com/repos/UWRobotLearning/diffusion_policy/commits/$DP_FULL" > "$S/dp_commit.json"
71
+ unset TOK
72
+ python3 - "$S/dp_commit.json" "$DP_FULL" <<'PY' || rc=5
73
+ import json, sys
74
+ d = json.load(open(sys.argv[1])); want = sys.argv[2]
75
+ if d.get("sha") != want:
76
+ print(f" !! upstream does not have {want[:12]}: {d.get('message', d.get('sha'))}"); raise SystemExit(1)
77
+ print(f" upstream HAS {want} ({d['commit']['committer']['date']}, {d['commit']['message'].splitlines()[0][:60]!r})")
78
+ print(f" short form quoted by every document: {want[:7]} -> prefix: {want.startswith(want[:7])}")
79
+ PY
80
+ [ $rc -eq 0 ] || { echo " refusing to pin a commit I cannot see"; exit $rc; }
81
+
82
+ hdr "4 syntax, and the parsers EXERCISED rather than read"
83
+ ( cd "$WT" && bash -n scripts/setup_env.sh ) && echo " bash -n scripts/setup_env.sh OK" || rc=6
84
+ ( cd "$WT" && python3 -m py_compile scripts/check_env.py ) && echo " py_compile scripts/check_env.py OK" || rc=6
85
+ for d in openpi robomimic rsm_libero diffusion_policy; do
86
+ printf '%s %s\n' "$d" "$(cd "$WT" && PRINT_PIN=$d bash scripts/setup_env.sh 2>&1 | tail -1)"
87
+ done | tee "$S/pins_after.txt"
88
+ echo " the three pre-existing pins must be byte-identical to the pushed head:"
89
+ if diff <(cat "$S/pins_before.txt") <(grep -vE '^diffusion_policy ' "$S/pins_after.txt"); then
90
+ echo " unchanged"
91
+ else
92
+ echo " A PRE-EXISTING PIN MOVED -- REFUSING"; rc=6
93
+ fi
94
+ grep -q "^diffusion_policy $DP_FULL$" "$S/pins_after.txt" || { echo " pin_of diffusion_policy is wrong"; rc=6; }
95
+ [ $rc -eq 0 ] || exit $rc
96
+
97
+ hdr "4b both readers, every pin dir -- this branch's own tests/test_rise_stack_pins.py grows a case"
98
+ # That test is parametrized over rise_stack/*/UPSTREAM_COMMIT.txt and asserts BOTH readers return the
99
+ # same FULL sha, so adding a pin file adds a case: it has to pass before the push, not after.
100
+ ( cd "$WT" && for d in $(ls -d rise_stack/*/UPSTREAM_COMMIT.txt | sed 's|rise_stack/||;s|/UPSTREAM_COMMIT.txt||'); do
101
+ sh=$(PRINT_PIN=$d bash scripts/setup_env.sh 2>&1 | tail -1)
102
+ py=$(python3 scripts/check_env.py --print-pin "$d" 2>&1 | tail -1)
103
+ st=AGREE; [ "$sh" = "$py" ] || st=MISMATCH
104
+ case "$sh" in *[!0-9a-f]*|"") st="NOT-A-SHA/$st";; esac
105
+ [ ${#sh} -eq 40 ] || st="SHORT/$st"
106
+ printf ' %-18s shell=%s python=%s %s\n' "$d" "$sh" "$py" "$st"
107
+ [ "$st" = AGREE ] || exit 1
108
+ done ) || { echo " a pin disagrees between the two readers -- REFUSING"; exit 6; }
109
+ CIVENV=${CIVENV:-/proj/dmfexp/zwhong/scratch_patchexport/run29/venv_ci}
110
+ if [ -x "$CIVENV/bin/pytest" ]; then
111
+ ( cd "$WT" && "$CIVENV/bin/pytest" -q tests/test_rise_stack_pins.py 2>&1 | tail -5 )
112
+ [ ${PIPESTATUS[0]:-0} -eq 0 ] || true # the tail hides the code; the summary line is the evidence
113
+ ( cd "$WT" && "$CIVENV/bin/pytest" -q tests/test_rise_stack_pins.py >/dev/null 2>&1 ) \
114
+ || { echo " tests/test_rise_stack_pins.py FAILED -- REFUSING"; exit 6; }
115
+ echo " tests/test_rise_stack_pins.py passed"
116
+ else
117
+ echo " !! no pytest at $CIVENV -- the pins test was NOT run (say so, do not imply it passed)"
118
+ fi
119
+
120
+ hdr "4c dino_pin() itself -- --print-pin never reaches it"
121
+ python3 "$D/patchexport_dp_pin_readers.py" "$WT" || { echo " a reader is wrong -- REFUSING"; exit 6; }
122
+
123
+ hdr "5 check_env.py, EXECUTED, actually COMPARES against both resolved pins"
124
+ # Run 24's job (LSF 1902328) exited 7 here with both shas NEVER PRINTED, and the gate was right to
125
+ # refuse but wrong about the reason: check_tree() returns at `if not cloned` (scripts/check_env.py:113)
126
+ # and never reaches the pin comparison, so on a machine with no third_party/ clones the checker
127
+ # reports "MISSING: clone" and compares nothing. A plain run therefore cannot prove the readers
128
+ # resolve. patchexport_check_env_pin_probe.sh points $RISE_DEPS at two throwaway git repos with a
129
+ # deliberately wrong HEAD, which forces the comparison branch and makes the real module-level call
130
+ # print `this repo pins <sha>` -- and then hides the pin files and requires that same assertion to
131
+ # go RED, because a check that cannot fail is not a check.
132
+ ( cd "$WT" && timeout 600 python3 scripts/check_env.py > "$S/check_env.log" 2>&1 )
133
+ echo " plain run (no clones here): exit=$? ($(wc -l < "$S/check_env.log") lines) -- reports MISSING, compares nothing:"
134
+ grep -nE 'diffusion_policy|dinov2' "$S/check_env.log" | head -5 | sed 's/^/ /'
135
+ bash "$D/patchexport_check_env_pin_probe.sh" "$WT" "$DP_FULL" "$DINO_FULL" "$S" || rc=7
136
+ [ $rc -eq 0 ] || exit $rc
137
+
138
+ hdr "6 no bare 40-hex sha survives in either script (#11's guard, run here first)"
139
+ python3 - "$WT" <<'PY' || rc=8
140
+ import pathlib, re, sys
141
+ w = pathlib.Path(sys.argv[1])
142
+ bare = re.compile(r"(?<![0-9a-f])[0-9a-f]{40}(?![0-9a-f])")
143
+ bad = 0
144
+ for rel in ("scripts/setup_env.sh", "scripts/check_env.py"):
145
+ hits = bare.findall((w / rel).read_text())
146
+ print(f" {rel}: bare40={hits}")
147
+ bad += len(hits)
148
+ raise SystemExit(1 if bad else 0)
149
+ PY
150
+ [ $rc -eq 0 ] || { echo " a hardcoded sha remains"; exit $rc; }
151
+
152
+ hdr "7 commit"
153
+ MSG=$(cat <<'EOM'
154
+ The last two hardcoded pins leave the scripts: diffusion_policy gets a pin file, dinov2 is read once
155
+
156
+ rsm_real#5. Run 23 replaced setup_env.sh's two DINOv2 shas with dino_pin(). Two literals were
157
+ left, and both are the same defect one level further in:
158
+
159
+ * `diffusion_policy` was pinned as the SHORT sha `078ce1e`, written three times in two files --
160
+ scripts/setup_env.sh twice (once per --env branch) and scripts/check_env.py once -- with no
161
+ rise_stack/diffusion_policy/UPSTREAM_COMMIT.txt at all. Nothing compared the three copies.
162
+ check_env.py's tree check is `HEAD.startswith(pin[:12])`, so a 7-character pin silently
163
+ degraded the check to a 7-character compare. The pin file now records the full sha
164
+ 078ce1ee2064cde28074db239ff0af2f9254069b (verified present upstream, and `078ce1e` is its
165
+ prefix, so every document that quotes the short form stays correct), and both call sites read
166
+ it with pin_of.
167
+ * `dinov2` was pinned by its FULL sha in check_env.py while the same commit is recorded as
168
+ `dino_commit` in rise_stack/rsm_libero/UPSTREAM_COMMIT.txt and read from there by
169
+ setup_env.sh. A checker carrying its own copy of the value it checks fails in the most
170
+ expensive direction: edit the pin, clone the new commit correctly, and the checker reports the
171
+ correct tree as wrong. #11's tests/test_rise_stack_openpi_patch_numbers.py guards
172
+ setup_env.sh against hardcoded shas and does not look at check_env.py, so this copy was
173
+ unguarded by the test that exists precisely to catch it.
174
+
175
+ Only this branch carries the two scripts: #6's tree has no scripts/ directory (GitHub trees API on
176
+ 49d68ec), so this is a one-branch change.
177
+
178
+ The edit is scripts/real/patchexport_dp_pin.py, which anchors on text that must appear an exact
179
+ number of times and exits 3 otherwise, and re-runs with --check afterwards. Gated before the push
180
+ (scripts/real/patchexport_dp_pin_push.sh): the pinned commit fetched from the upstream API; bash -n
181
+ and py_compile; `--print-pin` for all four dependencies with the three pre-existing answers
182
+ byte-identical to the pushed head; scripts/check_env.py EXECUTED against two throwaway git repos
183
+ injected through $RISE_DEPS, so check_tree() reaches its comparison branch and has to print the pin
184
+ it compares against -- with the pin files then hidden and that same assertion required to go red,
185
+ because check_tree returns at `if not cloned` and a plain run on a machine without the clones
186
+ compares nothing at all (that is how LSF 1902328 exited 7); no bare 40-hex sha left in either
187
+ script; and a clean five-way merge.
188
+
189
+ Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
190
+ EOM
191
+ )
192
+ git -C "$WT" add $FILES rise_stack/diffusion_policy/UPSTREAM_COMMIT.txt
193
+ git -C "$WT" commit -q -m "$MSG" || { echo " commit failed"; exit 2; }
194
+ echo " $BR -> $(git -C "$WT" rev-parse --short HEAD)"
195
+ git -C "$WT" show --stat --oneline HEAD | head -8
196
+
197
+ hdr "8 trial five-way merge (main -> #6 -> this)"
198
+ T=$(mktemp -d /proj/dmfexp/zwhong/scratch_patchexport/dppin.XXXXXX)
199
+ git clone --quiet --shared --no-checkout "$WT" "$T/r" 2>/dev/null
200
+ git -C "$T/r" fetch --quiet "$WT" HEAD:local-setup
201
+ git -C "$T/r" fetch --quiet "$WT_MAIN" HEAD:local-main
202
+ git -C "$T/r" fetch --quiet "$WT" refs/remotes/origin/main:local-mainline
203
+ git -C "$T/r" checkout --quiet -b trial local-mainline
204
+ git -C "$T/r" config user.email noreply@anthropic.com; git -C "$T/r" config user.name "dp pin trial"
205
+ 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
206
+ echo " #6 then #10: MERGED CLEAN"
207
+ else
208
+ echo " TRIAL MERGE CONFLICTED"; git -C "$T/r" diff --name-only --diff-filter=U; rc=9
209
+ fi
210
+ rm -rf "$T"
211
+ [ $rc -eq 0 ] || { echo " not pushing"; exit $rc; }
212
+
213
+ hdr "9 push"
214
+ if [ "$DO_PUSH" = "1" ]; then
215
+ git -C "$WT" push origin "HEAD:$BR" 2>&1 | scrub || rc=2
216
+ else
217
+ echo " DO_PUSH=0 -- committed locally only"
218
+ fi
219
+ hdr "OVERALL rc=$rc"
220
+ exit $rc
rsm_rise/scripts/real/patchexport_dp_pin_readers.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Exercise check_env.py's two pin readers WITHOUT running the whole checker.
3
+
4
+ `scripts/setup_env.sh --print-pin` covers `pin_of` on the shell side and `check_env.py --print-pin`
5
+ covers it on the python side, but NEITHER touches `dino_pin()`: that function is called once, at
6
+ module level, in `check_tree("dinov2", "dinov2", dino_pin())`, so the only way to reach it is to run
7
+ the whole checker -- which imports openpi and torch and therefore belongs in a job. This lifts the
8
+ two function definitions out of the real source with `ast` (not a copy of them) and calls them, so a
9
+ reader that silently returns "" cannot reach a push just because the cluster is busy. The full
10
+ `python3 scripts/check_env.py` run is still owed; this is a floor, not a substitute.
11
+
12
+ usage: patchexport_dp_pin_readers.py <worktree>
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import ast
17
+ import pathlib
18
+ import re
19
+ import sys
20
+
21
+ EXPECT = {
22
+ ("dino_pin",): "7764ea0f912e53c92e82eb78a2a1631e92725fc8",
23
+ ("pin_of", "diffusion_policy"): "078ce1ee2064cde28074db239ff0af2f9254069b",
24
+ ("pin_of", "rsm_libero"): "f612011bb400ac204918be1d6f923e539cd59fd7",
25
+ ("pin_of", "openpi"): "215abfb217dbac7d5f1273282331b9b1866c0479",
26
+ ("pin_of", "robomimic"): "40e427a695a9f085d3fc0f70ffb0d687a10802c8",
27
+ }
28
+
29
+
30
+ def main() -> int:
31
+ if len(sys.argv) < 2:
32
+ print(__doc__)
33
+ return 2
34
+ w = pathlib.Path(sys.argv[1])
35
+ src = (w / "scripts" / "check_env.py").read_text()
36
+ ns: dict = {"re": re, "REPO": w, "Path": pathlib.Path}
37
+ found = []
38
+ for node in ast.parse(src).body:
39
+ if isinstance(node, ast.FunctionDef) and node.name in {"pin_of", "dino_pin"}:
40
+ exec(compile(ast.Module(body=[node], type_ignores=[]), "check_env.py", "exec"), ns)
41
+ found.append(node.name)
42
+ print(f" lifted from the real source: {found}")
43
+ if set(found) != {"pin_of", "dino_pin"}:
44
+ print(" !! a reader is missing from check_env.py")
45
+ return 3
46
+ bad = 0
47
+ for call, want in EXPECT.items():
48
+ got = ns[call[0]](*call[1:])
49
+ ok = got == want
50
+ bad += not ok
51
+ print(f" {'ok' if ok else '!!'} {call[0]}({', '.join(map(repr, call[1:]))}) -> {got or '(empty)'}"
52
+ + ("" if ok else f" expected {want}"))
53
+ print("READERS " + ("OK" if not bad else "WRONG"))
54
+ return 4 if bad else 0
55
+
56
+
57
+ if __name__ == "__main__":
58
+ raise SystemExit(main())
rsm_rise/scripts/real/patchexport_envc_probe.sh ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Cover commit 9d18628 (the `--env c` rsm_libero probe imported `model` directly, which CANNOT work:
3
+ # our packaging patch installs the PACKAGE rsm_libero, whose __init__ puts its own directory on
4
+ # sys.path so the library's internal unqualified imports resolve). The probe printed
5
+ # "rsm_libero missing (No module named 'model') -- bc_idql works here, rsm does not"
6
+ # in an interpreter where check_env.py reported RSM reranking PASS. Only the printed line was wrong,
7
+ # but it is the line a labmate reads to decide whether they can rerank. Everything in --env c is
8
+ # stamped and idempotent, so this re-run is cheap; it asserts the corrected line and that check_env
9
+ # still agrees with it.
10
+ set -uo pipefail
11
+ ROOT=/proj/dmfexp/zwhong/rsm_rise
12
+ SCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run9}
13
+ REPO=$SCRATCH/rsm_real
14
+ SRC=${SRC:-/proj/dmfexp/zwhong/scratch_patchexport/wt_setup}
15
+ export CKPTS=${CKPTS:-$ROOT/hf_ckpt_root}
16
+ unset RISE_ROOT RSM_LIBERO_DIR PYTHONPATH HF_TOKEN HF_HUB_OFFLINE HF_LEROBOT_HOME
17
+ export PYTHONNOUSERSITE=1 PYTHONUNBUFFERED=1 TOKENIZERS_PARALLELISM=false JAX_PLATFORMS=cpu
18
+ export UV_CACHE_DIR=$SCRATCH/uv_cache HF_HOME=$SCRATCH/hf_home TORCH_HOME=$SCRATCH/torch_home
19
+ export MPLCONFIGDIR=$SCRATCH/mpl OPENPI_DATA_HOME=$SCRATCH/openpi_assets GIT_TERMINAL_PROMPT=0
20
+ hdr(){ echo; echo "=================== $* ==================="; date -u; }
21
+ rc_all=0
22
+ chk(){ if [ "$1" -ne 0 ]; then echo "STEP FAILED rc=$1: $2"; rc_all=1; fi; }
23
+
24
+ hdr "0 context"
25
+ echo "host=$(hostname) job=${LSB_JOBID:-none} repo=$REPO"
26
+ WANT=$(git -C "$SRC" rev-parse HEAD)
27
+ # checkout -f, never reset --hard + clean: third_party/ and .venvs/ are UNTRACKED here and hold the
28
+ # already-built environments this job exists to reuse.
29
+ git -C "$REPO" fetch --quiet origin && git -C "$REPO" checkout -f --quiet "$WANT"
30
+ chk $? "checkout $WANT"
31
+ echo "rsm_real now at: $(git -C "$REPO" rev-parse --short HEAD) $(git -C "$REPO" log -1 --pretty=%s)"
32
+ [ -d "$REPO/third_party/openpi/.venv" ] || { echo "environment A was destroyed by the checkout"; exit 1; }
33
+ PY_A=$REPO/third_party/openpi/.venv/bin/python
34
+
35
+ hdr "1 setup_env.sh --env c, and the line the probe prints"
36
+ OUT=$SCRATCH/envc_probe.txt
37
+ ( cd "$REPO" && bash scripts/setup_env.sh --env c 2>&1 ) | tee "$OUT"
38
+ chk ${PIPESTATUS[0]} "setup_env.sh --env c"
39
+ echo "--- the rsm_libero line ---"
40
+ grep -n "rsm_libero" "$OUT"
41
+ if grep -q "rsm_libero missing" "$OUT"; then
42
+ echo "REGRESSION: the probe still reports rsm_libero missing"; rc_all=1
43
+ fi
44
+ grep -qE "rsm_libero (imports|from) " "$OUT" || { echo "the corrected line is absent"; rc_all=1; }
45
+
46
+ hdr "2 check_env.py must agree with it"
47
+ ( cd "$REPO" && "$PY_A" scripts/check_env.py > "$SCRATCH/envc_checkenv.txt" 2>&1 )
48
+ chk $? "check_env C"
49
+ grep -E "rsm_libero|RSM reranking|IQL reranking|real.algorithm=rsm" "$SCRATCH/envc_checkenv.txt"
50
+ echo "PASS rows: $(grep -c '^ PASS' "$SCRATCH/envc_checkenv.txt") MISSING rows: $(grep -c '^ MISSING' "$SCRATCH/envc_checkenv.txt")"
51
+ [ "$(grep -c '^ MISSING' "$SCRATCH/envc_checkenv.txt")" -eq 0 ] || { echo "environment C has MISSING rows"; rc_all=1; }
52
+
53
+ hdr "done"
54
+ echo "OVERALL rc=$rc_all"
55
+ exit $rc_all
rsm_rise/scripts/real/patchexport_genq_sparse.sh ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Validate the sparse/blobless gen_q clone that scripts/setup_env.sh now uses, against the full clone
3
+ # it used before. The full clone measured 2.5 GB and ~20 min on this filesystem (LSF 1888352) to
4
+ # deliver the 2,862 lines of rsm_libero/ that are actually used.
5
+ set -uo pipefail
6
+ SCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run11}
7
+ REPO=${REPO:-/proj/dmfexp/zwhong/scratch_patchexport/wt_setup}
8
+ URL=https://github.com/williamd4112/gen_q.git
9
+ PIN=f612011bb400ac204918be1d6f923e539cd59fd7
10
+ PATCHF=$REPO/rise_stack/rsm_libero/rise_on_rsm_libero.patch
11
+ hdr(){ echo; echo "=================== $* ==================="; date -u; }
12
+ rc_all=0
13
+ chk(){ if [ "$1" -ne 0 ]; then echo "STEP FAILED rc=$1: $2"; rc_all=1; fi; }
14
+ rm -rf "${SCRATCH:?}"; mkdir -p "${SCRATCH:?}" || exit 1
15
+
16
+ hdr "0 context"
17
+ echo "host=$(hostname) job=${LSB_JOBID:-none} git=$(git --version)"
18
+ echo "patch: $PATCHF"; md5sum "$PATCHF"
19
+
20
+ hdr "1 the exact sequence clone_at now runs for gen_q"
21
+ t0=$(date +%s)
22
+ git clone --quiet --filter=blob:none --no-checkout "$URL" "$SCRATCH/gen_q"; chk $? "clone"
23
+ git -C "$SCRATCH/gen_q" sparse-checkout init --cone; chk $? "sparse init"
24
+ git -C "$SCRATCH/gen_q" sparse-checkout set rsm_libero; chk $? "sparse set"
25
+ git -C "$SCRATCH/gen_q" fetch --quiet --all 2>/dev/null
26
+ git -C "$SCRATCH/gen_q" checkout --quiet "$PIN"; chk $? "checkout pin"
27
+ t1=$(date +%s)
28
+ echo "HEAD: $(git -C "$SCRATCH/gen_q" rev-parse HEAD)"
29
+ echo "HEAD == pin: $([ "$(git -C "$SCRATCH/gen_q" rev-parse HEAD)" = "$PIN" ] && echo YES || echo NO)"
30
+ echo "ELAPSED clone+checkout: $((t1-t0)) s"
31
+ echo "ON DISK: $(du -sh "$SCRATCH/gen_q" | cut -f1) (.git: $(du -sh "$SCRATCH/gen_q/.git" | cut -f1))"
32
+
33
+ hdr "2 the sparse cone contains what the patch and the scorer need"
34
+ echo "--- top level of the working tree ---"
35
+ ls -1 "$SCRATCH/gen_q" | head -20
36
+ echo "--- rsm_libero/ present? ---"
37
+ ls -1 "$SCRATCH/gen_q/rsm_libero"/*.py 2>/dev/null | head -20
38
+ echo "count: $(ls -1 "$SCRATCH/gen_q/rsm_libero"/*.py 2>/dev/null | wc -l)"
39
+ for f in model.py train_rsm.py is_ope.py data.py; do
40
+ [ -f "$SCRATCH/gen_q/rsm_libero/$f" ] && echo " OK $f ($(wc -l < "$SCRATCH/gen_q/rsm_libero/$f") lines)" \
41
+ || { echo " MISSING $f"; rc_all=1; }
42
+ done
43
+ echo "total lines of the four modules: $(cat "$SCRATCH/gen_q/rsm_libero"/{model,train_rsm,is_ope,data}.py | wc -l)"
44
+
45
+ hdr "3 our packaging patch applies inside the sparse checkout"
46
+ ( cd "$SCRATCH/gen_q" && git apply --check "$PATCHF" && echo "git apply --check OK" && git apply "$PATCHF" && echo "git apply OK" )
47
+ chk $? "apply packaging patch"
48
+ echo "--- the two files it creates ---"
49
+ for f in rsm_libero/__init__.py pyproject.toml; do
50
+ [ -f "$SCRATCH/gen_q/$f" ] && echo " OK $f ($(wc -l < "$SCRATCH/gen_q/$f") lines)" || { echo " MISSING $f"; rc_all=1; }
51
+ done
52
+ echo "--- pyproject.toml ---"; cat "$SCRATCH/gen_q/pyproject.toml"
53
+
54
+ hdr "4 the sparse clone is byte-identical to the tree the validated RSM run used"
55
+ # run7/gen_q is the clone LSF 1887661 used when it loaded the real successor checkpoint and produced
56
+ # finite scores -- and it is ITSELF a sparse checkout at the same pin. So the reference for "does the
57
+ # sparse clone deliver the right bytes" already exists and is one the real checkpoints ran against.
58
+ REF=/proj/dmfexp/zwhong/scratch_patchexport/run7/gen_q
59
+ if [ -d "$REF/rsm_libero" ]; then
60
+ echo "reference: $REF HEAD=$(git -C "$REF" rev-parse HEAD) sparse=[$(git -C "$REF" sparse-checkout list 2>/dev/null | tr '\n' ' ')]"
61
+ diff -r -q "$REF/rsm_libero" "$SCRATCH/gen_q/rsm_libero" \
62
+ --exclude=__pycache__ --exclude=__init__.py && echo "rsm_libero/ identical to the validated tree"
63
+ chk $? "sparse clone == the tree the RSM validation ran against"
64
+ else
65
+ echo "reference clone absent -- skipping (record this as NOT CHECKED, do not claim it)"
66
+ fi
67
+
68
+ hdr "5 pip install -e it, then import rsm_libero and the four top-level modules for real"
69
+ "${PY:-/u/zwhong/.local/bin/python3.11}" -m venv "$SCRATCH/venv" 2>/dev/null || python3 -m venv "$SCRATCH/venv"
70
+ chk $? "venv"
71
+ "$SCRATCH/venv/bin/pip" install --quiet --upgrade pip setuptools wheel >/dev/null 2>&1
72
+ # torch is needed because rsm_libero/model.py imports it at module scope; CPU wheel is enough here.
73
+ "$SCRATCH/venv/bin/pip" install --quiet "numpy==1.26.4" "torch==2.5.1" \
74
+ --index-url https://download.pytorch.org/whl/cpu --extra-index-url https://pypi.org/simple
75
+ chk $? "numpy + torch (cpu)"
76
+ "$SCRATCH/venv/bin/pip" install --quiet -e "$SCRATCH/gen_q"; chk $? "pip install -e gen_q"
77
+ env -u PYTHONPATH -u RSM_LIBERO_DIR -u RISE_ROOT "$SCRATCH/venv/bin/python" - <<'PYEOF'
78
+ import sys
79
+ sys.path = [p for p in sys.path if "rsm_rise" not in p and "gen_q/rsm_libero" not in p]
80
+ import rsm_libero
81
+ print("rsm_libero ->", rsm_libero.__file__)
82
+ import model, train_rsm, is_ope, data
83
+ for name, m in (("model", model), ("train_rsm", train_rsm), ("is_ope", is_ope), ("data", data)):
84
+ print(f"{name:15s} ->", m.__file__)
85
+ f = m.__file__ or ""
86
+ assert "/proj/dmfexp/zwhong/rsm_rise" not in f, f"{name} came from the research tree"
87
+ assert "issue_resolver" not in f, f"{name} came from the research tree"
88
+ assert "/run11/gen_q/" in f, f"{name} did not come from the sparse clone: {f}"
89
+ import torch
90
+ print("torch", torch.__version__)
91
+ print("VERDICT: the sparse clone supplies rsm_libero and all four top-level modules,"
92
+ " and nothing resolved into the research tree")
93
+ PYEOF
94
+ chk $? "import from the sparse clone"
95
+
96
+ hdr "done"
97
+ echo "OVERALL rc=$rc_all"
98
+ exit $rc_all
rsm_rise/scripts/real/patchexport_guard_controls_merged.sh ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # rsm_real#5 run 25 -- do #11's NEW negative controls still FIRE once the runbook's take-ours
3
+ # resolutions are applied?
4
+ #
5
+ # #11's 9fb9abf added tests/controls/run_guard_controls.sh (300 lines): each control mutates a
6
+ # staged copy of an input and requires the guard to go RED and name the drift. It is the right
7
+ # idea and it is the same idea this stream just had to apply to its own push gate (LSF 1902328
8
+ # asserted check_env.py prints a pin, and the assertion was unsatisfiable because check_tree()
9
+ # returns at `if not cloned`).
10
+ #
11
+ # But the controls key on EXACT strings (`grep -c -F`) in files the merge resolves to OUR side:
12
+ # ours (take-ours, per patchexport_merged_tests_detail.sh):
13
+ # scripts/setup_env.sh SETUP.md rise_stack/openpi/README.md scripts/check_env.py
14
+ # theirs (one-sided #11):
15
+ # QUICKSTART.md rise_stack/configs/baselines.yaml rise_stack/CHECKPOINTS.md
16
+ # A control whose target string lives only in THEIR copy of an ours-resolved file reports
17
+ # `rc=99 NON-RESULT` -- their harness is honest about that, it does not count it as a pass -- and
18
+ # the guard it was meant to police is then unpoliced on the tree a human would actually merge.
19
+ #
20
+ # So run their own harness, unmodified, twice: on #11's head (H) and on the resolved tree (R).
21
+ # Any label that is 0 on H and 99 on R is a control the MERGE silently disables. Read-only: fetches
22
+ # from GitHub, works only in SCRATCH, pushes nothing.
23
+ set -uo pipefail
24
+ source /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_resolve.sh
25
+ SCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run76}
26
+ VENV=${VENV:-/proj/dmfexp/zwhong/scratch_patchexport/run29/venv_ci}
27
+ PRS=${PRS:-"6 7 8 9 10"}
28
+ SC_PR=${SC_PR:-11}
29
+ CTL=tests/controls/run_guard_controls.sh
30
+ export GIT_TERMINAL_PROMPT=0 PYTHONDONTWRITEBYTECODE=1 OMP_NUM_THREADS=1
31
+ scrub(){ sed 's#https://[^@]*@#https://<redacted>@#g'; }
32
+ hdr(){ echo; echo "=================== $* ==================="; date -u; }
33
+ rc_all=0
34
+ mkdir -p "${SCRATCH:?}" || exit 1
35
+ M=$SCRATCH/mt
36
+ PY=$VENV/bin/python
37
+ [ -x "$PY" ] || { echo "no venv at $VENV"; exit 2; }
38
+
39
+ hdr "0 context"
40
+ echo "host=$(hostname) job=${LSB_JOBID:-none} scratch=$SCRATCH"
41
+
42
+ hdr "1 build main + five-way merge + the published take-ours resolution"
43
+ TOK=$(grep -m1 'https://richardrl:' ~/.git-credentials | sed -E 's|https://richardrl:([^@]*)@.*|\1|')
44
+ [ -n "$TOK" ] || { echo "NO TOKEN"; exit 1; }
45
+ rm -rf "${M:?}"; git init --quiet "$M" || exit 1
46
+ printf '[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"
47
+ unset TOK
48
+ git -C "$M" fetch --quiet origin main 2>&1 | scrub
49
+ git -C "$M" checkout --quiet -b main FETCH_HEAD 2>&1 | scrub
50
+ git -C "$M" config user.email noreply@anthropic.com; git -C "$M" config user.name "guard-controls merged"
51
+ for n in $PRS $SC_PR; do git -C "$M" fetch --quiet origin "pull/$n/head:pr-$n" 2>&1 | scrub; done
52
+ SC_SHA=$(git -C "$M" rev-parse "pr-$SC_PR")
53
+ LIVE=$(git -C "$M" ls-remote origin "refs/pull/$SC_PR/head" 2>/dev/null | awk '{print $1}')
54
+ [ "$LIVE" = "$SC_SHA" ] || { echo "STALE: $SC_SHA != $LIVE -- #11 moved again"; exit 2; }
55
+ echo " #$SC_PR head = $(echo "$SC_SHA" | cut -c1-7) (live)"
56
+ 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; }; done
57
+ FIVE=$(git -C "$M" rev-parse HEAD)
58
+ git -C "$M" merge --no-ff -m "Merge PR #$SC_PR" "pr-$SC_PR" >/dev/null 2>&1
59
+ echo " conflicted: $(git -C "$M" diff --name-only --diff-filter=U | tr '\n' ' ')"
60
+ pe_resolve "$M" "$FIVE" scripts/setup_env.sh SETUP.md rise_stack/openpi/README.md scripts/check_env.py rise_stack/scorers.py
61
+ [ -z "$(git -C "$M" diff --name-only --diff-filter=U)" ] || { echo " RESOLUTION INCOMPLETE:"; git -C "$M" diff --name-only --diff-filter=U; exit 2; }
62
+ git -C "$M" rm -rf -f --quiet rise_stack/rsm 2>/dev/null
63
+ git -C "$M" commit --quiet -m "scratch: five-way + #$SC_PR + take-ours resolution" || true
64
+ RES=$(git -C "$M" rev-parse HEAD)
65
+ echo " resolved = $(echo "$RES" | cut -c1-7)"
66
+
67
+ hdr "2 the harness exists on the head, and is IDENTICAL on the resolved tree"
68
+ git -C "$M" cat-file -e "$SC_SHA:$CTL" 2>/dev/null || { echo " $CTL not on #$SC_PR head"; exit 2; }
69
+ HB=$(git -C "$M" rev-parse "$SC_SHA:$CTL"); RB=$(git -C "$M" rev-parse "$RES:$CTL" 2>/dev/null || echo ABSENT)
70
+ echo " blob on head=$(echo "$HB" | cut -c1-10) on resolved=$(echo "$RB" | cut -c1-10) $([ "$HB" = "$RB" ] && echo IDENTICAL || echo DIFFERENT)"
71
+ [ "$HB" = "$RB" ] || rc_all=2
72
+
73
+ hdr "3 which of the harness's inputs does the merge take from OUR side?"
74
+ for f in SETUP.md QUICKSTART.md scripts/setup_env.sh rise_stack/openpi/README.md \
75
+ rise_stack/openpi/rise_on_pi05.patch rise_stack/openpi/UPSTREAM_COMMIT.txt \
76
+ rise_stack/configs/baselines.yaml rise_stack/CHECKPOINTS.md rise_stack/README.md \
77
+ tests/test_deployment_models.py; do
78
+ h=$(git -C "$M" rev-parse "$SC_SHA:$f" 2>/dev/null || echo ABSENT)
79
+ r=$(git -C "$M" rev-parse "$RES:$f" 2>/dev/null || echo ABSENT)
80
+ printf ' %-45s head=%s resolved=%s %s\n' "$f" "$(echo "$h"|cut -c1-10)" "$(echo "$r"|cut -c1-10)" \
81
+ "$([ "$h" = "$r" ] && echo same || echo "DIFFERENT -> resolved side wins")"
82
+ done
83
+
84
+ hdr "4 run THEIR harness, unmodified, on #$SC_PR's head (H)"
85
+ WH=$SCRATCH/t_head; WR=$SCRATCH/t_res
86
+ rm -rf "$WH" "$WR"
87
+ git -C "$M" worktree add --quiet --detach "$WH" "$SC_SHA" || exit 2
88
+ git -C "$M" worktree add --quiet --detach "$WR" "$RES" || exit 2
89
+ ( cd "$WH" && PY="$PY" REPO="$WH" timeout 1800 bash "$CTL" 2>&1 ) | tee "$SCRATCH/H.log" | tail -45
90
+ echo " H exit=${PIPESTATUS[0]}"
91
+
92
+ hdr "5 run THEIR harness, unmodified, on the RESOLVED tree (R)"
93
+ ( cd "$WR" && PY="$PY" REPO="$WR" timeout 1800 bash "$CTL" 2>&1 ) | tee "$SCRATCH/R.log" | tail -45
94
+ echo " R exit=${PIPESTATUS[0]}"
95
+
96
+ hdr "6 label by label -- which controls the MERGE disables"
97
+ python3 - "$SCRATCH/H.log" "$SCRATCH/R.log" <<'PY'
98
+ import re, sys, pathlib
99
+ def rcs(p):
100
+ out = {}
101
+ for line in pathlib.Path(p).read_text().splitlines():
102
+ m = re.match(r'^(\S+) rc=(\d+)', line.strip())
103
+ if m and not m.group(1).startswith('==='):
104
+ out[m.group(1)] = (int(m.group(2)), line.strip())
105
+ return out
106
+ H, R = rcs(sys.argv[1]), rcs(sys.argv[2])
107
+ labels = sorted(set(H) | set(R))
108
+ print(f" {'label':32s} {'head':>6s} {'resolved':>9s} verdict")
109
+ bad = []
110
+ for L in labels:
111
+ h = H.get(L, (None,))[0]; r = R.get(L, (None,))[0]
112
+ if h == r: v = "same"
113
+ elif r == 99: v = "*** the MERGE turns this control into a NON-RESULT ***"; bad.append(L)
114
+ elif h == 99: v = "fires only after the merge"
115
+ else: v = "*** CHANGED ***"; bad.append(L)
116
+ print(f" {L:32s} {str(h):>6s} {str(r):>9s} {v}")
117
+ print()
118
+ for L in bad:
119
+ if L in R: print(f" {L}: {R[L][1]}")
120
+ print(f"\n {len(bad)} control(s) differ between the head and the tree a human would merge")
121
+ raise SystemExit(1 if bad else 0)
122
+ PY
123
+ [ $? -eq 0 ] || rc_all=1
124
+
125
+ hdr "7 cleanup"
126
+ git -C "$M" worktree remove --force "$WH" 2>/dev/null; git -C "$M" worktree remove --force "$WR" 2>/dev/null
127
+ hdr "OVERALL rc=$rc_all (1 = a control behaves differently on the merged tree)"
128
+ exit $rc_all
rsm_rise/scripts/real/patchexport_import_winner.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Which RSMScorer actually loads? Execute the shipped fallback block, don't read it.
3
+
4
+ rsm_real#5/#4: PR #8 removes the vendored `rise_stack/rsm/rsm_scorer.py` and supplies
5
+ `robomimic.algo.rsm_scorer` from the robomimic patch; the scaffold branch keeps the vendored copy and
6
+ `rise_stack/scorers.py` tries it FIRST. After a six-way merge both exist, so the question "which one
7
+ runs" has one answer and it is decided by the code text, not by intent. This extracts the real
8
+ try/except out of a given commit's `rise_stack/scorers.py` and runs it verbatim with BOTH candidates
9
+ importable as stubs, and prints the winner.
10
+
11
+ usage: patchexport_import_winner.py <repo> <rev> <label>
12
+ """
13
+ import os
14
+ import re
15
+ import subprocess
16
+ import sys
17
+ import tempfile
18
+ import textwrap
19
+
20
+ repo, rev, label = sys.argv[1], sys.argv[2], sys.argv[3]
21
+ # rev may be "" -> `git show :path`, i.e. stage 0 of the index (the in-progress merge result)
22
+ src = subprocess.run(["git", "-C", repo, "show", f"{rev}:rise_stack/scorers.py"],
23
+ capture_output=True, text=True)
24
+ if src.returncode != 0:
25
+ print(f" {label}: no rise_stack/scorers.py at {rev}")
26
+ sys.exit(0)
27
+ lines = src.stdout.splitlines()
28
+ hits = [i for i, l in enumerate(lines) if re.search(r"rsm_scorer import RSMScorer", l)]
29
+ if not hits:
30
+ print(f" {label}: no rsm_scorer import found -- nothing to resolve")
31
+ sys.exit(0)
32
+ start = None
33
+ for j in range(hits[0], max(-1, hits[0] - 6), -1):
34
+ if lines[j].strip() == "try:":
35
+ start = j
36
+ break
37
+ if start is None:
38
+ # Single source, no fallback. Still EXECUTE it with both stubs importable: a probe that reports
39
+ # "nothing to resolve" and exits is a check that has degraded to nothing, which is the failure mode
40
+ # this whole gate exists to catch. The import line is indented inside a method, so dedent it.
41
+ start = end = hits[0]
42
+ single = True
43
+ else:
44
+ end = max(h for h in hits if h < start + 14)
45
+ single = False
46
+ block = textwrap.dedent("\n".join(lines[start:end + 1]))
47
+ order = ["vendored rise_stack.rsm.rsm_scorer" if ".rsm.rsm_scorer" in lines[h]
48
+ else "fork robomimic.algo.rsm_scorer" for h in hits if start <= h <= end]
49
+ kind = "single source, no fallback" if single else "fallback chain"
50
+ print(f" {label} ({rev[:8] or 'merge index'}): {kind} = {' THEN '.join(order)}")
51
+
52
+ d = tempfile.mkdtemp(prefix="imp_")
53
+ os.makedirs(f"{d}/rise_stack/rsm", exist_ok=True)
54
+ os.makedirs(f"{d}/robomimic/algo", exist_ok=True)
55
+ stub = "SOURCE=%r\nclass RSMScorer: pass\ndef chain_continuation_p(*a, **k): pass\ndef chain_cap_fn(*a, **k): pass\n"
56
+ for f, body in [("rise_stack/__init__.py", ""), ("rise_stack/rsm/__init__.py", ""),
57
+ ("robomimic/__init__.py", ""), ("robomimic/algo/__init__.py", ""),
58
+ ("rise_stack/rsm/rsm_scorer.py", stub % "VENDORED rise_stack/rsm/rsm_scorer.py"),
59
+ ("robomimic/algo/rsm_scorer.py", stub % "FORK robomimic/algo/rsm_scorer.py (our patch)")]:
60
+ with open(os.path.join(d, f), "w") as fh:
61
+ fh.write(body)
62
+ with open(f"{d}/block.py", "w") as fh:
63
+ fh.write(block)
64
+ runner = (
65
+ f"import sys, types\n"
66
+ f"sys.path.insert(0, {d!r})\n"
67
+ f"m = types.ModuleType('rise_stack.scorers'); m.__package__='rise_stack'\n"
68
+ f"sys.modules['rise_stack.scorers'] = m\n"
69
+ f"exec(compile(open({os.path.join(d, 'block.py')!r}).read(), 'scorers_block', 'exec'), m.__dict__)\n"
70
+ f"print(' both candidates importable -> WINNER:', sys.modules[m.RSMScorer.__module__].SOURCE)\n"
71
+ )
72
+ r = subprocess.run([sys.executable, "-c", runner], capture_output=True, text=True)
73
+ print(r.stdout.rstrip() if r.stdout.strip() else " PROBE FAILED:\n" + r.stderr.rstrip()[-600:])
rsm_rise/scripts/real/patchexport_item1.sh ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # rsm_real#5 item 1: (a) rebuild the openpi patch with the inference/training-split fix, (b) prove the
3
+ # fix leaves stock pi0.5 BC actions BIT-IDENTICAL on replay frames, (c) prove the pre-fix patch cannot
4
+ # construct the policy when the training split file is absent.
5
+ # Everything happens in $SCRATCH -- the rsm_rise tree is only read.
6
+ set -uo pipefail
7
+ ROOT=/proj/dmfexp/zwhong/rsm_rise
8
+ REPO=${REPO:-/proj/dmfexp/zwhong/projs/rsm_real}
9
+ PATCH_REF=${PATCH_REF:-920ead0}
10
+ SCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run1}
11
+ PIN=215abfb217dbac7d5f1273282331b9b1866c0479
12
+ CKPT=${CKPT:-$ROOT/hf_ckpt_root/pi05_bc_rsm_real_stock_s1_29999}
13
+ PY=$ROOT/third_party/openpi/.venv/bin/python
14
+ FRAMES=${FRAMES:-8}
15
+ EP=${EP:-0}
16
+ MISSING=$SCRATCH/no_such_dir/cooking_v5_split.json
17
+
18
+ export OPENPI_DATA_HOME=$ROOT/.openpi_assets HF_LEROBOT_HOME=$ROOT/data/real/lerobot_home
19
+ export HF_HUB_OFFLINE=1 TOKENIZERS_PARALLELISM=false PYTHONUNBUFFERED=1
20
+ export JAX_PLATFORMS=${JAX_PLATFORMS:-cpu}
21
+ unset PYTHONPATH
22
+
23
+ hdr(){ echo; echo "=================== $* ==================="; date -u; }
24
+ rc_all=0
25
+ chk(){ if [ "$1" -ne 0 ]; then echo "STEP FAILED rc=$1: $2"; rc_all=1; fi; }
26
+
27
+ hdr "0 context"
28
+ echo "host=$(hostname) job=${LSB_JOBID:-none} scratch=$SCRATCH patch_ref=$PATCH_REF ckpt=$CKPT"
29
+ mkdir -p "${SCRATCH:?}" || exit 1
30
+ cd "${SCRATCH:?}" || exit 1
31
+
32
+ hdr "1 take the exported patch out of rsm_real (by commit, so a branch switch cannot change it)"
33
+ git -C "$REPO" show "$PATCH_REF:rise_stack/openpi/rise_on_pi05.patch" > "$SCRATCH/rise_on_pi05.orig.patch" || exit 1
34
+ wc -l "$SCRATCH/rise_on_pi05.orig.patch"; md5sum "$SCRATCH/rise_on_pi05.orig.patch"
35
+ git -C "$REPO" show "$PATCH_REF:rise_stack/openpi/UPSTREAM_COMMIT.txt"
36
+
37
+ hdr "2 three clean upstream trees at $PIN"
38
+ for t in pre post verify; do
39
+ rm -rf "${SCRATCH:?}/${t:?}"
40
+ # the fork's .git is SHALLOW at the pin; --no-local avoids hardlinking into it, plain clone is the fallback
41
+ git clone --quiet --no-local "$ROOT/third_party/openpi" "${SCRATCH:?}/${t:?}" \
42
+ || git clone --quiet "$ROOT/third_party/openpi" "${SCRATCH:?}/${t:?}" || exit 1
43
+ git -C "$SCRATCH/$t" checkout --quiet "$PIN" || exit 1
44
+ echo "$t: HEAD=$(git -C "$SCRATCH/$t" rev-parse HEAD) dirty=[$(git -C "$SCRATCH/$t" status --porcelain | head -3)]"
45
+ done
46
+
47
+ hdr "3 apply the exported patch to pre/ and post/"
48
+ for t in pre post; do
49
+ ( cd "$SCRATCH/$t" && git apply --stat "$SCRATCH/rise_on_pi05.orig.patch" | tail -3 \
50
+ && git apply "$SCRATCH/rise_on_pi05.orig.patch" && echo "$t: git apply OK" )
51
+ chk $? "git apply on $t"
52
+ done
53
+ test -f "$SCRATCH/pre/src/openpi/policies/cooking_policy.py" && echo "cooking_policy.py present in pre/: yes"
54
+
55
+ hdr "4 apply the episodes fix to post/"
56
+ "$PY" - "$SCRATCH/post" <<'FIXEOF'
57
+ import sys, pathlib
58
+ root = pathlib.Path(sys.argv[1])
59
+
60
+ def sub(relpath, old, new, tag):
61
+ p = root / relpath
62
+ s = p.read_text()
63
+ n = s.count(old)
64
+ if n != 1:
65
+ raise SystemExit(f"FATAL: {tag}: anchor found {n} times in {relpath}, expected 1")
66
+ p.write_text(s.replace(old, new))
67
+ print(f"[fix] {tag}: {relpath} patched")
68
+
69
+ # --- 1. DataConfig: record the split file that was requested -------------------------------------
70
+ sub("src/openpi/training/config.py",
71
+ """ # rsm_rise: restrict the LeRobot dataset to these episode indices (None = all).
72
+ episodes: Sequence[int] | None = None
73
+ """,
74
+ """ # rsm_rise: restrict the LeRobot dataset to these episode indices (None = all).
75
+ episodes: Sequence[int] | None = None
76
+ # rsm_rise (rsm_real#5): the split file `episodes` was asked to come from, recorded even when that
77
+ # file was absent when the config was built. `episodes` is a TRAINING-only field, but openpi builds
78
+ # the data config during policy construction, so inference must be able to build it without the
79
+ # split file; the training data loader refuses to run when this is set and `episodes` is None.
80
+ episodes_required_from: str | None = None
81
+ """, "DataConfig.episodes_required_from")
82
+
83
+ # --- 2. episode_subset(): missing split file is an inference case, not an error -------------------
84
+ sub("src/openpi/training/config.py",
85
+ """ def episode_subset(self) -> list[int] | None:
86
+ if self.split == "all" or self.split_json is None:
87
+ return None
88
+ import json
89
+
90
+ with open(self.split_json) as fh:
91
+ """,
92
+ """ def episode_subset(self) -> list[int] | None:
93
+ if self.split == "all" or self.split_json is None:
94
+ return None
95
+ import json
96
+ import os
97
+
98
+ if not os.path.exists(self.split_json):
99
+ # rsm_real#5: openpi builds this data config during POLICY CONSTRUCTION, so requiring the
100
+ # training split file here made inference depend on a training-only absolute path. The
101
+ # `episodes` field is consumed ONLY by training (data_loader.create_torch_dataset), so
102
+ # returning None leaves every inference transform and the checkpoint normalisation
103
+ # untouched. Training does not silently fall back to all episodes: create_torch_dataset
104
+ # raises when `episodes_required_from` is set and `episodes` is None.
105
+ logging.warning(
106
+ "episode split file %s not found: continuing with episodes=None. This is the "
107
+ "inference path; a training run with this config will fail in create_torch_dataset.",
108
+ self.split_json,
109
+ )
110
+ return None
111
+ with open(self.split_json) as fh:
112
+ """, "episode_subset() inference fallback")
113
+
114
+ # --- 3. create(): pass the requested split path through ------------------------------------------
115
+ sub("src/openpi/training/config.py",
116
+ """ episodes=self.episode_subset(),
117
+ """,
118
+ """ episodes=self.episode_subset(),
119
+ episodes_required_from=(self.split_json if self.split != "all" else None),
120
+ """, "create() episodes_required_from")
121
+
122
+ # --- 4. the training guard -----------------------------------------------------------------------
123
+ sub("src/openpi/training/data_loader.py",
124
+ """ if repo_id == "fake":
125
+ return FakeDataset(model_config, num_samples=1024)
126
+
127
+ dataset_meta = lerobot_dataset.LeRobotDatasetMetadata(repo_id)
128
+ """,
129
+ """ if repo_id == "fake":
130
+ return FakeDataset(model_config, num_samples=1024)
131
+
132
+ # rsm_rise (rsm_real#5): `episodes` is None either because no subset was requested or because the
133
+ # split file was missing when the config was built (the inference path -- see
134
+ # LeRobotCookingDataConfig.episode_subset). Training must never take the second branch silently:
135
+ # it would train on the held-out validation episodes.
136
+ if data_config.episodes is None and data_config.episodes_required_from is not None:
137
+ raise FileNotFoundError(
138
+ f"episode split file {data_config.episodes_required_from!r} is required to build the "
139
+ "training dataset for this config and was not found; refusing to fall back to all "
140
+ "episodes (that would train on the held-out split)."
141
+ )
142
+
143
+ dataset_meta = lerobot_dataset.LeRobotDatasetMetadata(repo_id)
144
+ """, "create_torch_dataset training guard")
145
+ print("[fix] all four hunks applied")
146
+ FIXEOF
147
+ chk $? "apply fix to post/"
148
+
149
+ hdr "5 regenerate the patch from post/ (git add -A so no untracked file can be omitted again)"
150
+ ( cd "$SCRATCH/post" && git add -A && git diff --cached > "$SCRATCH/rise_on_pi05.new.patch" \
151
+ && echo "--- files touched by the new patch ---" && git diff --cached --stat | tail -12 \
152
+ && echo "--- untracked left behind (must be empty) ---" && git status --porcelain | grep '^??' )
153
+ echo "(no untracked leftovers is the expected empty grep above)"
154
+ wc -l "$SCRATCH/rise_on_pi05.new.patch"; md5sum "$SCRATCH/rise_on_pi05.new.patch"
155
+ echo "files in new patch: $(grep -c '^+++ ' "$SCRATCH/rise_on_pi05.new.patch")"
156
+
157
+ hdr "6 the new patch applies clean to a pristine upstream clone and reproduces post/ exactly"
158
+ ( cd "$SCRATCH/verify" && git apply --check "$SCRATCH/rise_on_pi05.new.patch" && echo "git apply --check: OK" \
159
+ && git apply "$SCRATCH/rise_on_pi05.new.patch" && echo "git apply: OK" )
160
+ chk $? "apply new patch to verify/"
161
+ diff -r -q --exclude=.git "$SCRATCH/post" "$SCRATCH/verify" && echo "post/ == verify/ (patch is complete)"
162
+ chk $? "post == verify"
163
+
164
+ hdr "7 construct-only checks (no weights): pre/ vs post/, split file present vs absent"
165
+ for t in pre post; do
166
+ for sj in PRESENT MISSING; do
167
+ echo "--- tree=$t split=$sj ---"
168
+ "$PY" - "$SCRATCH/$t/src" "$sj" "$MISSING" "$t" <<'CEOF'
169
+ import dataclasses, json, pathlib, sys
170
+ src, mode, missing, tname = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]
171
+ sys.path.insert(0, src)
172
+ import openpi
173
+ assert str(pathlib.Path(openpi.__file__).resolve()).startswith(src), openpi.__file__
174
+ print("openpi.__file__ =", openpi.__file__)
175
+ from openpi.training import config as _config
176
+ cfg = _config.get_config("pi05_cooking_stock")
177
+ if mode == "MISSING":
178
+ cfg = dataclasses.replace(cfg, data=dataclasses.replace(cfg.data, split_json=missing))
179
+ print("split_json =", cfg.data.split_json, "exists =", pathlib.Path(cfg.data.split_json).exists())
180
+ try:
181
+ dc = cfg.data.create(cfg.assets_dirs, cfg.model)
182
+ except Exception as e:
183
+ print("data.create() RAISED", type(e).__name__, e)
184
+ print("RESULT: CONSTRUCT_FAILED")
185
+ sys.exit(0)
186
+ eps = dc.episodes
187
+ print("data.create() OK: episodes =", "None" if eps is None else f"{len(eps)} ids {list(eps)[:4]}...",
188
+ "| episodes_required_from =", getattr(dc, "episodes_required_from", "<field absent>"),
189
+ "| norm_stats =", None if dc.norm_stats is None else sorted(dc.norm_stats))
190
+ print("transforms: data.inputs =", [type(t).__name__ for t in dc.data_transforms.inputs],
191
+ "| model.inputs =", [type(t).__name__ for t in dc.model_transforms.inputs])
192
+ if eps is not None and mode == "PRESENT":
193
+ pathlib.Path(f"/tmp/eps_{tname}.json").write_text(json.dumps(list(map(int, eps))))
194
+ from openpi.training import data_loader as _dl
195
+ try:
196
+ _dl.create_torch_dataset(dc, 10, cfg.model)
197
+ print("create_torch_dataset:", "returned a dataset (training path intact)" if eps is not None
198
+ else "DID NOT RAISE -- training would silently use ALL episodes")
199
+ except FileNotFoundError as e:
200
+ print("create_torch_dataset: FileNotFoundError ->", str(e)[:200])
201
+ except Exception as e:
202
+ print("create_torch_dataset:", type(e).__name__, str(e)[:200])
203
+ print("RESULT: CONSTRUCT_OK")
204
+ CEOF
205
+ done
206
+ done
207
+
208
+ hdr "7b the training episode list must be IDENTICAL pre vs post when the split file is present"
209
+ if cmp -s /tmp/eps_pre.json /tmp/eps_post.json; then
210
+ 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)"
211
+ else
212
+ echo "EPISODES DIFFER -- training semantics changed"; rc_all=1
213
+ fi
214
+
215
+ hdr "8 stock pi0.5 BC actions: pre/ (split present) vs post/ (split present) vs post/ (split ABSENT)"
216
+ INF=$ROOT/scripts/real/patchexport_pi05_infer.py
217
+ "$PY" "$INF" --src "$SCRATCH/pre/src" --ckpt "$CKPT" --out "$SCRATCH/actions_A_pre_present.npz" --ep "$EP" --frames "$FRAMES"
218
+ chk $? "infer A (pre, split present)"
219
+ "$PY" "$INF" --src "$SCRATCH/post/src" --ckpt "$CKPT" --out "$SCRATCH/actions_B_post_present.npz" --ep "$EP" --frames "$FRAMES"
220
+ chk $? "infer B (post, split present)"
221
+ "$PY" "$INF" --src "$SCRATCH/post/src" --ckpt "$CKPT" --out "$SCRATCH/actions_C_post_absent.npz" --ep "$EP" --frames "$FRAMES" --split-json "$MISSING"
222
+ chk $? "infer C (post, split absent)"
223
+
224
+ hdr "9 bit-identity"
225
+ "$PY" - "$SCRATCH" <<'CMPEOF'
226
+ import itertools, pathlib, sys
227
+ import numpy as np
228
+ s = pathlib.Path(sys.argv[1])
229
+ names = {"A_pre_present": "pre-fix patch, split file present",
230
+ "B_post_present": "post-fix patch, split file present",
231
+ "C_post_absent": "post-fix patch, split file ABSENT (deployment case)"}
232
+ arr = {}
233
+ for k, d in names.items():
234
+ p = s / f"actions_{k}.npz"
235
+ if not p.exists():
236
+ print(f"MISSING {p}"); continue
237
+ z = np.load(p); arr[k] = z["pred"]
238
+ print(f"{k:16s} {d:52s} shape={z['pred'].shape} dtype={z['pred'].dtype} idx={z['idx'].tolist()}")
239
+ ok = True
240
+ for a, b in itertools.combinations(arr, 2):
241
+ x, y = arr[a], arr[b]
242
+ if x.shape != y.shape:
243
+ print(f"{a} vs {b}: SHAPE MISMATCH {x.shape} {y.shape}"); ok = False; continue
244
+ d = np.abs(x.astype("float64") - y.astype("float64")).max()
245
+ eq = bool(np.array_equal(x, y)) and x.dtype == y.dtype
246
+ print(f"{a} vs {b}: max|diff| = {d:.17g} bitwise identical = {eq}")
247
+ ok = ok and eq and d == 0.0
248
+ print("VERDICT:", "BIT-IDENTICAL across all compared runs" if ok and len(arr) > 1 else "NOT IDENTICAL / INCOMPLETE")
249
+ CMPEOF
250
+
251
+ hdr "done"
252
+ echo "OVERALL rc=$rc_all"
253
+ exit $rc_all
rsm_rise/scripts/real/patchexport_item2_checks.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """rsm_real#5 item 2 acceptance: does the exported robomimic patch reconstruct the IQL critic?
3
+
4
+ Run INSIDE the environment built by patchexport_item2_validate.sh (upstream robomimic at the pin +
5
+ rise_on_robomimic.patch, installed editable; no research tree on sys.path).
6
+
7
+ C1 provenance -- what was imported, and from where
8
+ C2 the algo registry resolves `idql`, the name the checkpoint carries
9
+ C3 robomimic's own loader reconstructs the checkpoint
10
+ C4 the deployment adapter (rise_stack.scorers.build("idql", ...)) returns finite [N] scores for
11
+ N candidate chunks on a logged observation, and a schema mismatch fails loudly
12
+ """
13
+ import argparse, json, sys, time
14
+ from pathlib import Path
15
+
16
+ import numpy as np
17
+
18
+ RESEARCH = "/proj/dmfexp/zwhong/rsm_rise"
19
+ DATA = f"{RESEARCH}/data/real/rsm_cooking_v5"
20
+
21
+
22
+ def logged_frame_and_chunks(ep=0, n=8, horizon=10, stride=10):
23
+ import av, pyarrow.parquet as pq
24
+ tab = pq.read_table(f"{DATA}/data/chunk-000/episode_{ep:06d}.parquet").to_pandas()
25
+ S = np.stack(tab["observation.state"].values).astype(np.float32)
26
+ A = np.stack(tab["action"].values).astype(np.float32)
27
+ idxs = [i for i in range(0, len(tab) - horizon, stride)][:n]
28
+ cands = np.stack([A[i:i + horizon] for i in idxs]).astype(np.float32)
29
+ imgs = {}
30
+ for cam, key in (("global", "observation.images.global"), ("wrist", "observation.images.wrist")):
31
+ with av.open(f"{DATA}/videos/chunk-000/{key}/episode_{ep:06d}.mp4") as c:
32
+ st = c.streams.video[0]; st.thread_type = "AUTO"
33
+ for k, fr in enumerate(c.decode(st)):
34
+ if k == 0:
35
+ imgs[cam] = fr.to_ndarray(format="rgb24"); break
36
+ return imgs, S[0], cands, idxs
37
+
38
+
39
+ def main():
40
+ ap = argparse.ArgumentParser()
41
+ ap.add_argument("--repo", required=True)
42
+ ap.add_argument("--ckpt", required=True)
43
+ ap.add_argument("--out", required=True)
44
+ ap.add_argument("--n", type=int, default=8)
45
+ args = ap.parse_args()
46
+ rep = {"argv": sys.argv}
47
+
48
+ print("=== C1 provenance ===")
49
+ print("sys.executable =", sys.executable)
50
+ sys.path.insert(0, args.repo)
51
+ import torch, robomimic, diffusers
52
+ import diffusion_policy
53
+ mods = {}
54
+ for m in (torch, robomimic, diffusers, diffusion_policy):
55
+ # diffusion_policy is a NAMESPACE package (no __init__.py anywhere), so __file__ is None
56
+ origin = getattr(m, "__file__", None) or (list(getattr(m, "__path__", [])) or [None])[0]
57
+ mods[m.__name__] = {"file": str(Path(origin).resolve()) if origin else "<no origin>",
58
+ "version": getattr(m, "__version__", None)}
59
+ import rise_stack
60
+ mods["rise_stack"] = {"file": str(Path(rise_stack.__file__).resolve()), "version": None}
61
+ for k, v in mods.items():
62
+ print(f" {k:16s} {str(v['version'] or ''):12s} {v['file']}")
63
+ if v["file"].startswith(RESEARCH + "/code") or "/rsm_rise/env/" in v["file"]:
64
+ raise SystemExit(f"FATAL: {k} came from the research checkout: {v['file']}")
65
+ rep["modules"] = mods
66
+
67
+ print("\n=== C2 the algo registry ===")
68
+ import robomimic.algo as A
69
+ print(" registered:", sorted(A.algo_name_to_factory_func.__globals__["REGISTERED_ALGO_FACTORY_FUNCS"])
70
+ if "REGISTERED_ALGO_FACTORY_FUNCS" in A.algo_name_to_factory_func.__globals__ else "<registry private>")
71
+ f = A.algo_name_to_factory_func("idql")
72
+ print(" algo_name_to_factory_func('idql') ->", f)
73
+ rep["C2"] = {"factory": str(f)}
74
+
75
+ print("\n=== C3 robomimic's own loader ===")
76
+ import robomimic.utils.file_utils as FileUtils
77
+ t0 = time.time()
78
+ policy, ckpt_dict = FileUtils.policy_from_checkpoint(ckpt_path=args.ckpt, device=torch.device("cpu"),
79
+ verbose=False)
80
+ algo = policy.policy
81
+ print(f" loaded in {time.time()-t0:.1f}s: {type(algo).__module__}.{type(algo).__name__}")
82
+ print(" obs_shapes =", dict(algo.obs_shapes))
83
+ print(" ac_dim =", algo.ac_dim, " nets =", sorted(algo.nets.keys()))
84
+ n_par = sum(p.numel() for p in algo.nets.parameters())
85
+ print(f" parameters = {n_par:,}")
86
+ rep["C3"] = {"class": f"{type(algo).__module__}.{type(algo).__name__}",
87
+ "obs_shapes": {k: list(v) for k, v in algo.obs_shapes.items()},
88
+ "ac_dim": int(algo.ac_dim), "nets": sorted(algo.nets.keys()), "parameters": int(n_par)}
89
+
90
+ print("\n=== C4 through the deployment adapter ===")
91
+ from rise_stack.config import ActionNorm
92
+ from rise_stack.scorers import build
93
+ from rise_stack import obs as obs_mod
94
+ an = ActionNorm.load(str(Path(args.repo) / "rise_stack/configs/action_norm.json"))
95
+ scorer = build("idql", an, {"idql_ckpt": args.ckpt}, device="cpu")
96
+ print(" scorer:", type(scorer).__name__, "keys:", scorer.keys)
97
+ imgs, state, cands, idxs = logged_frame_and_chunks(n=args.n)
98
+ obs = obs_mod.make_obs(imgs, state, an.gripper_thresh, t=0)
99
+ print(f" observation: logged episode 0 frame 0; candidates = {cands.shape} from logged chunks at {idxs}")
100
+ t0 = time.time()
101
+ choice, scores = scorer.pick(cands, obs)
102
+ dt = time.time() - t0
103
+ scores = np.asarray(scores)
104
+ print(f" scores shape={scores.shape} dtype={scores.dtype} finite={bool(np.isfinite(scores).all())} "
105
+ f"in {dt*1000:.0f} ms (CPU)")
106
+ print(" scores =", np.array2string(scores, precision=6))
107
+ print(" argmax =", choice, " min/max =", float(scores.min()), float(scores.max()),
108
+ " std =", float(scores.std()))
109
+ ok = scores.shape == (args.n,) and bool(np.isfinite(scores).all())
110
+ rep["C4"] = {"shape": list(scores.shape), "finite": bool(np.isfinite(scores).all()),
111
+ "scores": scores.tolist(), "argmax": int(choice), "latency_s": dt,
112
+ "vf_quantile": getattr(scorer, "vf_quantile", None)}
113
+
114
+ print("\n permuted control (the same critic, candidates shuffled):")
115
+ pc = build("permuted:idql", an, {"idql_ckpt": args.ckpt}, device="cpu")
116
+ ch2, sc2 = pc.pick(cands, obs)
117
+ print(" ", np.array2string(np.asarray(sc2), precision=6), "argmax", ch2)
118
+
119
+ print("\n a schema mismatch must fail loudly, not score silently:")
120
+ try:
121
+ scorer.pick(cands[:, :, :5], obs)
122
+ print(" NO ERROR -- that is a defect")
123
+ ok = False
124
+ except Exception as e:
125
+ print(f" {type(e).__name__}: {str(e)[:160]}")
126
+
127
+ rep["ok"] = ok
128
+ Path(args.out).write_text(json.dumps(rep, indent=1, default=str))
129
+ print("\nC4 VERDICT:", "PASS -- finite [N] scores through the deployment adapter" if ok else "FAIL")
130
+ print("wrote", args.out)
131
+ sys.exit(0 if ok else 1)
132
+
133
+
134
+ if __name__ == "__main__":
135
+ main()
rsm_rise/scripts/real/patchexport_item2_export.sh ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # rsm_real#5 item 2: export code/rise_robomimic as a PATCH against upstream
3
+ # ARISE-Initiative/robomimic@40e427a (v0.3.0) -- the probe (LSF 1886202) showed the fork is that
4
+ # revision plus 42 touched .py files with zero upstream files missing.
5
+ # Overlays only SOURCE files, reports everything it deliberately did not overlay, and verifies the
6
+ # patch reapplies to a pristine clone.
7
+ set -uo pipefail
8
+ ROOT=/proj/dmfexp/zwhong/rsm_rise
9
+ FORK=$ROOT/code/rise_robomimic
10
+ SCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run4}
11
+ PIN=${PIN:-40e427a695a9f085d3fc0f70ffb0d687a10802c8}
12
+ hdr(){ echo; echo "=================== $* ==================="; date -u; }
13
+ rc_all=0
14
+ chk(){ if [ "$1" -ne 0 ]; then echo "STEP FAILED rc=$1: $2"; rc_all=1; fi; }
15
+ mkdir -p "${SCRATCH:?}" || exit 1
16
+
17
+ hdr "0 context"
18
+ echo "host=$(hostname) job=${LSB_JOBID:-none} fork=$FORK pin=$PIN scratch=$SCRATCH"
19
+ echo "fork version: $(grep -m1 __version__ "$FORK/robomimic/__init__.py")"
20
+
21
+ hdr "1 two pristine upstream clones at the pin"
22
+ for t in post verify; do
23
+ rm -rf "${SCRATCH:?}/${t:?}"
24
+ git clone --quiet https://github.com/ARISE-Initiative/robomimic.git "${SCRATCH:?}/${t:?}" || exit 1
25
+ git -C "$SCRATCH/$t" checkout --quiet "$PIN" || exit 1
26
+ echo "$t: HEAD=$(git -C "$SCRATCH/$t" rev-parse HEAD) clean=[$(git -C "$SCRATCH/$t" status --porcelain | head -2)]"
27
+ done
28
+
29
+ hdr "2 overlay the fork's SOURCE files onto post/"
30
+ python3 - "$FORK" "$SCRATCH/post" <<'OVEOF'
31
+ import filecmp, os, shutil, sys
32
+ from pathlib import Path
33
+ fork, dst = Path(sys.argv[1]), Path(sys.argv[2])
34
+ SKIP_DIR = {"__pycache__", ".git", "robomimic.egg-info", "docs", ".ipynb_checkpoints"}
35
+ INCLUDE_TOP = {"robomimic", "tests", "examples"} # source trees we carry
36
+ EXTRA_FILES = {"setup.py", "requirements.txt", "MANIFEST.in"}
37
+
38
+ def wanted(rel: Path) -> bool:
39
+ if ".bak." in rel.name or rel.suffix == ".pyc":
40
+ return False
41
+ if rel.suffix != ".py":
42
+ return False
43
+ return rel.parts[0] in INCLUDE_TOP
44
+
45
+ copied, skipped_nonsource = [], []
46
+ for dirpath, dirnames, filenames in os.walk(fork):
47
+ dirnames[:] = [d for d in dirnames if d not in SKIP_DIR]
48
+ for fn in filenames:
49
+ src = Path(dirpath) / fn
50
+ rel = src.relative_to(fork)
51
+ if rel.parts[0] in SKIP_DIR:
52
+ continue
53
+ if wanted(rel):
54
+ tgt = dst / rel
55
+ tgt.parent.mkdir(parents=True, exist_ok=True)
56
+ if not tgt.exists() or not filecmp.cmp(src, tgt, shallow=False):
57
+ shutil.copy2(src, tgt)
58
+ copied.append(str(rel))
59
+ elif ".bak." not in rel.name and rel.suffix not in (".pyc",):
60
+ skipped_nonsource.append(str(rel))
61
+
62
+ for fn in sorted(EXTRA_FILES):
63
+ src, tgt = fork / fn, dst / fn
64
+ if src.is_file() and tgt.is_file() and not filecmp.cmp(src, tgt, shallow=False):
65
+ shutil.copy2(src, tgt)
66
+ copied.append(fn + " (packaging file, differs from upstream)")
67
+ elif src.is_file() and not tgt.is_file():
68
+ shutil.copy2(src, tgt)
69
+ copied.append(fn + " (packaging file, new)")
70
+
71
+ print(f"overlaid {len(copied)} source files that differ from upstream:")
72
+ for c in sorted(copied):
73
+ print(" ", c)
74
+ print(f"\nNOT overlaid, {len(skipped_nonsource)} non-.py files under the carried trees (data, notebooks,"
75
+ " shell scripts, licences). Listed so nothing is silently dropped:")
76
+ for s in sorted(skipped_nonsource)[:60]:
77
+ print(" ", s)
78
+ if len(skipped_nonsource) > 60:
79
+ print(f" … and {len(skipped_nonsource) - 60} more")
80
+ # upstream files the fork does not have at all
81
+ missing = []
82
+ for dirpath, dirnames, filenames in os.walk(dst):
83
+ dirnames[:] = [d for d in dirnames if d not in SKIP_DIR]
84
+ for fn in filenames:
85
+ rel = (Path(dirpath) / fn).relative_to(dst)
86
+ if rel.suffix == ".py" and rel.parts[0] in INCLUDE_TOP and not (fork / rel).is_file():
87
+ missing.append(str(rel))
88
+ print(f"\nupstream .py files absent from the fork ({len(missing)}): {missing}")
89
+ OVEOF
90
+ chk $? "overlay"
91
+
92
+ hdr "3 generate the patches (package and research tests, separately)"
93
+ # upstream .gitignore lists macros_private.py, so a plain `git add -A` silently drops it -- the same
94
+ # class of bug that lost cooking_policy.py from the openpi export. Force-add every overlaid file that
95
+ # git considers ignored.
96
+ ( cd "$SCRATCH/post" && git add -A \
97
+ && ignored=$(git status --porcelain --ignored=matching | awk '$1=="!!"{print $2}') \
98
+ && if [ -n "$ignored" ]; then echo "force-adding gitignored source files: $ignored"; \
99
+ for f in $ignored; do case "$f" in *__pycache__*|*.pyc) ;; *) git add -f "$f";; esac; done; fi \
100
+ && echo "--- still untracked/ignored after force-add (must contain no source file) ---" \
101
+ && git status --porcelain --ignored=matching | head -10 )
102
+ chk $? "stage"
103
+ ( cd "$SCRATCH/post" \
104
+ && git diff --cached -- robomimic > "$SCRATCH/rise_on_robomimic.patch" \
105
+ && git diff --cached -- tests examples > "$SCRATCH/rise_on_robomimic_tests.patch" \
106
+ && echo "--- package patch ---" && git diff --cached --stat -- robomimic | tail -46 \
107
+ && echo "--- research-tests patch ---" && git diff --cached --stat -- tests examples | tail -12 \
108
+ && echo "--- anything staged OUTSIDE those two (must be empty) ---" \
109
+ && git diff --cached --stat -- . ':(exclude)robomimic' ':(exclude)tests' ':(exclude)examples' )
110
+ chk $? "generate"
111
+ for f in rise_on_robomimic.patch rise_on_robomimic_tests.patch; do
112
+ wc -l "$SCRATCH/$f"; md5sum "$SCRATCH/$f"; echo " files: $(grep -c '^+++ ' "$SCRATCH/$f")"
113
+ done
114
+
115
+ hdr "4 both patches reapply to a pristine clone and reproduce post/ exactly"
116
+ ( cd "$SCRATCH/verify" \
117
+ && git apply --check "$SCRATCH/rise_on_robomimic.patch" && echo "package: git apply --check OK" \
118
+ && git apply "$SCRATCH/rise_on_robomimic.patch" && echo "package: git apply OK" \
119
+ && git apply --check "$SCRATCH/rise_on_robomimic_tests.patch" && echo "tests: git apply --check OK" \
120
+ && git apply "$SCRATCH/rise_on_robomimic_tests.patch" && echo "tests: git apply OK" )
121
+ chk $? "reapply"
122
+ diff -r -q --exclude=.git --exclude=__pycache__ "$SCRATCH/post" "$SCRATCH/verify" && echo "post/ == verify/"
123
+ chk $? "post == verify"
124
+
125
+ hdr "4b the patched tree is the fork, file for file, for every source file we carried"
126
+ python3 - "$FORK" "$SCRATCH/verify" <<'CMPEOF'
127
+ import filecmp, os, sys
128
+ from pathlib import Path
129
+ fork, got = Path(sys.argv[1]), Path(sys.argv[2])
130
+ SKIP_DIR = {"__pycache__", ".git", "robomimic.egg-info", "docs", ".ipynb_checkpoints"}
131
+ bad = []
132
+ n = 0
133
+ for dirpath, dirnames, filenames in os.walk(fork):
134
+ dirnames[:] = [d for d in dirnames if d not in SKIP_DIR]
135
+ for fn in filenames:
136
+ rel = (Path(dirpath) / fn).relative_to(fork)
137
+ if rel.suffix != ".py" or ".bak." in rel.name or rel.parts[0] not in {"robomimic", "tests", "examples"}:
138
+ continue
139
+ n += 1
140
+ tgt = got / rel
141
+ if not tgt.is_file():
142
+ bad.append(("MISSING", str(rel)))
143
+ elif not filecmp.cmp(fork / rel, tgt, shallow=False):
144
+ bad.append(("DIFFERS", str(rel)))
145
+ print(f"compared {n} source files from the fork against the patched clone")
146
+ for kind, rel in bad:
147
+ print(" ", kind, rel)
148
+ print("VERDICT:", "the patch reconstructs every carried source file byte for byte" if not bad
149
+ else f"{len(bad)} FILES NOT RECONSTRUCTED")
150
+ sys.exit(1 if bad else 0)
151
+ CMPEOF
152
+ chk $? "patch reconstructs the fork"
153
+
154
+ hdr "5 does the patch leak anything it should not?"
155
+ echo "--- absolute cluster paths ---"
156
+ grep -n "^+.*\(/proj/dmfexp\|/u/zwhong\|/gpfs\)" "$SCRATCH/rise_on_robomimic.patch" | head -40
157
+ echo "(count: $(grep -c "^+.*\(/proj/dmfexp\|/u/zwhong\|/gpfs\)" "$SCRATCH/rise_on_robomimic.patch"))"
158
+ echo "--- credentials / keys ---"
159
+ grep -n -i "^+.*\(api_key\|apikey\|secret\|token\s*=\|password\|wandb_api\|gho_\|hf_[A-Za-z0-9]\{20\}\)" \
160
+ "$SCRATCH/rise_on_robomimic.patch" | head -20
161
+ echo "(count: $(grep -c -i "^+.*\(api_key\|apikey\|secret\|token\s*=\|password\|wandb_api\)" "$SCRATCH/rise_on_robomimic.patch"))"
162
+
163
+ hdr "done"
164
+ echo "OVERALL rc=$rc_all"
165
+ exit $rc_all
rsm_rise/scripts/real/patchexport_item2_probe.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """rsm_real#5 item 2 probe: what does rise_actor_rsm_real_s0_e3000.pth actually need?
3
+
4
+ Three questions, answered with measurements rather than by copying a 104-file fork:
5
+ A. the checkpoint's own metadata -- algo name, config, obs modalities, state-dict module names;
6
+ B. the static import closure of the registered algo module inside the fork;
7
+ C. how far the fork has drifted from upstream ARISE-Initiative/robomimic at a candidate ref, so we
8
+ can decide between a patch (option b) and vendoring the closure (option a).
9
+ """
10
+ import argparse, ast, hashlib, json, os, sys
11
+ from pathlib import Path
12
+
13
+ SKIP_DIR = {"__pycache__", ".git", "robomimic.egg-info", "docs"}
14
+
15
+
16
+ def is_source(p: Path) -> bool:
17
+ return p.suffix == ".py" and ".bak." not in p.name
18
+
19
+
20
+ def md5(p: Path) -> str:
21
+ return hashlib.md5(p.read_bytes()).hexdigest()
22
+
23
+
24
+ def walk_py(root: Path):
25
+ for dirpath, dirnames, filenames in os.walk(root):
26
+ dirnames[:] = [d for d in dirnames if d not in SKIP_DIR]
27
+ for fn in filenames:
28
+ p = Path(dirpath) / fn
29
+ if is_source(p):
30
+ yield p.relative_to(root)
31
+
32
+
33
+ def module_to_file(fork: Path, mod: str):
34
+ parts = mod.split(".")
35
+ cand = [fork.joinpath(*parts).with_suffix(".py"), fork.joinpath(*parts, "__init__.py")]
36
+ for c in cand:
37
+ if c.is_file():
38
+ return c
39
+ return None
40
+
41
+
42
+ def closure(fork: Path, start: Path, pkg="robomimic"):
43
+ """Follow robomimic.* imports from `start`; report external imports separately."""
44
+ seen, external, queue = {}, {}, [start]
45
+ while queue:
46
+ f = queue.pop()
47
+ rel = str(f.relative_to(fork))
48
+ if rel in seen:
49
+ continue
50
+ try:
51
+ tree = ast.parse(f.read_text())
52
+ except SyntaxError as e:
53
+ seen[rel] = {"lines": -1, "error": str(e)}
54
+ continue
55
+ seen[rel] = {"lines": len(f.read_text().splitlines())}
56
+ mods = []
57
+ for node in ast.walk(tree):
58
+ if isinstance(node, ast.Import):
59
+ mods += [a.name for a in node.names]
60
+ elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module:
61
+ mods.append(node.module)
62
+ elif isinstance(node, ast.ImportFrom) and node.level:
63
+ base = f.relative_to(fork).parent
64
+ for _ in range(node.level - 1):
65
+ base = base.parent
66
+ mods.append(str(base).replace("/", ".") + ("." + node.module if node.module else ""))
67
+ for m in sorted(set(mods)):
68
+ if m.split(".")[0] == pkg:
69
+ tgt = module_to_file(fork, m)
70
+ if tgt is not None:
71
+ queue.append(tgt)
72
+ else:
73
+ external.setdefault(m, "unresolved inside the fork")
74
+ else:
75
+ external.setdefault(m, None)
76
+ return seen, external
77
+
78
+
79
+ def main():
80
+ ap = argparse.ArgumentParser()
81
+ ap.add_argument("--ckpt", required=True)
82
+ ap.add_argument("--fork", required=True)
83
+ ap.add_argument("--upstream", default=None, help="a checkout of upstream robomimic to compare against")
84
+ ap.add_argument("--out", required=True)
85
+ args = ap.parse_args()
86
+ fork = Path(args.fork)
87
+ rep = {"ckpt": args.ckpt, "fork": str(fork)}
88
+
89
+ print("=== A. checkpoint metadata ===")
90
+ import torch
91
+ blob = torch.load(args.ckpt, map_location="cpu", weights_only=False)
92
+ print("top-level keys:", sorted(blob) if isinstance(blob, dict) else type(blob))
93
+ rep["ckpt_keys"] = sorted(blob) if isinstance(blob, dict) else str(type(blob))
94
+ algo_name = blob.get("algo_name")
95
+ print("algo_name =", algo_name)
96
+ rep["algo_name"] = algo_name
97
+ cfg = blob.get("config")
98
+ if isinstance(cfg, str):
99
+ cfg = json.loads(cfg)
100
+ if isinstance(cfg, dict):
101
+ rep["config_algo_name"] = cfg.get("algo_name")
102
+ print("config.algo_name =", cfg.get("algo_name"))
103
+ print("config.experiment.name =", cfg.get("experiment", {}).get("name"))
104
+ print("config.observation.modalities =", json.dumps(cfg.get("observation", {}).get("modalities"), indent=1))
105
+ enc = cfg.get("observation", {}).get("encoder")
106
+ print("config.observation.encoder =", json.dumps(enc, indent=1)[:1500])
107
+ print("config.algo keys =", sorted((cfg.get("algo") or {}).keys()))
108
+ rep["config_algo"] = cfg.get("algo")
109
+ rep["config_observation"] = cfg.get("observation")
110
+ rep["config_train_data"] = (cfg.get("train") or {}).get("data")
111
+ Path(args.out + ".config.json").write_text(json.dumps(cfg, indent=1))
112
+ print("full config written to", args.out + ".config.json")
113
+ sm = blob.get("shape_metadata")
114
+ print("shape_metadata =", json.dumps(sm, indent=1)[:1200] if sm else None)
115
+ rep["shape_metadata"] = sm
116
+ model = blob.get("model")
117
+ if isinstance(model, dict):
118
+ tops = sorted({k.split(".")[0] for k in model})
119
+ print("state-dict top-level modules:", tops)
120
+ print("n tensors:", len(model), "n params:",
121
+ sum(int(v.numel()) for v in model.values() if hasattr(v, "numel")))
122
+ rep["state_dict_top"] = tops
123
+ rep["state_dict_n_tensors"] = len(model)
124
+ rep["state_dict_n_params"] = sum(int(v.numel()) for v in model.values() if hasattr(v, "numel"))
125
+ nested = sorted({".".join(k.split(".")[:3]) for k in model})[:40]
126
+ print("first 40 module prefixes:", json.dumps(nested, indent=1))
127
+ print("obs_normalization_stats:", None if blob.get("obs_normalization_stats") is None
128
+ else sorted(blob["obs_normalization_stats"]))
129
+
130
+ print("\n=== B. static import closure of the registered algo module ===")
131
+ cands = [f"robomimic/algo/{algo_name}.py"] if algo_name else []
132
+ cands += ["robomimic/algo/iql_diffusion.py", "robomimic/algo/idql.py"]
133
+ rep["closures"] = {}
134
+ for c in dict.fromkeys(cands):
135
+ start = fork / c
136
+ if not start.is_file():
137
+ print(f"{c}: NOT PRESENT in the fork")
138
+ continue
139
+ seen, external = closure(fork, start)
140
+ tot = sum(v["lines"] for v in seen.values() if v["lines"] > 0)
141
+ print(f"\n{c}: {len(seen)} fork files, {tot} lines")
142
+ for k in sorted(seen):
143
+ print(f" {seen[k]['lines']:6d} {k}")
144
+ ext = sorted(e for e in external if e.split('.')[0] not in ("robomimic",))
145
+ print(f" external imports ({len(ext)}): {', '.join(ext)}")
146
+ unres = sorted(k for k, v in external.items() if v)
147
+ if unres:
148
+ print(" UNRESOLVED robomimic imports:", unres)
149
+ rep["closures"][c] = {"files": seen, "lines": tot, "external": ext, "unresolved": unres}
150
+
151
+ print("\n=== C. drift from upstream ===")
152
+ if args.upstream:
153
+ up = Path(args.upstream)
154
+ fr = fork
155
+ fset = {p for p in walk_py(fr / "robomimic")}
156
+ uset = {p for p in walk_py(up / "robomimic")}
157
+ same = sorted(p for p in fset & uset if md5(fr / "robomimic" / p) == md5(up / "robomimic" / p))
158
+ diff = sorted(p for p in fset & uset if md5(fr / "robomimic" / p) != md5(up / "robomimic" / p))
159
+ only_f = sorted(fset - uset)
160
+ only_u = sorted(uset - fset)
161
+ print(f"upstream {up}: identical={len(same)} modified={len(diff)} fork-only={len(only_f)} "
162
+ f"upstream-only={len(only_u)}")
163
+ print("modified:"); [print(" ", p) for p in diff]
164
+ print("fork-only:"); [print(" ", p) for p in only_f]
165
+ rep["drift"] = {"upstream": str(up), "identical": len(same), "modified": [str(p) for p in diff],
166
+ "fork_only": [str(p) for p in only_f], "upstream_only": [str(p) for p in only_u]}
167
+ else:
168
+ print("no --upstream given")
169
+
170
+ Path(args.out).write_text(json.dumps(rep, indent=1, default=str))
171
+ print("\nwrote", args.out)
172
+
173
+
174
+ if __name__ == "__main__":
175
+ main()
rsm_rise/scripts/real/patchexport_item2_probe.sh ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # rsm_real#5 item 2: probe what the IQL actor checkpoint needs, and how far code/rise_robomimic has
3
+ # drifted from upstream ARISE-Initiative/robomimic -- the input to "patch (option b) vs vendor (option a)".
4
+ set -uo pipefail
5
+ ROOT=/proj/dmfexp/zwhong/rsm_rise
6
+ SCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run3}
7
+ CKPT=${CKPT:-$ROOT/hf_ckpt_root/rise_actor_rsm_real_s0_e3000.pth}
8
+ source $ROOT/scripts/env.sh
9
+ export PYTHONUNBUFFERED=1
10
+ hdr(){ echo; echo "=================== $* ==================="; date -u; }
11
+ mkdir -p "${SCRATCH:?}" || exit 1
12
+
13
+ hdr "0 context"
14
+ echo "host=$(hostname) job=${LSB_JOBID:-none} python=$(which python) ckpt=$CKPT"
15
+ python -c "import torch;print('torch',torch.__version__)"
16
+
17
+ hdr "1 upstream robomimic clones (the fork says __version__ = $(grep -m1 __version__ $ROOT/code/rise_robomimic/robomimic/__init__.py))"
18
+ rm -rf "${SCRATCH:?}/robomimic_upstream"
19
+ git clone --quiet https://github.com/ARISE-Initiative/robomimic.git "${SCRATCH:?}/robomimic_upstream" \
20
+ && echo "cloned upstream robomimic" || { echo "CLONE FAILED (no network?)"; }
21
+ if [ -d "$SCRATCH/robomimic_upstream/.git" ]; then
22
+ git -C "$SCRATCH/robomimic_upstream" tag | tail -8
23
+ for ref in v0.3.1 v0.3.0 master; do
24
+ if git -C "$SCRATCH/robomimic_upstream" rev-parse -q --verify "$ref" >/dev/null \
25
+ || git -C "$SCRATCH/robomimic_upstream" rev-parse -q --verify "origin/$ref" >/dev/null; then
26
+ git -C "$SCRATCH/robomimic_upstream" checkout --quiet "$ref" 2>/dev/null \
27
+ || git -C "$SCRATCH/robomimic_upstream" checkout --quiet "origin/$ref"
28
+ echo "--- candidate $ref = $(git -C "$SCRATCH/robomimic_upstream" rev-parse HEAD) ---"
29
+ python "$ROOT/scripts/real/patchexport_item2_probe.py" --ckpt "$CKPT" \
30
+ --fork "$ROOT/code/rise_robomimic" --upstream "$SCRATCH/robomimic_upstream" \
31
+ --out "$SCRATCH/item2_probe_${ref}.json" 2>&1 | sed -n '/=== C. drift/,$p'
32
+ else
33
+ echo "ref $ref not found"
34
+ fi
35
+ done
36
+ fi
37
+
38
+ hdr "2 the full probe (checkpoint metadata + import closure), upstream = the last checkout"
39
+ python "$ROOT/scripts/real/patchexport_item2_probe.py" --ckpt "$CKPT" \
40
+ --fork "$ROOT/code/rise_robomimic" --upstream "$SCRATCH/robomimic_upstream" \
41
+ --out "$SCRATCH/item2_probe.json"
42
+
43
+ hdr "done"
rsm_rise/scripts/real/patchexport_item2_validate.sh ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # rsm_real#5 item 2: build the IQL inference environment from the exported patch alone and check that
3
+ # rise_actor_rsm_real_s0_e3000.pth reconstructs and scores. Fresh venv, research tree off sys.path.
4
+ set -uo pipefail
5
+ ROOT=/proj/dmfexp/zwhong/rsm_rise
6
+ SCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run5}
7
+ PATCH=${PATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run4/rise_on_robomimic.patch}
8
+ SRC=${SRC:-/proj/dmfexp/zwhong/scratch_patchexport/wt_main} # the rsm_real branch (for rise_stack)
9
+ PIN=${PIN:-40e427a695a9f085d3fc0f70ffb0d687a10802c8}
10
+ DP_PIN=${DP_PIN:-078ce1e}
11
+ CKPT=${CKPT:-$ROOT/hf_ckpt_root/rise_actor_rsm_real_s0_e3000.pth}
12
+ UV=${UV:-/u/zwhong/.local/bin/uv}
13
+ unset RISE_ROOT RSM_LIBERO_DIR PYTHONPATH HF_TOKEN HF_HUB_OFFLINE
14
+ export PYTHONNOUSERSITE=1 PYTHONUNBUFFERED=1 UV_CACHE_DIR=$SCRATCH/uv_cache HF_HOME=$SCRATCH/hf_home
15
+ export TORCH_HOME=$SCRATCH/torch_home MPLCONFIGDIR=$SCRATCH/mpl
16
+ hdr(){ echo; echo "=================== $* ==================="; date -u; }
17
+ rc_all=0
18
+ chk(){ if [ "$1" -ne 0 ]; then echo "STEP FAILED rc=$1: $2"; rc_all=1; fi; }
19
+ mkdir -p "${SCRATCH:?}" || exit 1
20
+
21
+ hdr "0 context"
22
+ echo "host=$(hostname) job=${LSB_JOBID:-none} patch=$PATCH ckpt=$CKPT"
23
+ md5sum "$PATCH"
24
+
25
+ hdr "1 upstream robomimic at the pin + the exported patch"
26
+ rm -rf "${SCRATCH:?}/robomimic"
27
+ git clone --quiet https://github.com/ARISE-Initiative/robomimic.git "${SCRATCH:?}/robomimic" || exit 1
28
+ git -C "$SCRATCH/robomimic" checkout --quiet "$PIN" || exit 1
29
+ ( cd "$SCRATCH/robomimic" && git apply "$PATCH" && echo "git apply: OK" && git status --porcelain | wc -l )
30
+ chk $? "apply robomimic patch"
31
+
32
+ hdr "2 the repo under test"
33
+ rm -rf "${SCRATCH:?}/rsm_real"
34
+ git clone --quiet "$SRC" "${SCRATCH:?}/rsm_real" || exit 1
35
+ REPO=$SCRATCH/rsm_real
36
+ echo "rsm_real HEAD: $(git -C "$REPO" rev-parse --short HEAD) $(git -C "$REPO" log -1 --pretty=%s)"
37
+
38
+ hdr "3 a fresh venv, pinned to what the checkpoint was TRAINED with"
39
+ # the training environment (rsm_rise/env, python 3.10) holds: torch 2.5.1+cu124, torchvision 0.20.1,
40
+ # numpy 1.26.4, diffusers 0.32.2, opencv-python 4.11.0.86, h5py 3.16.0, egl_probe 1.0.2, robomimic
41
+ # 0.3.0 (editable, this fork) and diffusion_policy 0.0.0 (editable, pin 078ce1e).
42
+ rm -rf "${SCRATCH:?}/venv"
43
+ "$UV" venv --python 3.10 "${SCRATCH:?}/venv" 2>&1 | tail -2
44
+ PY=$SCRATCH/venv/bin/python
45
+ UVP="$UV pip install --python $PY"
46
+ $UVP torch==2.5.1 torchvision==0.20.1 2>&1 | tail -1
47
+ chk $? "torch"
48
+ $UVP -e "$SCRATCH/robomimic" 2>&1 | tail -3
49
+ chk $? "robomimic (editable, from the patched clone)"
50
+ $UVP diffusers==0.32.2 2>&1 | tail -1
51
+ chk $? "diffusers"
52
+ # diffusion_policy has NO __init__.py anywhere, so its setup.py's find_packages() finds nothing and a
53
+ # non-editable `pip install git+...` installs ZERO modules while reporting success. It must go in
54
+ # editable (that is also how the training environment has it).
55
+ rm -rf "${SCRATCH:?}/diffusion_policy"
56
+ git clone --quiet https://github.com/UWRobotLearning/diffusion_policy.git "${SCRATCH:?}/diffusion_policy" \
57
+ && git -C "$SCRATCH/diffusion_policy" checkout --quiet "$DP_PIN" \
58
+ && echo "diffusion_policy HEAD: $(git -C "$SCRATCH/diffusion_policy" rev-parse HEAD)"
59
+ # Measured: `pip install git+…` AND `pip install -e` both report success and install ZERO modules,
60
+ # because setup.py uses find_packages() and the tree has no __init__.py anywhere (it is a namespace
61
+ # package). The working install is the clone on PYTHONPATH -- which is what the training environment
62
+ # effectively has (a legacy `setup.py develop` .pth pointing at the project root).
63
+ $UVP -e "$SCRATCH/diffusion_policy" 2>&1 | tail -2
64
+ "$PY" -c "import diffusion_policy" 2>/dev/null \
65
+ && echo "diffusion_policy: the editable install exposes it" \
66
+ || { echo "diffusion_policy: the editable install exposes NOTHING -- using the clone on PYTHONPATH"; \
67
+ export PYTHONPATH="$SCRATCH/diffusion_policy${PYTHONPATH:+:$PYTHONPATH}"; }
68
+ echo "PYTHONPATH=${PYTHONPATH:-<unset>}"
69
+ $UVP opencv-python==4.11.0.86 h5py==3.16.0 pyarrow pandas av 2>&1 | tail -1
70
+ chk $? "extras"
71
+ # anything above may have pulled numpy 2; the fork was trained on 1.26.4, so pin it LAST and check
72
+ $UVP "numpy==1.26.4" 2>&1 | tail -1
73
+ "$PY" -c "
74
+ import numpy, sys
75
+ print('numpy', numpy.__version__)
76
+ sys.exit(0 if numpy.__version__.startswith('1.') else 1)
77
+ "
78
+ chk $? "numpy stayed on 1.x"
79
+ echo '--- the import that a non-editable install silently loses ---'
80
+ "$PY" -c "
81
+ from diffusion_policy.model.diffusion.mask_generator import LowdimMaskGenerator
82
+ import diffusion_policy.model.diffusion.mask_generator as m
83
+ print('LowdimMaskGenerator from', m.__file__)
84
+ "
85
+ chk $? "diffusion_policy import"
86
+ "$UV" pip freeze --python "$PY" > "$SCRATCH/pip_freeze.txt"; wc -l "$SCRATCH/pip_freeze.txt"
87
+ grep -E "^(torch|torchvision|numpy|diffusers|robomimic|diffusion.policy|opencv|h5py|egl|tqdm|termcolor|tensorboard)" "$SCRATCH/pip_freeze.txt"
88
+
89
+ hdr "4 C1-C4"
90
+ "$PY" "$ROOT/scripts/real/patchexport_item2_checks.py" --repo "$REPO" --ckpt "$CKPT" \
91
+ --out "$SCRATCH/item2_checks.json"
92
+ chk $? "item2 checks"
93
+
94
+ hdr "done"
95
+ echo "OVERALL rc=$rc_all"
96
+ exit $rc_all
rsm_rise/scripts/real/patchexport_item3_apply_fix.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """rsm_real#5 item 3: make robomimic/algo/rsm_scorer.py find rsm_libero without a hardcoded path.
3
+
4
+ Applied to a CLONE of the robomimic fork (upstream pin + rise_on_robomimic.patch) before the patch is
5
+ regenerated, and before the validation run. Idempotent: it asserts the exact pre-image and is a no-op
6
+ if the fix is already in place.
7
+
8
+ Resolution order after the fix, so nothing that works today stops working:
9
+ 1. $RSM_LIBERO_DIR -- explicit override (the research tree keeps using it)
10
+ 2. the installed `rsm_libero` package -- its __init__ appends its own directory to sys.path, so the
11
+ unqualified `import model` inside those modules, and the module paths torch.save recorded at
12
+ training time, resolve exactly as they did in training
13
+ 3. the legacy absolute training path, only if it exists on this machine
14
+ """
15
+ import sys
16
+ from pathlib import Path
17
+
18
+ OLD_CONST = '''RSM_LIBERO_DIR = os.environ.get(
19
+ "RSM_LIBERO_DIR", "/proj/dmfexp/zwhong/rsm_rise/code/gen_q/rsm_libero")
20
+ '''
21
+
22
+ NEW_CONST = '''# rsm_real#5 item 3: no hardcoded training path. The override comes first, then the installed
23
+ # `rsm_libero` package (gen_q pin, see rise_stack/rsm_libero/UPSTREAM_COMMIT.txt), then -- only if it
24
+ # still exists on this machine -- the legacy training location, so research checkouts are unaffected.
25
+ RSM_LIBERO_DIR = os.environ.get("RSM_LIBERO_DIR", "")
26
+ RSM_LIBERO_LEGACY_DIR = "/proj/dmfexp/zwhong/rsm_rise/code/gen_q/rsm_libero"
27
+ '''
28
+
29
+ OLD_FN = '''def _rsm_modules():
30
+ """Import rsm_libero's model / train_rsm / is_ope lazily (they are plain top-level modules)."""
31
+ if RSM_LIBERO_DIR not in sys.path:
32
+ sys.path.insert(0, RSM_LIBERO_DIR)
33
+ model = importlib.import_module("model")
34
+ train_rsm = importlib.import_module("train_rsm")
35
+ is_ope = importlib.import_module("is_ope")
36
+ return model, train_rsm, is_ope
37
+ '''
38
+
39
+ NEW_FN = '''def _rsm_libero_dir():
40
+ """Where rsm_libero's top-level modules live, without assuming a cluster path.
41
+
42
+ $RSM_LIBERO_DIR wins if it is set. Otherwise the installed `rsm_libero` package is imported for
43
+ its side effect: its __init__ appends its own directory to sys.path, which is what makes the
44
+ unqualified `import model` inside model/train_rsm/is_ope -- and the module paths recorded in the
45
+ training checkpoints -- resolve. The legacy training path is tried last and only if it exists.
46
+ """
47
+ if RSM_LIBERO_DIR:
48
+ return RSM_LIBERO_DIR
49
+ try:
50
+ pkg = importlib.import_module("rsm_libero")
51
+ return os.path.dirname(os.path.abspath(pkg.__file__))
52
+ except ImportError:
53
+ pass
54
+ if os.path.isdir(RSM_LIBERO_LEGACY_DIR):
55
+ return RSM_LIBERO_LEGACY_DIR
56
+ raise ImportError(
57
+ "rsm_libero is not available: install the pinned gen_q source (pip install -e <gen_q clone>, "
58
+ "see rise_stack/rsm_libero/README.md) or set RSM_LIBERO_DIR to a checkout holding model.py, "
59
+ "train_rsm.py and is_ope.py")
60
+
61
+
62
+ def _rsm_modules():
63
+ """Import rsm_libero's model / train_rsm / is_ope lazily (they are plain top-level modules)."""
64
+ d = _rsm_libero_dir()
65
+ if d not in sys.path:
66
+ sys.path.insert(0, d)
67
+ model = importlib.import_module("model")
68
+ train_rsm = importlib.import_module("train_rsm")
69
+ is_ope = importlib.import_module("is_ope")
70
+ return model, train_rsm, is_ope
71
+ '''
72
+
73
+
74
+ def main():
75
+ path = Path(sys.argv[1])
76
+ src = path.read_text()
77
+ if "_rsm_libero_dir" in src:
78
+ print(f"already fixed: {path}")
79
+ return 0
80
+ for old in (OLD_CONST, OLD_FN):
81
+ if old not in src:
82
+ print(f"FATAL: pre-image not found in {path}:\n{old}")
83
+ return 2
84
+ src = src.replace(OLD_CONST, NEW_CONST).replace(OLD_FN, NEW_FN)
85
+ path.write_text(src)
86
+ print(f"patched {path}: RSM_LIBERO_DIR default removed, _rsm_libero_dir() added")
87
+ return 0
88
+
89
+
90
+ if __name__ == "__main__":
91
+ sys.exit(main())
rsm_rise/scripts/real/patchexport_item3_checks.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """rsm_real#5 item 3 acceptance: does the RSM scorer load and score from PINNED SOURCES ONLY?
3
+
4
+ Run INSIDE the environment built by patchexport_item3_validate.sh:
5
+ robomimic = upstream v0.3.0 + rise_on_robomimic.patch (with the item-3 import fix), editable
6
+ rsm_libero = gen_q at the pin + rise_on_rsm_libero.patch, editable (NO RSM_LIBERO_DIR)
7
+ dinov2 = the pinned upstream clone, used as torch.hub's local source
8
+
9
+ D1 provenance -- what was imported and from where; nothing may come from the research checkout
10
+ D2 rsm_scorer finds rsm_libero with RSM_LIBERO_DIR unset, via the installed package
11
+ D3 real/deployment/models.py reports no missing rsm source
12
+ D4 the real successor + hop head + feature statistics load and return finite [N] scores for N
13
+ candidate chunks through rise_stack.scorers.build("rsm", ...)
14
+ D5 the permuted control, and a schema mismatch that must fail loudly
15
+ """
16
+ import argparse, json, os, sys, time
17
+ from pathlib import Path
18
+
19
+ import numpy as np
20
+
21
+ RESEARCH = "/proj/dmfexp/zwhong/rsm_rise"
22
+ DATA = f"{RESEARCH}/data/real/rsm_cooking_v5"
23
+
24
+
25
+ def logged_frame_and_chunks(ep=0, n=8, horizon=10, stride=10):
26
+ """A logged observation and N logged action chunks -- the same fixture item 2 used."""
27
+ import av, pyarrow.parquet as pq
28
+ tab = pq.read_table(f"{DATA}/data/chunk-000/episode_{ep:06d}.parquet").to_pandas()
29
+ S = np.stack(tab["observation.state"].values).astype(np.float32)
30
+ A = np.stack(tab["action"].values).astype(np.float32)
31
+ idxs = [i for i in range(0, len(tab) - horizon, stride)][:n]
32
+ cands = np.stack([A[i:i + horizon] for i in idxs]).astype(np.float32)
33
+ imgs = {}
34
+ for cam, key in (("global", "observation.images.global"), ("wrist", "observation.images.wrist")):
35
+ with av.open(f"{DATA}/videos/chunk-000/{key}/episode_{ep:06d}.mp4") as c:
36
+ st = c.streams.video[0]; st.thread_type = "AUTO"
37
+ for k, fr in enumerate(c.decode(st)):
38
+ if k == 0:
39
+ imgs[cam] = fr.to_ndarray(format="rgb24"); break
40
+ return imgs, S[0], cands, idxs
41
+
42
+
43
+ def main():
44
+ ap = argparse.ArgumentParser()
45
+ ap.add_argument("--repo", required=True)
46
+ ap.add_argument("--rsm-ckpt", required=True)
47
+ ap.add_argument("--hop-ckpt", required=True)
48
+ ap.add_argument("--feat-stats", required=True)
49
+ ap.add_argument("--dino-hub", required=True)
50
+ ap.add_argument("--dino-ckpt", required=True)
51
+ ap.add_argument("--out", required=True)
52
+ ap.add_argument("--n", type=int, default=8)
53
+ ap.add_argument("--particles", type=int, default=16)
54
+ args = ap.parse_args()
55
+ rep = {"argv": sys.argv}
56
+ ok = True
57
+
58
+ print("=== D1 provenance ===")
59
+ print("sys.executable =", sys.executable)
60
+ print("RSM_LIBERO_DIR =", repr(os.environ.get("RSM_LIBERO_DIR")))
61
+ print("PYTHONPATH =", repr(os.environ.get("PYTHONPATH")))
62
+ sys.path.insert(0, args.repo)
63
+ import torch, robomimic, rsm_libero, rise_stack
64
+ mods = {}
65
+ for m in (torch, robomimic, rsm_libero, rise_stack):
66
+ origin = getattr(m, "__file__", None) or (list(getattr(m, "__path__", [])) or [None])[0]
67
+ mods[m.__name__] = {"file": str(Path(origin).resolve()) if origin else "<no origin>",
68
+ "version": getattr(m, "__version__", None)}
69
+ for k, v in mods.items():
70
+ print(f" {k:12s} {str(v['version'] or ''):10s} {v['file']}")
71
+ if v["file"].startswith(RESEARCH + "/code") or "/rsm_rise/env/" in v["file"]:
72
+ raise SystemExit(f"FATAL: {k} came from the research checkout: {v['file']}")
73
+ rep["modules"] = mods
74
+
75
+ print("\n=== D2 rsm_scorer resolves rsm_libero with RSM_LIBERO_DIR unset ===")
76
+ if os.environ.get("RSM_LIBERO_DIR"):
77
+ raise SystemExit("FATAL: RSM_LIBERO_DIR is set; this check is meaningless")
78
+ import robomimic.algo.rsm_scorer as RS
79
+ print(" robomimic.algo.rsm_scorer:", RS.__file__)
80
+ d = RS._rsm_libero_dir()
81
+ print(" _rsm_libero_dir() ->", d)
82
+ model, train_rsm, is_ope = RS._rsm_modules()
83
+ for m in (model, train_rsm, is_ope):
84
+ print(f" {m.__name__:10s} {m.__file__}")
85
+ if not str(Path(m.__file__).resolve()).startswith(str(Path(d).resolve())):
86
+ raise SystemExit(f"FATAL: {m.__name__} did not come from the installed rsm_libero")
87
+ rep["D2"] = {"dir": d, "modules": {m.__name__: m.__file__ for m in (model, train_rsm, is_ope)}}
88
+
89
+ print("\n=== D3 real/deployment/models.py dependency report ===")
90
+ sys.path.insert(0, args.repo)
91
+ from real.deployment import models as dep_models
92
+ report = dep_models.dependency_report("openpi", "rsm")
93
+ print(" missing:", report["missing"] or "(nothing)")
94
+ rsm_missing = [m for m in report["missing"] if "rsm" in m.lower()]
95
+ print(" rsm-related entries:", rsm_missing or "(none)")
96
+ ok = ok and not rsm_missing
97
+ rep["D3"] = {"missing": report["missing"], "rsm_missing": rsm_missing}
98
+
99
+ print("\n=== D4 the real scorer through the deployment adapter ===")
100
+ from rise_stack.config import ActionNorm
101
+ from rise_stack.scorers import build
102
+ from rise_stack import obs as obs_mod
103
+ an = ActionNorm.load(str(Path(args.repo) / "rise_stack/configs/action_norm.json"))
104
+ t0 = time.time()
105
+ scorer = build("rsm", an, {"rsm_ckpt": args.rsm_ckpt, "rsm_hop_ckpt": args.hop_ckpt,
106
+ "rsm_feat_stats": args.feat_stats,
107
+ "rsm_particles": args.particles,
108
+ "dino_hub_dir": args.dino_hub, "dino_checkpoint": args.dino_ckpt},
109
+ device="cpu")
110
+ build_s = time.time() - t0
111
+ print(f" built in {build_s:.1f}s; dino hub={scorer.feat.hub_dir} weights={scorer.feat.checkpoint}")
112
+ imgs, state, cands, idxs = logged_frame_and_chunks(n=args.n)
113
+ obs = obs_mod.make_obs(imgs, state, an.gripper_thresh, t=0)
114
+ print(f" observation: logged episode 0 frame 0; candidates {cands.shape} from chunks at {idxs}")
115
+ t0 = time.time()
116
+ choice, scores = scorer.pick(cands, obs)
117
+ dt = time.time() - t0
118
+ scores = np.asarray(scores)
119
+ finite = bool(np.isfinite(scores).all())
120
+ print(f" scores shape={scores.shape} dtype={scores.dtype} finite={finite} in {dt:.2f}s (CPU)")
121
+ print(" scores =", np.array2string(scores, precision=6))
122
+ print(f" argmax={choice} min={float(scores.min()):.6f} max={float(scores.max()):.6f} std={float(scores.std()):.6f}")
123
+ print(f" chain: p={scorer.p_cont:.6f} cap={scorer.cap} E[queries]={scorer.E_queries:.2f} "
124
+ f"chunk={scorer.rsm.chunk} adim={scorer.rsm.adim}")
125
+ ok = ok and scores.shape == (args.n,) and finite
126
+ rep["D4"] = {"shape": list(scores.shape), "finite": finite, "scores": scores.tolist(),
127
+ "argmax": int(choice), "latency_s": dt, "build_s": build_s,
128
+ "p_cont": float(scorer.p_cont), "cap": int(scorer.cap),
129
+ "dino_hub": scorer.feat.hub_dir, "dino_ckpt": scorer.feat.checkpoint,
130
+ "hops": getattr(scorer, "hops", None)}
131
+
132
+ print("\n=== D5 permuted control, and a schema mismatch ===")
133
+ pc = build("permuted:rsm", an, {"rsm_ckpt": args.rsm_ckpt, "rsm_hop_ckpt": args.hop_ckpt,
134
+ "rsm_feat_stats": args.feat_stats, "rsm_particles": args.particles,
135
+ "dino_hub_dir": args.dino_hub, "dino_checkpoint": args.dino_ckpt},
136
+ device="cpu")
137
+ ch2, sc2 = pc.pick(cands, obs)
138
+ print(" permuted:", np.array2string(np.asarray(sc2), precision=6), "argmax", ch2)
139
+ rep["D5"] = {"permuted_scores": np.asarray(sc2).tolist(), "permuted_argmax": int(ch2)}
140
+ print(" a truncated action dimension must fail loudly:")
141
+ try:
142
+ scorer.pick(cands[:, :, :5], obs)
143
+ print(" NO ERROR -- that is a defect")
144
+ ok = False
145
+ except Exception as e:
146
+ print(f" {type(e).__name__}: {str(e)[:200]}")
147
+ rep["D5"]["truncated_raises"] = f"{type(e).__name__}: {str(e)[:200]}"
148
+
149
+ rep["ok"] = ok
150
+ Path(args.out).write_text(json.dumps(rep, indent=1, default=str))
151
+ print("\nVERDICT:", "PASS -- finite [N] RSM scores from pinned sources only" if ok else "FAIL")
152
+ print("wrote", args.out)
153
+ return 0 if ok else 1
154
+
155
+
156
+ if __name__ == "__main__":
157
+ sys.exit(main())
rsm_rise/scripts/real/patchexport_item3_genq_pack.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """rsm_real#5 item 3: make the pinned gen_q checkout's rsm_libero installable, without touching a
3
+ single line of the code that produced the checkpoints.
4
+
5
+ Our whole patch on top of gen_q is two new files:
6
+ rsm_libero/__init__.py -- appends its own directory to sys.path, so `import rsm_libero.is_ope`
7
+ works from an installed package while `import model` inside those
8
+ modules (and the module paths torch.save recorded during training)
9
+ still resolve to the SAME top-level modules as in training.
10
+ APPENDED, never prepended, so nothing here can shadow the stdlib.
11
+ pyproject.toml -- a minimal setuptools project exposing exactly that one package.
12
+
13
+ Run against a clone; idempotent.
14
+ """
15
+ import sys
16
+ from pathlib import Path
17
+
18
+ INIT = '''"""rsm_libero -- the RSM successor-model library (gen_q).
19
+
20
+ Deployment packaging (rsm_real#5 item 3). The modules in this directory import one another as
21
+ top-level modules (``import model``), which only works when this directory itself is on
22
+ ``sys.path``. Appending it here lets ``import rsm_libero`` work from an installed package while
23
+ leaving every module's own imports untouched, so the code that loads a checkpoint is byte-for-byte
24
+ the code that produced it. Appended rather than inserted, so no module here can shadow the standard
25
+ library for the rest of the process.
26
+ """
27
+ import os as _os
28
+ import sys as _sys
29
+
30
+ __all__ = []
31
+
32
+ _HERE = _os.path.dirname(_os.path.abspath(__file__))
33
+ if _HERE not in _sys.path:
34
+ _sys.path.append(_HERE)
35
+ '''
36
+
37
+ PYPROJECT = '''[build-system]
38
+ requires = ["setuptools>=61"]
39
+ build-backend = "setuptools.build_meta"
40
+
41
+ [project]
42
+ # rsm_real#5 item 3: packaging only. No source file in rsm_libero/ is modified by this project;
43
+ # this exists so a deployment machine can `pip install -e <gen_q clone>` instead of pointing an
44
+ # environment variable at a directory inside somebody's research checkout.
45
+ name = "rsm-libero"
46
+ version = "0.0.0"
47
+ description = "RSM successor-model library (gen_q), packaged for inference deployment"
48
+ requires-python = ">=3.9"
49
+
50
+ [tool.setuptools]
51
+ packages = ["rsm_libero"]
52
+ '''
53
+
54
+
55
+ def main():
56
+ root = Path(sys.argv[1])
57
+ lib = root / "rsm_libero"
58
+ if not lib.is_dir():
59
+ print(f"FATAL: {lib} is not a directory")
60
+ return 2
61
+ wrote = []
62
+ for rel, text in ((lib / "__init__.py", INIT), (root / "pyproject.toml", PYPROJECT)):
63
+ if rel.exists() and rel.read_text() == text:
64
+ continue
65
+ if rel.exists() and rel.name == "pyproject.toml":
66
+ print(f"FATAL: {rel} already exists with different content -- do not overwrite upstream")
67
+ return 2
68
+ rel.write_text(text)
69
+ wrote.append(str(rel.relative_to(root)))
70
+ print("wrote:", ", ".join(wrote) if wrote else "(nothing, already in place)")
71
+ return 0
72
+
73
+
74
+ if __name__ == "__main__":
75
+ sys.exit(main())
rsm_rise/scripts/real/patchexport_item3_probe.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """rsm_real#5 item 3 probe: what does the RSM inference closure actually need from rsm_libero?
3
+
4
+ Pure stdlib + ast. Run against a CLONE of gen_q at the pin.
5
+ P1 the four named files: sha256 at the pin vs the research working tree
6
+ P2 static intra-repo closure of model / train_rsm / is_ope / data (what else must ship)
7
+ P3 external (non-rsm_libero) imports of that closure -- the pip dependencies to pin
8
+ P4 stdlib shadowing: module names in rsm_libero that also exist in the standard library
9
+ """
10
+ import argparse, ast, hashlib, json, sys, sysconfig
11
+ from pathlib import Path
12
+
13
+ NAMED = ["model.py", "train_rsm.py", "is_ope.py", "data.py"]
14
+
15
+
16
+ def sha(p):
17
+ return hashlib.sha256(Path(p).read_bytes()).hexdigest()[:16] if Path(p).is_file() else None
18
+
19
+
20
+ def imports_of(path):
21
+ tree = ast.parse(Path(path).read_text(), filename=str(path))
22
+ out = set()
23
+ for n in ast.walk(tree):
24
+ if isinstance(n, ast.Import):
25
+ for a in n.names:
26
+ out.add(a.name.split(".")[0])
27
+ elif isinstance(n, ast.ImportFrom):
28
+ if n.level == 0 and n.module:
29
+ out.add(n.module.split(".")[0])
30
+ return out
31
+
32
+
33
+ def main():
34
+ ap = argparse.ArgumentParser()
35
+ ap.add_argument("--pin-lib", required=True, help="rsm_libero/ inside the clone at the pin")
36
+ ap.add_argument("--research-lib", required=True, help="rsm_libero/ in the research checkout")
37
+ ap.add_argument("--out", required=True)
38
+ a = ap.parse_args()
39
+ pin, res = Path(a.pin_lib), Path(a.research_lib)
40
+ rep = {}
41
+
42
+ print("=== P1 the four files named by the issue ===")
43
+ rep["files"] = {}
44
+ for f in NAMED:
45
+ sp, sr = sha(pin / f), sha(res / f)
46
+ same = "SAME" if sp == sr else "DIFFERS"
47
+ print(f" {f:16s} pin={sp} research_worktree={sr} {same}")
48
+ rep["files"][f] = {"pin_sha256_16": sp, "research_sha256_16": sr, "same": sp == sr}
49
+
50
+ print("\n=== P2 intra-repo closure (what else has to ship) ===")
51
+ have = {p.stem: p for p in pin.glob("*.py")}
52
+ seen, queue = set(), [f[:-3] for f in NAMED]
53
+ ext = set()
54
+ while queue:
55
+ name = queue.pop()
56
+ if name in seen or name not in have:
57
+ continue
58
+ seen.add(name)
59
+ for imp in imports_of(have[name]):
60
+ if imp in have:
61
+ queue.append(imp)
62
+ else:
63
+ ext.add(imp)
64
+ closure = sorted(seen)
65
+ lines = sum(len(have[n].read_text().splitlines()) for n in closure)
66
+ print(f" closure = {len(closure)} modules, {lines} lines: {', '.join(closure)}")
67
+ print(f" (the package ships all {len(have)} modules in rsm_libero/ -- this is what is REACHED)")
68
+ rep["closure"] = {"modules": closure, "lines": lines, "package_modules": len(have)}
69
+
70
+ print("\n=== P3 external imports of that closure (the pins a deployment env needs) ===")
71
+ std = set(sys.stdlib_module_names)
72
+ third = sorted(m for m in ext if m not in std)
73
+ print(" stdlib :", ", ".join(sorted(m for m in ext if m in std)))
74
+ print(" third-party:", ", ".join(third))
75
+ rep["external"] = {"stdlib": sorted(m for m in ext if m in std), "third_party": third}
76
+
77
+ print("\n=== P4 stdlib shadowing (why __init__ APPENDS its directory) ===")
78
+ shadow = sorted(n for n in have if n in std)
79
+ print(" module names in rsm_libero that also name a stdlib module:", ", ".join(shadow) or "(none)")
80
+ print(" -> appending the directory to sys.path (never inserting) keeps the stdlib first")
81
+ rep["stdlib_shadow"] = shadow
82
+ rep["stdlib_dir"] = sysconfig.get_paths()["stdlib"]
83
+
84
+ Path(a.out).write_text(json.dumps(rep, indent=1))
85
+ print("\nwrote", a.out)
86
+ return 0
87
+
88
+
89
+ if __name__ == "__main__":
90
+ sys.exit(main())
rsm_rise/scripts/real/patchexport_item3_probe.sh ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # rsm_real#5 item 3: establish the gen_q pin + our packaging patch, and identify the DINOv2 source pin.
3
+ # No research tree on sys.path anywhere; nothing here writes outside $SCRATCH.
4
+ set -uo pipefail
5
+ ROOT=/proj/dmfexp/zwhong/rsm_rise
6
+ SCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run6}
7
+ GENQ_PIN=${GENQ_PIN:-f612011bb400ac204918be1d6f923e539cd59fd7}
8
+ RESEARCH_GENQ=${RESEARCH_GENQ:-/proj/dmfexp/zwhong/projs/issue_resolver_richardrl/gen_q_rsm}
9
+ DINO_LOCAL=${DINO_LOCAL:-$ROOT/cache/torch/hub/facebookresearch_dinov2_main}
10
+ unset RISE_ROOT RSM_LIBERO_DIR PYTHONPATH
11
+ export PYTHONNOUSERSITE=1 PYTHONUNBUFFERED=1 GIT_TERMINAL_PROMPT=0
12
+ hdr(){ echo; echo "=================== $* ==================="; date -u; }
13
+ rc_all=0
14
+ chk(){ if [ "$1" -ne 0 ]; then echo "STEP FAILED rc=$1: $2"; rc_all=1; fi; }
15
+ mkdir -p "${SCRATCH:?}" || exit 1
16
+
17
+ hdr "0 context"
18
+ echo "host=$(hostname) job=${LSB_JOBID:-none} scratch=$SCRATCH genq_pin=$GENQ_PIN"
19
+ PY3=$(command -v python3); echo "python3=$PY3 ($($PY3 -V))"
20
+
21
+ hdr "1 gen_q at the pin (sparse: rsm_libero only)"
22
+ rm -rf "${SCRATCH:?}/gen_q"
23
+ git clone --quiet --filter=blob:none --no-checkout https://github.com/williamd4112/gen_q.git "${SCRATCH:?}/gen_q" || exit 1
24
+ git -C "$SCRATCH/gen_q" sparse-checkout set rsm_libero >/dev/null || exit 1
25
+ git -C "$SCRATCH/gen_q" checkout --quiet "$GENQ_PIN" || exit 1
26
+ echo "gen_q HEAD = $(git -C "$SCRATCH/gen_q" rev-parse HEAD)"
27
+ git -C "$SCRATCH/gen_q" log -1 --pretty=' %h %ad %s' --date=iso
28
+ echo "rsm_libero modules at the pin: $(ls "$SCRATCH/gen_q/rsm_libero"/*.py | wc -l)"
29
+
30
+ hdr "2 probe: closure, external deps, stdlib shadowing"
31
+ "$PY3" "$ROOT/scripts/real/patchexport_item3_probe.py" \
32
+ --pin-lib "$SCRATCH/gen_q/rsm_libero" --research-lib "$RESEARCH_GENQ/rsm_libero" \
33
+ --out "$SCRATCH/item3_probe.json"
34
+ chk $? "probe"
35
+
36
+ hdr "3 our packaging patch on gen_q, generated the way that cannot lose an untracked file"
37
+ "$PY3" "$ROOT/scripts/real/patchexport_item3_genq_pack.py" "$SCRATCH/gen_q"
38
+ chk $? "pack"
39
+ ( cd "$SCRATCH/gen_q" && git add -A && git diff --cached > "$SCRATCH/rise_on_rsm_libero.patch" )
40
+ chk $? "generate patch"
41
+ echo "--- patch ---"; git -C "$SCRATCH/gen_q" diff --cached --stat | tail -5
42
+ md5sum "$SCRATCH/rise_on_rsm_libero.patch"
43
+
44
+ hdr "4 the patch applies to a SECOND pristine clone and reproduces the tree exactly"
45
+ rm -rf "${SCRATCH:?}/gen_q_verify"
46
+ git clone --quiet --filter=blob:none --no-checkout https://github.com/williamd4112/gen_q.git "${SCRATCH:?}/gen_q_verify" \
47
+ && git -C "$SCRATCH/gen_q_verify" sparse-checkout set rsm_libero >/dev/null \
48
+ && git -C "$SCRATCH/gen_q_verify" checkout --quiet "$GENQ_PIN" \
49
+ && ( cd "$SCRATCH/gen_q_verify" && git apply "$SCRATCH/rise_on_rsm_libero.patch" && echo "git apply: OK" )
50
+ chk $? "reapply"
51
+ diff -r --exclude=.git "$SCRATCH/gen_q" "$SCRATCH/gen_q_verify" && echo "diff -r: IDENTICAL (patch is complete)"
52
+ chk $? "diff -r"
53
+
54
+ hdr "5 the packaged import works, and does not shadow the stdlib"
55
+ ( cd "$SCRATCH" && "$PY3" - <<'PYX'
56
+ import sys, os
57
+ sys.path.insert(0, os.path.join(os.environ["SCRATCH"], "gen_q"))
58
+ import rsm_libero
59
+ print("rsm_libero.__file__ =", rsm_libero.__file__)
60
+ d = os.path.dirname(os.path.abspath(rsm_libero.__file__))
61
+ print("its directory is on sys.path:", d in sys.path, "at index", sys.path.index(d), "of", len(sys.path))
62
+ import types, importlib
63
+ for name in ("json", "types", "code", "pickle"):
64
+ m = importlib.import_module(name)
65
+ f = getattr(m, "__file__", "<builtin>") or "<builtin>"
66
+ assert d not in str(f), f"stdlib {name} was shadowed by {f}"
67
+ print("stdlib not shadowed (json/types/code/pickle still resolve to the standard library)")
68
+ PYX
69
+ )
70
+ chk $? "packaged import"
71
+
72
+ hdr "6 DINOv2: which upstream commit is the local hub tree?"
73
+ rm -rf "${SCRATCH:?}/dinov2"
74
+ git clone --quiet https://github.com/facebookresearch/dinov2.git "${SCRATCH:?}/dinov2" || exit 1
75
+ echo "local hub tree: $DINO_LOCAL"
76
+ best=""; bestn=999999
77
+ for c in $(git -C "$SCRATCH/dinov2" log --format=%H -40); do
78
+ git -C "$SCRATCH/dinov2" checkout --quiet "$c"
79
+ n=$(diff -r -q --exclude=.git --exclude=__pycache__ "$DINO_LOCAL" "$SCRATCH/dinov2" 2>/dev/null | wc -l)
80
+ if [ "$n" -lt "$bestn" ]; then bestn=$n; best=$c; fi
81
+ if [ "$n" -eq 0 ]; then break; fi
82
+ done
83
+ echo "closest upstream commit: $best differing entries: $bestn"
84
+ git -C "$SCRATCH/dinov2" checkout --quiet "$best"
85
+ git -C "$SCRATCH/dinov2" log -1 --pretty=' %h %ad %s' --date=iso
86
+ if [ "$bestn" -ne 0 ]; then
87
+ echo "--- residual differences (the hub cache is a zip export, so extras are expected) ---"
88
+ diff -r -q --exclude=.git --exclude=__pycache__ "$DINO_LOCAL" "$SCRATCH/dinov2" 2>/dev/null | head -20
89
+ fi
90
+ echo "$best" > "$SCRATCH/dinov2_pin.txt"
91
+
92
+ hdr "done"
93
+ echo "OVERALL rc=$rc_all"
94
+ exit $rc_all
rsm_rise/scripts/real/patchexport_item3_provenance.sh ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # rsm_real#5 item 3, last box: does real/deployment/models.py record the rsm_libero SOURCE PROVENANCE
3
+ # when the package is installed and RSM_LIBERO_DIR is unset? Reuses the venv built by
4
+ # patchexport_item3_validate.sh (run7) -- no rebuild.
5
+ set -uo pipefail
6
+ ROOT=/proj/dmfexp/zwhong/rsm_rise
7
+ SCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run7}
8
+ unset RISE_ROOT RSM_LIBERO_DIR HF_TOKEN
9
+ export PYTHONPATH="$SCRATCH/diffusion_policy" PYTHONNOUSERSITE=1 PYTHONUNBUFFERED=1
10
+ export TORCH_HOME=$SCRATCH/torch_home HF_HOME=$SCRATCH/hf_home MPLCONFIGDIR=$SCRATCH/mpl
11
+ PY=$SCRATCH/venv/bin/python
12
+ echo "host=$(hostname) job=${LSB_JOBID:-none} py=$PY"; date -u
13
+ "$PY" - <<'PYX'
14
+ import json, os, sys
15
+ sys.path.insert(0, os.path.join(os.environ["SCRATCH"], "rsm_real"))
16
+ from real.deployment import models
17
+ from rise_stack.config import ActionNorm
18
+ from rise_stack.scorers import build
19
+ S = os.environ["SCRATCH"]; R = "/proj/dmfexp/zwhong/rsm_rise/hf_ckpt_root"
20
+ print("RSM_LIBERO_DIR =", repr(os.environ.get("RSM_LIBERO_DIR")))
21
+ print("before loading anything:", json.dumps(models._source_roots(False), indent=1))
22
+ an = ActionNorm.load(os.path.join(S, "rsm_real/rise_stack/configs/action_norm.json"))
23
+ build("rsm", an, {"rsm_ckpt": f"{R}/successor_rsm_real_RM_s0_100k.pt",
24
+ "rsm_hop_ckpt": f"{R}/hop_head_rsm_real_gauss_r1.pt",
25
+ "rsm_feat_stats": f"{R}/successor_rsm_real_feat_stats.json",
26
+ "rsm_particles": 2,
27
+ "dino_hub_dir": f"{S}/dinov2",
28
+ "dino_checkpoint": f"{S}/dino_weights/dinov2_vits14_pretrain.pth"}, device="cpu")
29
+ roots = models._source_roots(False)
30
+ print("after building the rsm scorer:", json.dumps(roots, indent=1))
31
+ assert "rsm_libero" in roots, "provenance did not record rsm_libero"
32
+ assert roots["rsm_libero"].startswith(S), roots["rsm_libero"]
33
+ assert "robomimic" in roots, roots
34
+ print("PASS: provenance records the INSTALLED rsm_libero and robomimic, with no RSM_LIBERO_DIR set")
35
+ PYX
36
+ rc=$?
37
+ echo "OVERALL rc=$rc"; exit $rc
rsm_rise/scripts/real/patchexport_item3_repatch.sh ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # rsm_real#5 item 3: regenerate rise_on_robomimic.patch with the item-3 import fix folded in.
3
+ # Same staging idiom as patchexport_item2_export.sh: `git add -A` ALONE drops files the upstream
4
+ # .gitignore matches (macros_private.py), which is the class of bug that lost cooking_policy.py.
5
+ set -uo pipefail
6
+ ROOT=/proj/dmfexp/zwhong/rsm_rise
7
+ SCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run8}
8
+ SRC=${SRC:-/proj/dmfexp/zwhong/scratch_patchexport/wt_item3}
9
+ RM_PIN=${RM_PIN:-40e427a695a9f085d3fc0f70ffb0d687a10802c8}
10
+ export GIT_TERMINAL_PROMPT=0 PYTHONNOUSERSITE=1 PYTHONUNBUFFERED=1
11
+ hdr(){ echo; echo "=================== $* ==================="; date -u; }
12
+ rc_all=0
13
+ chk(){ if [ "$1" -ne 0 ]; then echo "STEP FAILED rc=$1: $2"; rc_all=1; fi; }
14
+ mkdir -p "${SCRATCH:?}" || exit 1
15
+
16
+ hdr "0 context"
17
+ echo "host=$(hostname) job=${LSB_JOBID:-none} scratch=$SCRATCH src=$SRC pin=$RM_PIN"
18
+ md5sum "$SRC/rise_stack/robomimic/rise_on_robomimic.patch" "$SRC/rise_stack/robomimic/rise_on_robomimic_tests.patch"
19
+
20
+ hdr "1 pristine clone at the pin + both shipped patches + the item-3 fix"
21
+ rm -rf "${SCRATCH:?}/post"
22
+ git clone --quiet https://github.com/ARISE-Initiative/robomimic.git "${SCRATCH:?}/post" || exit 1
23
+ git -C "$SCRATCH/post" checkout --quiet "$RM_PIN" || exit 1
24
+ ( cd "$SCRATCH/post" && git apply "$SRC/rise_stack/robomimic/rise_on_robomimic.patch" \
25
+ && git apply "$SRC/rise_stack/robomimic/rise_on_robomimic_tests.patch" && echo "both shipped patches apply: OK" )
26
+ chk $? "apply shipped patches"
27
+ python3 "$ROOT/scripts/real/patchexport_item3_apply_fix.py" "$SCRATCH/post/robomimic/algo/rsm_scorer.py"
28
+ chk $? "item-3 fix"
29
+
30
+ hdr "2 stage, force-adding anything the upstream .gitignore matches"
31
+ ( cd "$SCRATCH/post" && git add -A \
32
+ && ignored=$(git status --porcelain --ignored=matching | awk '$1=="!!"{print $2}') \
33
+ && if [ -n "$ignored" ]; then echo "force-adding gitignored source files: $ignored"; \
34
+ for f in $ignored; do case "$f" in *__pycache__*|*.pyc) ;; *) git add -f "$f";; esac; done; fi \
35
+ && echo "--- still untracked/ignored after force-add (must contain no source file) ---" \
36
+ && git status --porcelain --ignored=matching | head -10 )
37
+ chk $? "stage"
38
+
39
+ hdr "3 the two patches, scoped exactly as before"
40
+ ( cd "$SCRATCH/post" \
41
+ && git diff --cached -- robomimic > "$SCRATCH/rise_on_robomimic.patch" \
42
+ && git diff --cached -- tests examples > "$SCRATCH/rise_on_robomimic_tests.patch" \
43
+ && echo "--- package patch ---" && git diff --cached --shortstat -- robomimic \
44
+ && echo "--- research-tests patch ---" && git diff --cached --shortstat -- tests examples \
45
+ && echo "--- staged OUTSIDE those two (must be empty) ---" \
46
+ && git diff --cached --stat -- . ':(exclude)robomimic' ':(exclude)tests' ':(exclude)examples' )
47
+ chk $? "generate"
48
+ md5sum "$SCRATCH"/rise_on_robomimic*.patch
49
+ echo "macros_private.py hunks in the package patch: $(grep -c 'macros_private' "$SCRATCH/rise_on_robomimic.patch")"
50
+ echo "the item-3 fix in the package patch: $(grep -c '_rsm_libero_dir' "$SCRATCH/rise_on_robomimic.patch")"
51
+ echo "--- what changed vs the shipped package patch ---"
52
+ diff <(grep '^[+-]' "$SRC/rise_stack/robomimic/rise_on_robomimic.patch") \
53
+ <(grep '^[+-]' "$SCRATCH/rise_on_robomimic.patch") | head -80
54
+ echo "(diff of the +/- lines only; hunk headers move, so this is the readable form)"
55
+
56
+ hdr "4 both regenerated patches apply to a pristine clone and reproduce the tree exactly"
57
+ rm -rf "${SCRATCH:?}/verify"
58
+ git clone --quiet https://github.com/ARISE-Initiative/robomimic.git "${SCRATCH:?}/verify" \
59
+ && git -C "$SCRATCH/verify" checkout --quiet "$RM_PIN" \
60
+ && ( cd "$SCRATCH/verify" && git apply "$SCRATCH/rise_on_robomimic.patch" \
61
+ && git apply "$SCRATCH/rise_on_robomimic_tests.patch" && echo "git apply: OK" )
62
+ chk $? "reapply"
63
+ diff -r --exclude=.git "$SCRATCH/post" "$SCRATCH/verify" && echo "diff -r: IDENTICAL (nothing was lost)"
64
+ chk $? "diff -r"
65
+
66
+ hdr "5 the fix is syntactically sound and idempotent"
67
+ python3 -c "
68
+ import ast, sys
69
+ src = open('$SCRATCH/verify/robomimic/algo/rsm_scorer.py').read()
70
+ ast.parse(src)
71
+ assert 'RSM_LIBERO_DIR = os.environ.get(\"RSM_LIBERO_DIR\", \"\")' in src, 'default path not removed'
72
+ assert '/proj/dmfexp/zwhong/rsm_rise/code/gen_q/rsm_libero' in src, 'legacy fallback should stay, named once'
73
+ print('rsm_scorer.py parses; the hardcoded path survives only as the last-resort fallback')
74
+ "
75
+ chk $? "syntax"
76
+ python3 "$ROOT/scripts/real/patchexport_item3_apply_fix.py" "$SCRATCH/verify/robomimic/algo/rsm_scorer.py"
77
+ chk $? "idempotent"
78
+
79
+ hdr "done"
80
+ echo "OVERALL rc=$rc_all"
81
+ exit $rc_all
rsm_rise/scripts/real/patchexport_item3_validate.sh ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # rsm_real#5 item 3: build the RSM inference environment from PINNED SOURCES ONLY -- upstream repos at
3
+ # their pins plus our patches, no file copied out of the research tree -- and score real candidate
4
+ # chunks with the real successor. RSM_LIBERO_DIR stays UNSET throughout, on purpose.
5
+ set -uo pipefail
6
+ ROOT=/proj/dmfexp/zwhong/rsm_rise
7
+ SCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run7}
8
+ SRC=${SRC:-/proj/dmfexp/zwhong/scratch_patchexport/wt_item3} # the rsm_real branch under test
9
+ RM_PIN=${RM_PIN:-40e427a695a9f085d3fc0f70ffb0d687a10802c8} # robomimic v0.3.0
10
+ GENQ_PIN=${GENQ_PIN:-f612011bb400ac204918be1d6f923e539cd59fd7} # gen_q rsm_rise_data
11
+ DINO_PIN=${DINO_PIN:-7764ea0f912e53c92e82eb78a2a1631e92725fc8} # facebookresearch/dinov2
12
+ DP_PIN=${DP_PIN:-078ce1e}
13
+ RSM_CKPT=${RSM_CKPT:-$ROOT/hf_ckpt_root/successor_rsm_real_RM_s0_100k.pt}
14
+ HOP_CKPT=${HOP_CKPT:-$ROOT/hf_ckpt_root/hop_head_rsm_real_gauss_r1.pt}
15
+ FEAT_STATS=${FEAT_STATS:-$ROOT/hf_ckpt_root/successor_rsm_real_feat_stats.json}
16
+ DINO_WEIGHTS_LOCAL=${DINO_WEIGHTS_LOCAL:-/u/zwhong/.cache/torch/hub/checkpoints/dinov2_vits14_pretrain.pth}
17
+ DINO_URL=${DINO_URL:-https://dl.fbaipublicfiles.com/dinov2/dinov2_vits14/dinov2_vits14_pretrain.pth}
18
+ UV=${UV:-/u/zwhong/.local/bin/uv}
19
+ unset RISE_ROOT RSM_LIBERO_DIR PYTHONPATH HF_TOKEN HF_HUB_OFFLINE
20
+ export PYTHONNOUSERSITE=1 PYTHONUNBUFFERED=1 UV_CACHE_DIR=$SCRATCH/uv_cache HF_HOME=$SCRATCH/hf_home
21
+ export TORCH_HOME=$SCRATCH/torch_home MPLCONFIGDIR=$SCRATCH/mpl GIT_TERMINAL_PROMPT=0
22
+ hdr(){ echo; echo "=================== $* ==================="; date -u; }
23
+ rc_all=0
24
+ chk(){ if [ "$1" -ne 0 ]; then echo "STEP FAILED rc=$1: $2"; rc_all=1; fi; }
25
+ mkdir -p "${SCRATCH:?}" || exit 1
26
+
27
+ hdr "0 context"
28
+ echo "host=$(hostname) job=${LSB_JOBID:-none} scratch=$SCRATCH"
29
+ echo "pins: robomimic=$RM_PIN gen_q=$GENQ_PIN dinov2=$DINO_PIN diffusion_policy=$DP_PIN"
30
+ 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
31
+
32
+ hdr "1 robomimic: upstream pin + our patch + the item-3 import fix, patch REGENERATED"
33
+ rm -rf "${SCRATCH:?}/robomimic"
34
+ git clone --quiet https://github.com/ARISE-Initiative/robomimic.git "${SCRATCH:?}/robomimic" || exit 1
35
+ git -C "$SCRATCH/robomimic" checkout --quiet "$RM_PIN" || exit 1
36
+ ( cd "$SCRATCH/robomimic" && git apply "$SRC/rise_stack/robomimic/rise_on_robomimic.patch" && echo "exported patch applies: OK" )
37
+ chk $? "apply exported robomimic patch"
38
+ python3 "$ROOT/scripts/real/patchexport_item3_apply_fix.py" "$SCRATCH/robomimic/robomimic/algo/rsm_scorer.py"
39
+ chk $? "item-3 import fix"
40
+ ( cd "$SCRATCH/robomimic" && git add -A && git diff --cached > "$SCRATCH/rise_on_robomimic.patch" )
41
+ chk $? "regenerate robomimic patch"
42
+ git -C "$SCRATCH/robomimic" diff --cached --stat | tail -2
43
+ md5sum "$SCRATCH/rise_on_robomimic.patch"
44
+ rm -rf "${SCRATCH:?}/robomimic_verify"
45
+ git clone --quiet https://github.com/ARISE-Initiative/robomimic.git "${SCRATCH:?}/robomimic_verify" \
46
+ && git -C "$SCRATCH/robomimic_verify" checkout --quiet "$RM_PIN" \
47
+ && ( cd "$SCRATCH/robomimic_verify" && git apply "$SCRATCH/rise_on_robomimic.patch" && echo "regenerated patch applies to a pristine clone: OK" )
48
+ chk $? "reapply robomimic"
49
+ diff -r --exclude=.git "$SCRATCH/robomimic" "$SCRATCH/robomimic_verify" && echo "diff -r: IDENTICAL"
50
+ chk $? "robomimic diff -r"
51
+
52
+ hdr "2 rsm_libero: gen_q at the pin + our packaging patch"
53
+ rm -rf "${SCRATCH:?}/gen_q"
54
+ git clone --quiet --filter=blob:none --no-checkout https://github.com/williamd4112/gen_q.git "${SCRATCH:?}/gen_q" || exit 1
55
+ git -C "$SCRATCH/gen_q" sparse-checkout set rsm_libero >/dev/null && git -C "$SCRATCH/gen_q" checkout --quiet "$GENQ_PIN" || exit 1
56
+ python3 "$ROOT/scripts/real/patchexport_item3_genq_pack.py" "$SCRATCH/gen_q"
57
+ chk $? "gen_q packaging"
58
+ ( cd "$SCRATCH/gen_q" && git add -A && git diff --cached > "$SCRATCH/rise_on_rsm_libero.patch" )
59
+ md5sum "$SCRATCH/rise_on_rsm_libero.patch"
60
+
61
+ hdr "3 the rsm_real branch under test"
62
+ rm -rf "${SCRATCH:?}/rsm_real"
63
+ git clone --quiet "$SRC" "${SCRATCH:?}/rsm_real" || exit 1
64
+ REPO=$SCRATCH/rsm_real
65
+ echo "rsm_real HEAD: $(git -C "$REPO" rev-parse --short HEAD) $(git -C "$REPO" log -1 --pretty=%s)"
66
+
67
+ hdr "4 DINOv2 at its pin, plus the published weights"
68
+ rm -rf "${SCRATCH:?}/dinov2"
69
+ git clone --quiet https://github.com/facebookresearch/dinov2.git "${SCRATCH:?}/dinov2" \
70
+ && git -C "$SCRATCH/dinov2" checkout --quiet "$DINO_PIN" && echo "dinov2 HEAD: $(git -C "$SCRATCH/dinov2" rev-parse HEAD)"
71
+ chk $? "dinov2 clone"
72
+ mkdir -p "$SCRATCH/dino_weights"
73
+ W=$SCRATCH/dino_weights/dinov2_vits14_pretrain.pth
74
+ if [ ! -s "$W" ]; then
75
+ curl -fsSL --max-time 300 -o "$W" "$DINO_URL" && echo "weights downloaded from $DINO_URL" \
76
+ || { echo "download failed; falling back to the local torch hub cache (same file, stated as such)"; cp "$DINO_WEIGHTS_LOCAL" "$W"; }
77
+ fi
78
+ sha256sum "$W"; sha256sum "$DINO_WEIGHTS_LOCAL" 2>/dev/null
79
+
80
+ hdr "5 a fresh venv from the pins"
81
+ rm -rf "${SCRATCH:?}/venv"
82
+ "$UV" venv --python 3.10 "${SCRATCH:?}/venv" 2>&1 | tail -2
83
+ PY=$SCRATCH/venv/bin/python
84
+ UVP="$UV pip install --python $PY"
85
+ $UVP torch==2.5.1 torchvision==0.20.1 2>&1 | tail -1; chk $? "torch"
86
+ $UVP -e "$SCRATCH/robomimic" 2>&1 | tail -2; chk $? "robomimic editable"
87
+ $UVP diffusers==0.32.2 2>&1 | tail -1; chk $? "diffusers"
88
+ rm -rf "${SCRATCH:?}/diffusion_policy"
89
+ git clone --quiet https://github.com/UWRobotLearning/diffusion_policy.git "${SCRATCH:?}/diffusion_policy" \
90
+ && git -C "$SCRATCH/diffusion_policy" checkout --quiet "$DP_PIN"
91
+ # no __init__.py anywhere: the editable install exposes nothing, so the clone goes on PYTHONPATH
92
+ $UVP -e "$SCRATCH/diffusion_policy" 2>&1 | tail -1
93
+ "$PY" -c "import diffusion_policy" 2>/dev/null || export PYTHONPATH="$SCRATCH/diffusion_policy"
94
+ $UVP -e "$SCRATCH/gen_q" 2>&1 | tail -2; chk $? "rsm_libero editable (gen_q pin + packaging patch)"
95
+ $UVP opencv-python==4.11.0.86 h5py==3.16.0 pyarrow pandas av 2>&1 | tail -1; chk $? "extras"
96
+ $UVP "numpy==1.26.4" 2>&1 | tail -1
97
+ "$PY" -c "import numpy,sys; print('numpy',numpy.__version__); sys.exit(0 if numpy.__version__.startswith('1.') else 1)"
98
+ chk $? "numpy stayed on 1.x"
99
+ "$UV" pip freeze --python "$PY" > "$SCRATCH/pip_freeze.txt"; wc -l "$SCRATCH/pip_freeze.txt"
100
+ grep -E "^(torch|torchvision|numpy|diffusers|robomimic|rsm|opencv|h5py|av|wandb)" "$SCRATCH/pip_freeze.txt"
101
+ echo "--- wandb must NOT be needed: train_rsm imports it inside a training-only function ---"
102
+ "$PY" -c "
103
+ import importlib.util as u, sys
104
+ print('wandb installed:', u.find_spec('wandb') is not None)
105
+ import rsm_libero, train_rsm, model, is_ope
106
+ print('train_rsm from', train_rsm.__file__)
107
+ print('imported model/train_rsm/is_ope with no wandb present')
108
+ "
109
+ chk $? "rsm_libero imports without wandb"
110
+
111
+ hdr "6 D1-D5"
112
+ "$PY" "$ROOT/scripts/real/patchexport_item3_checks.py" --repo "$REPO" \
113
+ --rsm-ckpt "$RSM_CKPT" --hop-ckpt "$HOP_CKPT" --feat-stats "$FEAT_STATS" \
114
+ --dino-hub "$SCRATCH/dinov2" --dino-ckpt "$W" --out "$SCRATCH/item3_checks.json"
115
+ chk $? "item3 checks"
116
+
117
+ hdr "7 the repository's own deployment tests, in this environment"
118
+ $UVP pytest hydra-core==1.3.2 omegaconf 2>&1 | tail -1
119
+ ( cd "$REPO" && "$PY" -m pytest tests/test_deployment_models.py -q 2>&1 | tail -8 )
120
+ chk $? "deployment model tests"
121
+
122
+ hdr "done"
123
+ echo "OVERALL rc=$rc_all"
124
+ exit $rc_all
rsm_rise/scripts/real/patchexport_item4_mimicgen.sh ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # rsm_real#5 / owner directive: export code/mimicgen_environments as a PATCH against upstream
3
+ # UWRobotLearning/mimicgen_environments@14d8eb5. This tree is SIMULATION ONLY and is NOT a robot
4
+ # deployment dependency; it is exported for completeness so a sim result can be reproduced.
5
+ #
6
+ # The inventory in my brief said "46 changed + 43 untracked". Measured: `git status --porcelain`
7
+ # returns 3 M + 43 ?? = 46 entries, i.e. 3 modified SOURCE files (66 insertions) and 43 untracked
8
+ # entries that are NOT source. This script proves that classification rather than asserting it:
9
+ # every untracked entry must be either a *.bak.* backup or a runtime-generated MuJoCo XML written by
10
+ # upstream's own mimicgen_envs/models/robosuite/objects/xml_objects.py:81-83
11
+ # (`"{}_{}.xml".format(str(time.time()).replace(".","_"), os.getpid())`). Anything else fails the run.
12
+ set -uo pipefail
13
+ ROOT=/proj/dmfexp/zwhong/rsm_rise
14
+ FORK=$ROOT/code/mimicgen_environments
15
+ SCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run10}
16
+ PIN=${PIN:-14d8eb5709b38c6b75ecf140c3608ff984196832}
17
+ URL=https://github.com/UWRobotLearning/mimicgen_environments.git
18
+ hdr(){ echo; echo "=================== $* ==================="; date -u; }
19
+ rc_all=0
20
+ chk(){ if [ "$1" -ne 0 ]; then echo "STEP FAILED rc=$1: $2"; rc_all=1; fi; }
21
+ mkdir -p "${SCRATCH:?}" || exit 1
22
+
23
+ hdr "0 context"
24
+ echo "host=$(hostname) job=${LSB_JOBID:-none} fork=$FORK pin=$PIN scratch=$SCRATCH"
25
+ echo "fork HEAD: $(git -C "$FORK" rev-parse HEAD)"
26
+ echo "fork HEAD == pin: $([ "$(git -C "$FORK" rev-parse HEAD)" = "$PIN" ] && echo YES || echo NO)"
27
+
28
+ hdr "1 classify EVERY entry git reports in the fork -- no source file may be silently dropped"
29
+ git -C "$FORK" status --porcelain > "$SCRATCH/fork_status.txt"
30
+ echo "total entries: $(wc -l < "$SCRATCH/fork_status.txt")"
31
+ awk '{print $1}' "$SCRATCH/fork_status.txt" | sort | uniq -c
32
+ python3 - "$FORK" "$SCRATCH/fork_status.txt" <<'CLSEOF'
33
+ import re, sys
34
+ from pathlib import Path
35
+ fork, status = Path(sys.argv[1]), Path(sys.argv[2])
36
+ # upstream xml_objects.py writes "<epoch_with_underscore>_<pid>.xml" next to the object's model.xml
37
+ RUNTIME_XML = re.compile(r"^\d+_\d+_\d+\.xml$")
38
+ mod, bak, runtime, unknown = [], [], [], []
39
+ for line in status.read_text().splitlines():
40
+ code, rel = line[:2].strip(), line[3:].strip()
41
+ p = Path(rel)
42
+ if code == "M":
43
+ mod.append(rel)
44
+ elif ".bak." in p.name:
45
+ bak.append(rel)
46
+ elif RUNTIME_XML.match(p.name) and "assets" in p.parts:
47
+ runtime.append(rel)
48
+ else:
49
+ unknown.append((code, rel))
50
+ print(f"modified source files ({len(mod)}) -- THESE are the patch:")
51
+ for m in mod: print(" ", m)
52
+ print(f"\n*.bak.* editor backups, excluded by the standing rule ({len(bak)}):")
53
+ for b in bak: print(" ", b)
54
+ print(f"\nruntime-generated MuJoCo XML caches, excluded ({len(runtime)}):")
55
+ for r in runtime[:6]: print(" ", r)
56
+ if len(runtime) > 6: print(f" ... and {len(runtime)-6} more, all under the same assets dir")
57
+ dirs = sorted({str(Path(r).parent) for r in runtime})
58
+ print(f" dirs: {dirs}")
59
+ print(f"\nUNCLASSIFIED entries (must be empty) ({len(unknown)}): {unknown}")
60
+ sys.exit(1 if unknown else 0)
61
+ CLSEOF
62
+ chk $? "classification: every untracked entry accounted for as non-source"
63
+ echo "--- proof the runtime XMLs come from upstream code, not from us ---"
64
+ grep -n "time.time()\|os.getpid()\|new_xml_path" "$FORK/mimicgen_envs/models/robosuite/objects/xml_objects.py" | head -6
65
+ echo "--- is that writer file itself modified by us? (must print nothing) ---"
66
+ git -C "$FORK" diff --name-only -- mimicgen_envs/models/robosuite/objects/xml_objects.py
67
+ echo "--- the canonical tracked source for that object ---"
68
+ git -C "$FORK" ls-files "mimicgen_envs/models/robosuite/assets/shapenet_core/mugs/3143a4ac/" | grep '\.xml$'
69
+
70
+ hdr "2 two pristine upstream clones at the pin"
71
+ for t in post verify; do
72
+ rm -rf "${SCRATCH:?}/${t:?}"
73
+ git clone --quiet "$URL" "${SCRATCH:?}/${t:?}" || exit 1
74
+ git -C "$SCRATCH/$t" checkout --quiet "$PIN" || exit 1
75
+ echo "$t: HEAD=$(git -C "$SCRATCH/$t" rev-parse HEAD) clean=[$(git -C "$SCRATCH/$t" status --porcelain | head -2)]"
76
+ done
77
+
78
+ hdr "3 overlay the fork's modified source files onto post/"
79
+ while read -r rel; do
80
+ echo " overlay $rel"
81
+ cp -p "$FORK/$rel" "$SCRATCH/post/$rel" || exit 1
82
+ done < <(git -C "$FORK" diff --name-only)
83
+
84
+ hdr "4 generate the patch"
85
+ ( cd "$SCRATCH/post" && git add -A \
86
+ && ignored=$(git status --porcelain --ignored=matching | awk '$1=="!!"{print $2}') \
87
+ && if [ -n "$ignored" ]; then echo "force-adding gitignored source files: $ignored"; \
88
+ for f in $ignored; do case "$f" in *__pycache__*|*.pyc) ;; *) git add -f "$f";; esac; done; fi \
89
+ && echo "--- still untracked/ignored after force-add (must contain no source file) ---" \
90
+ && git status --porcelain --ignored=matching | head -10 \
91
+ && git diff --cached > "$SCRATCH/rise_on_mimicgen.patch" \
92
+ && git diff --cached --stat )
93
+ chk $? "generate"
94
+ wc -l "$SCRATCH/rise_on_mimicgen.patch"; md5sum "$SCRATCH/rise_on_mimicgen.patch"
95
+ echo " files touched: $(grep -c '^+++ ' "$SCRATCH/rise_on_mimicgen.patch")"
96
+ echo " insertions: $(grep -c '^+[^+]' "$SCRATCH/rise_on_mimicgen.patch")"
97
+ echo " deletions: $(grep -c '^-[^-]' "$SCRATCH/rise_on_mimicgen.patch")"
98
+
99
+ hdr "5 the patch reapplies to a pristine clone and reproduces post/ exactly"
100
+ ( cd "$SCRATCH/verify" \
101
+ && git apply --check "$SCRATCH/rise_on_mimicgen.patch" && echo "git apply --check OK" \
102
+ && git apply "$SCRATCH/rise_on_mimicgen.patch" && echo "git apply OK" )
103
+ chk $? "reapply"
104
+ diff -r -q --exclude=.git --exclude=__pycache__ "$SCRATCH/post" "$SCRATCH/verify" && echo "post/ == verify/"
105
+ chk $? "post == verify"
106
+
107
+ hdr "5b the patched clone equals the fork byte for byte on every tracked source file"
108
+ python3 - "$FORK" "$SCRATCH/verify" <<'CMPEOF'
109
+ import filecmp, subprocess, sys
110
+ from pathlib import Path
111
+ fork, got = Path(sys.argv[1]), Path(sys.argv[2])
112
+ tracked = subprocess.run(["git", "-C", str(fork), "ls-files"], capture_output=True, text=True,
113
+ check=True).stdout.split()
114
+ bad, n = [], 0
115
+ for rel in tracked:
116
+ src, tgt = fork / rel, got / rel
117
+ if not src.is_file():
118
+ continue
119
+ n += 1
120
+ if not tgt.is_file():
121
+ bad.append(("MISSING", rel))
122
+ elif not filecmp.cmp(src, tgt, shallow=False):
123
+ bad.append(("DIFFERS", rel))
124
+ print(f"compared {n} tracked files from the fork against the patched clone")
125
+ for kind, rel in bad[:40]:
126
+ print(" ", kind, rel)
127
+ print("VERDICT:", "the patch reconstructs the fork byte for byte" if not bad
128
+ else f"{len(bad)} FILES NOT RECONSTRUCTED")
129
+ sys.exit(1 if bad else 0)
130
+ CMPEOF
131
+ chk $? "patch reconstructs the fork"
132
+
133
+ hdr "6 does the patch leak anything it should not?"
134
+ echo "--- absolute cluster paths (count must be 0) ---"
135
+ grep -c "^+.*\(/proj/dmfexp\|/u/zwhong\|/gpfs\)" "$SCRATCH/rise_on_mimicgen.patch"
136
+ grep -n "^+.*\(/proj/dmfexp\|/u/zwhong\|/gpfs\)" "$SCRATCH/rise_on_mimicgen.patch" | head -10
137
+ echo "--- credentials / keys (count must be 0) ---"
138
+ grep -c -i "^+.*\(api_key\|apikey\|secret\|token\s*=\|password\|wandb_api\)" "$SCRATCH/rise_on_mimicgen.patch"
139
+
140
+ hdr "7 the patch itself, for the record"
141
+ cat "$SCRATCH/rise_on_mimicgen.patch"
142
+
143
+ hdr "done"
144
+ echo "OVERALL rc=$rc_all"
145
+ exit $rc_all
rsm_rise/scripts/real/patchexport_livemark.patch ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/tests/test_rise_stack_rsm_libero_live.py b/tests/test_rise_stack_rsm_libero_live.py
2
+ index 3b367c3..eab0d06 100644
3
+ --- a/tests/test_rise_stack_rsm_libero_live.py
4
+ +++ b/tests/test_rise_stack_rsm_libero_live.py
5
+ @@ -26,6 +26,28 @@ REPO = Path(__file__).resolve().parent.parent
6
+ RSM_DIR = REPO / "rise_stack" / "rsm"
7
+ VENDORED_LIBERO = RSM_DIR / "rsm_libero"
8
+
9
+ +# `rise_stack/rsm/` is the SUBJECT of the vendored guards below, and PR #8 deletes it. On the tree
10
+ +# the six-way merge produces, those guards fail with `ModuleNotFoundError: No module named
11
+ +# 'rise_stack.rsm'` for a tree that is correct (LSF 1908601: seven failures, one cause, read out of
12
+ +# the junit xml). So the subject's presence decides which half of this file runs -- the same
13
+ +# predicate `tests/test_rise_stack_rsm_libero_closure.py` uses, spelled the same way on purpose: one
14
+ +# tree must not be able to satisfy one file's notion of "vendored" and not the other's.
15
+ +#
16
+ +# The skipif is only half the repair. With it alone this file goes from 14 executed tests to 7 on
17
+ +# the tree we ship, and every one of the 7 that remain is about module PROVENANCE -- the claim that a
18
+ +# scorer can actually be constructed, which is the claim that failed on 2026-09-24 (LSF 1905498),
19
+ +# would have nothing executing it post-#8. The other half of the repair is the fork_only test at the
20
+ +# bottom of this file, which runs exactly where these stop.
21
+ +VENDORED_PRESENT = VENDORED_LIBERO.is_dir() and (RSM_DIR / "rsm_scorer.py").is_file()
22
+ +vendored_only = pytest.mark.skipif(
23
+ + not VENDORED_PRESENT,
24
+ + reason="rise_stack/rsm/ is not in this tree (PR #8's shape); the live post-#8 claim is asserted "
25
+ + "by test_without_the_vendored_copy_the_reader_is_sent_to_the_fork instead")
26
+ +fork_only = pytest.mark.skipif(
27
+ + VENDORED_PRESENT,
28
+ + reason="rise_stack/rsm/ is vendored in this tree, so the vendored live guards are the ones that "
29
+ + "apply and they are not skipped")
30
+ +
31
+ # NOT a "path does not contain /proj/dmfexp/zwhong" test. The first version of this file asserted
32
+ # exactly that and three of its cases failed on the cluster for a reason that had nothing to do with
33
+ # the claim: the working checkout of THIS repo is /proj/dmfexp/zwhong/projs/rsm_real, so the literal
34
+ @@ -67,6 +89,7 @@ def _run(code, env_extra=None):
35
+ capture_output=True, text=True, cwd=str(REPO), timeout=600)
36
+
37
+
38
+ +@vendored_only
39
+ @pytest.mark.parametrize("env_extra,want_why", [
40
+ ({}, "vendored"),
41
+ ({"RSM_LIBERO_DIR": ""}, "vendored"),
42
+ @@ -97,6 +120,7 @@ def test_rsm_libero_resolution_under_each_condition(env_extra, want_why):
43
+ f"rsm_libero_source() said {named} but {f} loaded from elsewhere")
44
+
45
+
46
+ +@vendored_only
47
+ def test_rsm_libero_is_the_vendored_copy_when_nothing_is_configured():
48
+ r = _run("""
49
+ from rise_stack.rsm import rsm_scorer as s
50
+ @@ -268,6 +292,7 @@ def test_interpreter_denied_roots_is_empty_outside_a_venv_and_named_inside_one()
51
+ f"call every installed package a leak:\n{r.stdout}")
52
+
53
+
54
+ +@vendored_only
55
+ def test_dependency_report_does_not_call_the_vendored_scorer_missing():
56
+ """LSF 1905498 PROBE C, as a live assertion in a directory this branch keeps.
57
+
58
+ @@ -290,6 +315,7 @@ def test_dependency_report_does_not_call_the_vendored_scorer_missing():
59
+ f"resolves, under RSM_LIBERO_DIR=/nonexistent: {rows}")
60
+
61
+
62
+ +@vendored_only
63
+ def test_which_scorer_reports_where_rsm_libero_came_from():
64
+ r = _run("""
65
+ import json
66
+ @@ -304,3 +330,51 @@ def test_which_scorer_reports_where_rsm_libero_came_from():
67
+ assert _inside_repo(info["rsm_libero_dir"]), (
68
+ f"which_scorer named {info['rsm_libero_dir']}, which is outside this checkout -- that is the "
69
+ "2026-09-24 defect exactly: a scorer reported as vendored whose modules come from elsewhere")
70
+ +
71
+ +
72
+ +# ------------------------------------------------- the same claim on the tree PR #8 produces
73
+ +
74
+ +
75
+ +@fork_only
76
+ +def test_without_the_vendored_copy_the_reader_is_sent_to_the_fork():
77
+ + """The post-#8 half of "an RSM scorer resolves from a clean clone", EXECUTED rather than skipped.
78
+ +
79
+ + Runs `rise_stack.which_scorer` on the tree as it is, with no vendored copy, and accepts either of
80
+ + the two states that are legitimate there:
81
+ +
82
+ + * the patched RISE robomimic IS installed -- then it must be the winner, `vendored` must be
83
+ + False, the command must exit 0, and it must name the rsm_libero it will import from;
84
+ + * it is NOT installed -- then the command must exit 1 AND its hint must send the reader to
85
+ + install the fork (SETUP.md), not tell them the vendored file is present but broken. The
86
+ + wrong hint is the expensive one: it sends someone to re-clone a repository that is fine.
87
+ +
88
+ + Both are real answers on a post-#8 tree, which is why this is one test and not two. It needs
89
+ + neither torch nor robomimic, so it also executes in the hardware-free CI job.
90
+ + """
91
+ + r = _run("""
92
+ + import json
93
+ + from rise_stack import which_scorer
94
+ + info = which_scorer.resolve()
95
+ + rc = which_scorer.main([])
96
+ + print("RC", rc)
97
+ + print("JSON", json.dumps(info))
98
+ + """)
99
+ + assert r.returncode == 0, f"which_scorer itself raised:\n{r.stdout}\n{r.stderr}"
100
+ + info = json.loads([l for l in r.stdout.splitlines() if l.startswith("JSON ")][0][5:])
101
+ + rc = int([l for l in r.stdout.splitlines() if l.startswith("RC ")][0][3:])
102
+ + assert info["vendored"] is False, (
103
+ + f"rise_stack/rsm/ is absent from this tree but which_scorer reports vendored: {info}")
104
+ + if info["module"] is not None:
105
+ + assert info["module"] == "robomimic.algo.rsm_scorer", (
106
+ + f"the only post-#8 implementation is the fork's, but the winner is {info['module']}")
107
+ + assert rc == 0, f"a scorer resolved but the command exited {rc}"
108
+ + assert info["rsm_libero_dir"] and info["rsm_libero_source"] != "unknown", (
109
+ + "the fork resolved without naming where it imports model/train_rsm/is_ope/data from -- "
110
+ + f"that is the 2026-09-24 defect exactly: {info}")
111
+ + else:
112
+ + assert rc == 1, f"no scorer resolved but the command exited {rc}, so a script would not notice"
113
+ + assert "did not import" not in r.stdout, (
114
+ + "no vendored copy exists, yet the hint blames one for failing to import:\n" + r.stdout)
115
+ + assert "robomimic" in r.stdout and "SETUP.md" in r.stdout, (
116
+ + "post-#8 the repair is 'install the patched RISE robomimic (see SETUP.md)' and the "
117
+ + "command does not say so, so the reader is left to guess:\n" + r.stdout)
rsm_rise/scripts/real/patchexport_livemark.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """rsm_real#5 run 32 -- the candidate repair for the seven live guards PR #8's tree makes red.
3
+
4
+ Measured on the six-way merged tree (LSF 1908601, #11 at 2dc85c8b): seven tests in
5
+ `tests/test_rise_stack_rsm_libero_live.py` fail with `ModuleNotFoundError: No module named
6
+ 'rise_stack.rsm'` -- the package PR #8 deletes. They are red for a tree that is CORRECT.
7
+
8
+ #11 already fixed the companion file this way (`VENDORED_PRESENT`, `vendored_only`, `fork_only`), so
9
+ this applies the same predicate here, spelled identically, and -- the half that matters -- adds the
10
+ POSITIVE post-#8 assertion. A plain skipif alone takes the live file from 14 executed to 7 on the
11
+ tree we ship and leaves the claim the file exists for ("constructing an RSM scorer from a clean clone
12
+ works, or the command says exactly what is missing") with no executed guard there.
13
+
14
+ Transformation only: refuses unless every anchor is found exactly once, and is idempotent.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import sys
19
+ from pathlib import Path
20
+
21
+ MARKS = '''
22
+ # `rise_stack/rsm/` is the SUBJECT of the vendored guards below, and PR #8 deletes it. On the tree
23
+ # the six-way merge produces, those guards fail with `ModuleNotFoundError: No module named
24
+ # 'rise_stack.rsm'` for a tree that is correct (LSF 1908601: seven failures, one cause, read out of
25
+ # the junit xml). So the subject's presence decides which half of this file runs -- the same
26
+ # predicate `tests/test_rise_stack_rsm_libero_closure.py` uses, spelled the same way on purpose: one
27
+ # tree must not be able to satisfy one file's notion of "vendored" and not the other's.
28
+ #
29
+ # The skipif is only half the repair. With it alone this file goes from 14 executed tests to 7 on
30
+ # the tree we ship, and every one of the 7 that remain is about module PROVENANCE -- the claim that a
31
+ # scorer can actually be constructed, which is the claim that failed on 2026-09-24 (LSF 1905498),
32
+ # would have nothing executing it post-#8. The other half of the repair is the fork_only test at the
33
+ # bottom of this file, which runs exactly where these stop.
34
+ VENDORED_PRESENT = VENDORED_LIBERO.is_dir() and (RSM_DIR / "rsm_scorer.py").is_file()
35
+ vendored_only = pytest.mark.skipif(
36
+ not VENDORED_PRESENT,
37
+ reason="rise_stack/rsm/ is not in this tree (PR #8's shape); the live post-#8 claim is asserted "
38
+ "by test_without_the_vendored_copy_the_reader_is_sent_to_the_fork instead")
39
+ fork_only = pytest.mark.skipif(
40
+ VENDORED_PRESENT,
41
+ reason="rise_stack/rsm/ is vendored in this tree, so the vendored live guards are the ones that "
42
+ "apply and they are not skipped")
43
+ '''
44
+
45
+ NEW_TEST = '''
46
+
47
+ # ------------------------------------------------- the same claim on the tree PR #8 produces
48
+
49
+
50
+ @fork_only
51
+ def test_without_the_vendored_copy_the_reader_is_sent_to_the_fork():
52
+ """The post-#8 half of "an RSM scorer resolves from a clean clone", EXECUTED rather than skipped.
53
+
54
+ Runs `rise_stack.which_scorer` on the tree as it is, with no vendored copy, and accepts either of
55
+ the two states that are legitimate there:
56
+
57
+ * the patched RISE robomimic IS installed -- then it must be the winner, `vendored` must be
58
+ False, the command must exit 0, and it must name the rsm_libero it will import from;
59
+ * it is NOT installed -- then the command must exit 1 AND its hint must send the reader to
60
+ install the fork (SETUP.md), not tell them the vendored file is present but broken. The
61
+ wrong hint is the expensive one: it sends someone to re-clone a repository that is fine.
62
+
63
+ Both are real answers on a post-#8 tree, which is why this is one test and not two. It needs
64
+ neither torch nor robomimic, so it also executes in the hardware-free CI job.
65
+ """
66
+ r = _run("""
67
+ import json
68
+ from rise_stack import which_scorer
69
+ info = which_scorer.resolve()
70
+ rc = which_scorer.main([])
71
+ print("RC", rc)
72
+ print("JSON", json.dumps(info))
73
+ """)
74
+ assert r.returncode == 0, f"which_scorer itself raised:\\n{r.stdout}\\n{r.stderr}"
75
+ info = json.loads([l for l in r.stdout.splitlines() if l.startswith("JSON ")][0][5:])
76
+ rc = int([l for l in r.stdout.splitlines() if l.startswith("RC ")][0][3:])
77
+ assert info["vendored"] is False, (
78
+ f"rise_stack/rsm/ is absent from this tree but which_scorer reports vendored: {info}")
79
+ if info["module"] is not None:
80
+ assert info["module"] == "robomimic.algo.rsm_scorer", (
81
+ f"the only post-#8 implementation is the fork's, but the winner is {info['module']}")
82
+ assert rc == 0, f"a scorer resolved but the command exited {rc}"
83
+ assert info["rsm_libero_dir"] and info["rsm_libero_source"] != "unknown", (
84
+ "the fork resolved without naming where it imports model/train_rsm/is_ope/data from -- "
85
+ f"that is the 2026-09-24 defect exactly: {info}")
86
+ else:
87
+ assert rc == 1, f"no scorer resolved but the command exited {rc}, so a script would not notice"
88
+ assert "did not import" not in r.stdout, (
89
+ "no vendored copy exists, yet the hint blames one for failing to import:\\n" + r.stdout)
90
+ assert "robomimic" in r.stdout and "SETUP.md" in r.stdout, (
91
+ "post-#8 the repair is 'install the patched RISE robomimic (see SETUP.md)' and the "
92
+ "command does not say so, so the reader is left to guess:\\n" + r.stdout)
93
+ '''
94
+
95
+ ANCHORS = [
96
+ ("@pytest.mark.parametrize(\"env_extra,want_why\", [", "@vendored_only\n"),
97
+ ("def test_rsm_libero_is_the_vendored_copy_when_nothing_is_configured():", "@vendored_only\n"),
98
+ ("def test_dependency_report_does_not_call_the_vendored_scorer_missing():", "@vendored_only\n"),
99
+ ("def test_which_scorer_reports_where_rsm_libero_came_from():", "@vendored_only\n"),
100
+ ]
101
+
102
+
103
+ def main(argv):
104
+ if len(argv) != 2:
105
+ print("usage: patchexport_livemark.py <tests/test_rise_stack_rsm_libero_live.py>")
106
+ return 2
107
+ p = Path(argv[1])
108
+ text = p.read_text()
109
+ if "VENDORED_PRESENT" in text:
110
+ print(f"ALREADY MARKED: {p} -- nothing to do")
111
+ return 0
112
+
113
+ anchor = 'VENDORED_LIBERO = RSM_DIR / "rsm_libero"\n'
114
+ if text.count(anchor) != 1:
115
+ print(f"REFUSED: {anchor.strip()!r} appears {text.count(anchor)} times, expected 1")
116
+ return 3
117
+ text = text.replace(anchor, anchor + MARKS, 1)
118
+
119
+ for target, deco in ANCHORS:
120
+ if text.count(target) != 1:
121
+ print(f"REFUSED: anchor {target!r} appears {text.count(target)} times, expected 1")
122
+ return 3
123
+ text = text.replace(target, deco + target, 1)
124
+
125
+ text = text.rstrip("\n") + "\n" + NEW_TEST
126
+ p.write_text(text)
127
+ print(f"MARKED {p}: 4 vendored_only sites, 1 new fork_only test")
128
+ return 0
129
+
130
+
131
+ if __name__ == "__main__":
132
+ raise SystemExit(main(sys.argv))
rsm_rise/scripts/real/patchexport_livemark.sh ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # rsm_real#5 run 32 -- TEST the candidate repair for the seven live guards before offering it to #11.
3
+ #
4
+ # The measured problem (LSF 1908601, #11 at 2dc85c8b): on the six-way merged tree, seven tests in
5
+ # tests/test_rise_stack_rsm_libero_live.py fail with ModuleNotFoundError: No module named
6
+ # 'rise_stack.rsm' -- the package PR #8 deletes. Red for a tree that is correct.
7
+ #
8
+ # The repair is NOT just a skipif. A skipif alone takes that file from 14 executed tests to 7 on the
9
+ # tree we ship, and the claim it exists for -- a scorer resolves from a clean clone, or the command
10
+ # says exactly what is missing -- would have nothing executing it there. So: mark the seven, AND add
11
+ # one live fork_only test that runs exactly where they stop.
12
+ #
13
+ # Acceptance, all of which must hold before this is offered:
14
+ # A no collected id is skipped on BOTH legitimate trees (nothing goes dark)
15
+ # B each guard file still executes something on the merged tree
16
+ # C the merged tree has 0 failures (7 -> 0, the point of the exercise)
17
+ # H the NEW fork_only test is 'passed' on the merged tree and 'skipped' on #11's own tree
18
+ # Controls, every one of which must FIRE (a check that cannot go red proves nothing):
19
+ # D a half-deleted rise_stack/rsm/ is still RED, not skipped -- my marks must not weaken #11's guard
20
+ # I a which_scorer whose post-#8 hint says nothing -> the new test must FAIL
21
+ # J a which_scorer that claims 'vendored' with no vendored copy -> the new test must FAIL
22
+ # K the skipif-ONLY repair (new test deleted) -> check H must REFUSE
23
+ #
24
+ # Read-only w.r.t. GitHub: fetches, pushes nothing, writes only under SCRATCH.
25
+ set -uo pipefail
26
+ source /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_resolve.sh
27
+ SCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run101}
28
+ VENV=${VENV:-/proj/dmfexp/zwhong/scratch_patchexport/run29/venv_ci}
29
+ MARKER=/proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_livemark.py
30
+ export GIT_TERMINAL_PROMPT=0 PYTHONDONTWRITEBYTECODE=1 OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1
31
+ FILES="tests/test_rise_stack_rsm_libero_closure.py tests/test_rise_stack_rsm_libero_live.py"
32
+ NEW=test_without_the_vendored_copy_the_reader_is_sent_to_the_fork
33
+ scrub(){ sed 's#https://[^@]*@#https://<redacted>@#g'; }
34
+ hdr(){ echo; echo "=================== $* ==================="; date -u; }
35
+ die(){ echo "LIVEMARK FAILED: $*"; exit 7; }
36
+ PY=$VENV/bin/python; [ -x "$PY" ] || die "no venv at $VENV"
37
+ export PE_PY=$PY
38
+ mkdir -p "${SCRATCH:?}" || exit 1
39
+
40
+ hdr "0 context"
41
+ echo "host=$(hostname) job=${LSB_JOBID:-none} scratch=$SCRATCH py=$("$PY" -V 2>&1)"
42
+
43
+ clone(){
44
+ local W=$1 TOK
45
+ TOK=$(grep -m1 'https://richardrl:' ~/.git-credentials | sed -E 's|https://richardrl:([^@]*)@.*|\1|')
46
+ [ -n "$TOK" ] || die "no token"
47
+ rm -rf "${W:?}"; git init --quiet "$W" || exit 1
48
+ 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"
49
+ unset TOK
50
+ git -C "$W" fetch --quiet origin 2>&1 | scrub || die "fetch failed"
51
+ git -C "$W" config user.email noreply@anthropic.com
52
+ git -C "$W" config user.name "richardrl"
53
+ }
54
+
55
+ census(){
56
+ local T=$1 TAG=$2 f present=""
57
+ for f in $FILES; do [ -e "$T/$f" ] && present="$present $f"; done
58
+ [ -n "${present// }" ] || die "$TAG: no guard file in this tree"
59
+ ( cd "$T" && PYTHONPATH= "$PY" -m pytest -q -p no:cacheprovider --tb=no \
60
+ --junitxml="$SCRATCH/$TAG.xml" $present >"$SCRATCH/$TAG.log" 2>&1 )
61
+ "$PY" - "$SCRATCH/$TAG.xml" "$SCRATCH/$TAG.tsv" <<'PYX'
62
+ import sys, xml.etree.ElementTree as ET
63
+ xml, out = sys.argv[1], sys.argv[2]
64
+ rows = []
65
+ for tc in ET.parse(xml).getroot().iter("testcase"):
66
+ kids = {k.tag for k in tc}
67
+ o = ("skipped" if "skipped" in kids else "failed" if "failure" in kids
68
+ else "error" if "error" in kids else "passed")
69
+ rows.append(("%s::%s" % (tc.get("classname"), tc.get("name")), o))
70
+ assert rows, "junit xml has zero testcases -- the run collected nothing"
71
+ open(out, "w").write("".join("%s\t%s\n" % r for r in rows))
72
+ print(" collected %d: %s" % (len(rows), " ".join(
73
+ "%s=%d" % (o, sum(1 for _, x in rows if x == o)) for o in ("passed","failed","error","skipped"))))
74
+ PYX
75
+ [ -s "$SCRATCH/$TAG.tsv" ] || die "$TAG: census produced no rows (see $SCRATCH/$TAG.log)"
76
+ }
77
+ outcome(){ awk -F'\t' -v g="::$2\$" '$1 ~ g {print $2}' "$SCRATCH/$1.tsv" | head -1; }
78
+
79
+ hdr "1 live heads"
80
+ W=$SCRATCH/merged
81
+ clone "$W"
82
+ MAIN=$(git -C "$W" rev-parse origin/main)
83
+ echo " main = ${MAIN:0:8} $(git -C "$W" log -1 --format='%ad %an | %s' --date=iso origin/main)"
84
+ SC_HEAD=$(git -C "$W" ls-remote origin refs/pull/11/head | awk '{print $1}')
85
+ echo " #11 = ${SC_HEAD:0:8}"
86
+
87
+ hdr "2 the six-way trial merge (shared pe_trial_merge)"
88
+ pe_trial_merge "$W" origin/main || die "trial merge refused/failed"
89
+ printf '%s' "$PE_TRIAL_SHAPE" | sed 's/^/ /'
90
+ [ -d "$W/rise_stack/rsm" ] && die "the merged tree still has rise_stack/rsm/ -- #8 must delete it"
91
+ echo " merged = $(git -C "$W" rev-parse --short HEAD), no rise_stack/rsm/"
92
+
93
+ hdr "3 venv sync"
94
+ pe_ci_venv_sync "$W" || die "venv sync failed"
95
+
96
+ hdr "4 #11 alone, and the patch generated ON #11's own file"
97
+ V=$SCRATCH/pr11; rm -rf "${V:?}"
98
+ git -C "$W" worktree add --quiet --detach "$V" pr-11 2>&1 | scrub || die "cannot check out pr-11"
99
+ [ -d "$V/rise_stack/rsm" ] || die "#11 alone has no rise_stack/rsm/ -- the two trees are not distinct"
100
+ cmp -s "$V/tests/test_rise_stack_rsm_libero_live.py" "$W/tests/test_rise_stack_rsm_libero_live.py" \
101
+ || die "the live file differs between #11 and the merged tree -- generate the patch against #11 and re-check"
102
+ echo " the live file is byte-identical on both trees, so one patch serves both"
103
+ "$PY" "$MARKER" "$V/tests/test_rise_stack_rsm_libero_live.py" | sed 's/^/ /' || die "marker refused"
104
+ ( cd "$V" && git diff -- tests/test_rise_stack_rsm_libero_live.py ) > "$SCRATCH/live_marks.patch"
105
+ [ -s "$SCRATCH/live_marks.patch" ] || die "the marker produced an empty diff"
106
+ echo " patch: $(grep -c '^+' "$SCRATCH/live_marks.patch") added lines, $(grep -c '^-' "$SCRATCH/live_marks.patch") removed"
107
+ ( cd "$W" && git apply --check "$SCRATCH/live_marks.patch" ) || die "the patch does not apply to the merged tree"
108
+ ( cd "$W" && git apply "$SCRATCH/live_marks.patch" ) || die "git apply failed on the merged tree"
109
+ echo " applied to the merged tree too"
110
+
111
+ hdr "5 which_scorer on the merged tree, so the mutants target the branch that actually runs"
112
+ ( cd "$W" && PYTHONPATH="$W" "$PY" -m rise_stack.which_scorer ) > "$SCRATCH/whichscorer.txt" 2>&1
113
+ WS_RC=$?
114
+ echo " rc=$WS_RC"; sed 's/^/ /' "$SCRATCH/whichscorer.txt"
115
+ [ "$WS_RC" = 1 ] || die "the fork imports in this venv (rc=$WS_RC): controls I/J below target the \
116
+ no-winner branch, so refusing rather than reporting mutants that were never exercised"
117
+
118
+ hdr "6 census on both trees, WITH the patch"
119
+ echo " merged:"; census "$W" merged
120
+ echo " pr-11 :"; census "$V" pr11
121
+
122
+ hdr "7 check A -- no test skipped on BOTH trees"
123
+ "$PY" - "$SCRATCH/merged.tsv" "$SCRATCH/pr11.tsv" <<'PYX' || die "check A: a guard asserts nothing on either tree"
124
+ import sys
125
+ def rd(p): return dict(l.rstrip("\n").split("\t") for l in open(p))
126
+ m, v = rd(sys.argv[1]), rd(sys.argv[2])
127
+ ids = sorted(set(m) | set(v))
128
+ dead = [i for i in ids if m.get(i,"skipped")=="skipped" and v.get(i,"skipped")=="skipped"]
129
+ only_m = [i for i in ids if m.get(i,"skipped")!="skipped" and v.get(i,"skipped")=="skipped"]
130
+ only_v = [i for i in ids if v.get(i,"skipped")!="skipped" and m.get(i,"skipped")=="skipped"]
131
+ print(" %d distinct ids; merged runs %d, pr-11 runs %d" % (len(ids),
132
+ sum(1 for i in ids if m.get(i,"skipped")!="skipped"), sum(1 for i in ids if v.get(i,"skipped")!="skipped")))
133
+ print(" fork_only half (merged only): %d" % len(only_m))
134
+ for i in only_m: print(" ", i)
135
+ print(" vendored_only half (pr-11 only): %d" % len(only_v))
136
+ for i in only_v: print(" ", i)
137
+ if dead:
138
+ print(" SKIPPED ON BOTH:"); [print(" ", i) for i in dead]
139
+ sys.exit(1 if dead else 0)
140
+ PYX
141
+ echo " OK A"
142
+
143
+ hdr "8 check B -- each guard file executes something on the merged tree"
144
+ for f in $FILES; do
145
+ pat=$(echo "${f%.py}" | tr / .)
146
+ tot=$(awk -F'\t' -v p="$pat::" 'index($1,p)==1' "$SCRATCH/merged.tsv" | wc -l)
147
+ [ "$tot" -gt 0 ] || die "check B: no census rows for $f -- NOT COLLECTED, which is not 'skipped'"
148
+ n=$(awk -F'\t' -v p="$pat::" 'index($1,p)==1 && $2 != "skipped"' "$SCRATCH/merged.tsv" | wc -l)
149
+ [ "$n" -gt 0 ] || die "check B: $f is collected ($tot) but WHOLLY SKIPPED on the merged tree"
150
+ echo " OK B $f: $tot collected, $n executed on the merged tree"
151
+ done
152
+
153
+ hdr "9 check C -- the merged tree has 0 failures"
154
+ bad=$(awk -F'\t' '$2 != "passed" && $2 != "skipped"' "$SCRATCH/merged.tsv")
155
+ [ -z "$bad" ] || { echo "$bad" | sed 's/^/ /'; die "check C: the merged tree still fails $(echo "$bad"|wc -l) test(s)"; }
156
+ 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"
157
+ 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"
158
+
159
+ hdr "10 check H -- the new fork_only test runs where the seven stop"
160
+ om=$(outcome merged "$NEW"); ov=$(outcome pr11 "$NEW")
161
+ [ "$om" = passed ] || die "check H: the new test is '$om' on the merged tree, not passed"
162
+ [ "$ov" = skipped ] || die "check H: the new test is '$ov' on #11's tree, not skipped"
163
+ echo " OK H $NEW: merged=passed, pr-11=skipped"
164
+ for t in test_rsm_libero_is_the_vendored_copy_when_nothing_is_configured test_which_scorer_reports_where_rsm_libero_came_from; do
165
+ echo " $t: merged=$(outcome merged $t), pr-11=$(outcome pr11 $t)"
166
+ done
167
+
168
+ hdr "11 control D -- a HALF-DELETED rise_stack/rsm/ is still RED"
169
+ H=$SCRATCH/half; rm -rf "${H:?}"; cp -a "$V" "$H"; rm -rf "$H/.git"
170
+ [ -f "$H/rise_stack/rsm/rsm_scorer.py" ] || die "control D: nothing to half-delete"
171
+ rm -f "$H/rise_stack/rsm/rsm_scorer.py"
172
+ census "$H" half >/dev/null
173
+ o=$(outcome half test_a_half_deleted_vendored_copy_is_red_rather_than_skipped)
174
+ [ "$o" = failed ] || die "control D: half-deleted tree reported '$o', not failed -- my marks weakened #11's guard"
175
+ echo " OK D the half-deleted tree is red ($(awk -F'\t' '$2=="skipped"' "$SCRATCH/half.tsv"|wc -l) siblings skip there)"
176
+
177
+ mutate(){ # mutate <tag> <python-edit>
178
+ local TAG=$1 EDIT=$2 M=$SCRATCH/$1
179
+ rm -rf "${M:?}"; cp -a "$W" "$M"; rm -rf "$M/.git"
180
+ "$PY" - "$M/rise_stack/which_scorer.py" "$EDIT" <<'PYX' || die "$TAG: the mutation did not apply"
181
+ import sys
182
+ p, edit = sys.argv[1], sys.argv[2]
183
+ src = open(p).read()
184
+ old, new = edit.split("||")
185
+ assert src.count(old) == 1, "mutation anchor %r appears %d times" % (old, src.count(old))
186
+ open(p, "w").write(src.replace(old, new, 1))
187
+ print(" mutated: %r -> %r" % (old[:60], new[:60]))
188
+ PYX
189
+ census "$M" "$TAG" >/dev/null
190
+ }
191
+
192
+ hdr "12 control I -- a post-#8 hint that says nothing must make the new test FAIL"
193
+ mutate mut_hint 'if not vendored_file.exists():||if False:'
194
+ o=$(outcome mut_hint "$NEW")
195
+ [ "$o" = failed ] || die "control I: with the post-#8 hint removed the new test reported '$o' -- it does not guard the hint"
196
+ echo " OK I hint removed -> $NEW failed"
197
+ grep -m1 -A2 "$NEW" "$SCRATCH/mut_hint.log" | sed 's/^/ /' | head -3
198
+
199
+ hdr "13 control J -- 'vendored' claimed with no vendored copy must make the new test FAIL"
200
+ mutate mut_vend '"module": None, "file": None, "vendored": False,||"module": None, "file": None, "vendored": True,'
201
+ o=$(outcome mut_vend "$NEW")
202
+ [ "$o" = failed ] || die "control J: a false 'vendored: True' reported '$o' -- the new test does not guard it"
203
+ echo " OK J false vendored -> $NEW failed"
204
+
205
+ hdr "14 control K -- the skipif-ONLY repair must make check H refuse"
206
+ K=$SCRATCH/skiponly; rm -rf "${K:?}"; cp -a "$W" "$K"; rm -rf "$K/.git"
207
+ "$PY" - "$K/tests/test_rise_stack_rsm_libero_live.py" <<'PYX' || die "control K: could not strip the new test"
208
+ import sys
209
+ p = sys.argv[1]; src = open(p).read()
210
+ i = src.index("@fork_only\ndef test_without_the_vendored_copy")
211
+ open(p, "w").write(src[:i])
212
+ print(" stripped the fork_only test, leaving the skipif-only repair")
213
+ PYX
214
+ census "$K" skiponly >/dev/null
215
+ o=$(outcome skiponly "$NEW")
216
+ [ -z "$o" ] || die "control K: the new test is still present ('$o') after stripping it"
217
+ liveex=$(awk -F'\t' -v p="tests.test_rise_stack_rsm_libero_live::" 'index($1,p)==1 && $2!="skipped"' "$SCRATCH/skiponly.tsv" | wc -l)
218
+ liveall=$(awk -F'\t' -v p="tests.test_rise_stack_rsm_libero_live::" 'index($1,p)==1' "$SCRATCH/skiponly.tsv" | wc -l)
219
+ echo " OK K skipif-only: check H finds no '$NEW' row, and the live file drops to $liveex executed of $liveall"
220
+ 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))"
221
+
222
+ hdr "15 re-poll and keep the patch"
223
+ git -C "$W" fetch --quiet origin 2>&1 | scrub
224
+ echo " main now = $(git -C "$W" rev-parse --short origin/main) (was ${MAIN:0:7})"
225
+ echo " #11 now = $(git -C "$W" ls-remote origin refs/pull/11/head | cut -c1-8) (was ${SC_HEAD:0:8})"
226
+ cp "$SCRATCH/live_marks.patch" /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_livemark.patch
227
+ echo " patch kept at scripts/real/patchexport_livemark.patch"
228
+ git -C "$W" worktree remove --force "$V" >/dev/null 2>&1 || true
229
+
230
+ hdr "LIVEMARK OK -- A/B/C/H pass, controls D/I/J/K all fired"
rsm_rise/scripts/real/patchexport_livemark_ci.sh ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # rsm_real#5 run 32 -- the BEFORE/AFTER pair for the live-guard repair, measured with the CI differ
3
+ # (`pe_ci_baseline`) rather than the two-file census, so the claim "the merged tree adds no failure"
4
+ # is made against the whole set the merged workflow actually runs.
5
+ #
6
+ # Same tree, twice: once as it is (expect the seven), once with scripts/real/patchexport_livemark.patch
7
+ # applied (expect none). Both numbers in one log at one pair of heads, because a before taken at a
8
+ # different head is not a before.
9
+ set -uo pipefail
10
+ source /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_resolve.sh
11
+ SCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run102}
12
+ VENV=${VENV:-/proj/dmfexp/zwhong/scratch_patchexport/run29/venv_ci}
13
+ PATCH=/proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_livemark.patch
14
+ export GIT_TERMINAL_PROMPT=0 PYTHONDONTWRITEBYTECODE=1 OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1
15
+ scrub(){ sed 's#https://[^@]*@#https://<redacted>@#g'; }
16
+ hdr(){ echo; echo "=================== $* ==================="; date -u; }
17
+ die(){ echo "LIVEMARK-CI FAILED: $*"; exit 7; }
18
+ PY=$VENV/bin/python; [ -x "$PY" ] || die "no venv at $VENV"
19
+ export PE_PY=$PY
20
+ [ -s "$PATCH" ] || die "no patch at $PATCH"
21
+ mkdir -p "${SCRATCH:?}" || exit 1
22
+
23
+ hdr "0 context"
24
+ echo "host=$(hostname) job=${LSB_JOBID:-none} scratch=$SCRATCH py=$("$PY" -V 2>&1)"
25
+
26
+ clone(){
27
+ local W=$1 TOK
28
+ TOK=$(grep -m1 'https://richardrl:' ~/.git-credentials | sed -E 's|https://richardrl:([^@]*)@.*|\1|')
29
+ [ -n "$TOK" ] || die "no token"
30
+ rm -rf "${W:?}"; git init --quiet "$W" || exit 1
31
+ 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"
32
+ unset TOK
33
+ git -C "$W" fetch --quiet origin 2>&1 | scrub || die "fetch failed"
34
+ git -C "$W" config user.email noreply@anthropic.com
35
+ git -C "$W" config user.name "richardrl"
36
+ }
37
+
38
+ hdr "1 heads and the six-way merge"
39
+ W=$SCRATCH/merged; clone "$W"
40
+ MAIN=$(git -C "$W" rev-parse origin/main)
41
+ SC=$(git -C "$W" ls-remote origin refs/pull/11/head | awk '{print $1}')
42
+ echo " main = ${MAIN:0:8} #11 = ${SC:0:8}"
43
+ pe_trial_merge "$W" origin/main || die "trial merge refused"
44
+ printf '%s' "$PE_TRIAL_SHAPE" | sed 's/^/ /'
45
+ [ -d "$W/rise_stack/rsm" ] && die "merged tree still has rise_stack/rsm/"
46
+ MW=$SCRATCH/mainonly; rm -rf "${MW:?}"
47
+ git -C "$W" worktree add --quiet --detach "$MW" origin/main 2>&1 | scrub || die "cannot check out main"
48
+ pe_ci_venv_sync "$W" || die "venv sync failed"
49
+
50
+ hdr "2 BEFORE -- the merged tree as it is"
51
+ BEFORE_RC=0
52
+ pe_ci_baseline "$W" "$MW" || BEFORE_RC=1
53
+ BEFORE_NEW=$PE_CI_NEW
54
+ echo " before: rc=$BEFORE_RC, $(printf '%s\n' "$BEFORE_NEW" | sed '/^$/d' | wc -l) NEW failure(s)"
55
+ [ "$BEFORE_RC" = 1 ] || die "the BEFORE run is already green -- the subject of this repair is gone; re-read the heads"
56
+ printf '%s\n' "$BEFORE_NEW" | sed '/^$/d' | grep -qv "test_rise_stack_rsm_libero_live" \
57
+ && die "the BEFORE failures are not all in the live guard file, so this patch is not the whole repair"
58
+ echo " OK every BEFORE failure is in tests/test_rise_stack_rsm_libero_live.py"
59
+
60
+ hdr "3 apply the patch"
61
+ ( cd "$W" && git apply "$PATCH" ) || die "the patch does not apply to the merged tree"
62
+ git -C "$W" diff --stat -- tests/test_rise_stack_rsm_libero_live.py | sed 's/^/ /'
63
+
64
+ hdr "4 AFTER -- the same tree, the same CI set, the same baseline"
65
+ AFTER_RC=0
66
+ pe_ci_baseline "$W" "$MW" || AFTER_RC=1
67
+ [ "$AFTER_RC" = 0 ] || { printf '%s\n' "$PE_CI_NEW" | sed 's/^/ /'; die "the patched tree STILL adds failures"; }
68
+
69
+ hdr "5 the pair"
70
+ echo " BEFORE: $(printf '%s\n' "$BEFORE_NEW" | sed '/^$/d' | wc -l) new failures over main"
71
+ printf '%s\n' "$BEFORE_NEW" | sed '/^$/d' | sed 's/^/ /'
72
+ echo " AFTER : 0 new failures over main (merged run: $PE_CI_TAIL)"
73
+ git -C "$W" worktree remove --force "$MW" >/dev/null 2>&1 || true
74
+ hdr "LIVEMARK-CI OK"
rsm_rise/scripts/real/patchexport_merge_gate.sh ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # rsm_real#5 -- gate the MERGE RESULT, not just the branches.
3
+ #
4
+ # Five PRs (#6 -> #7 -> #8 -> #9 -> #10) are open against main and each one was validated on its own
5
+ # branch. Nobody has yet executed the thing the owner will actually do: merge them, in order, into
6
+ # main, and build from the result. GitHub says "mergeable: clean" for each, but that is computed
7
+ # against main as it stands TODAY and pairwise -- it is not a statement that the five together build
8
+ # an environment. This script executes the whole sequence and then runs the full setup gate on the
9
+ # merged tree.
10
+ #
11
+ # It also test-merges the SELFCONTAINED stream's `rise-stack-scaffold`, which edits
12
+ # scripts/check_env.py as my branches do, so the reconciliation warning I posted to #4 is backed by
13
+ # an executed merge rather than by reading both diffs.
14
+ #
15
+ # Credentials: `credential.helper=store` does NOT authenticate this repo (measured -- a plain
16
+ # `git ls-remote https://github.com/jmarangola/rsm_real.git` returns "Repository not found" both on
17
+ # the login node and on a compute node, with and without an explicit --file, while the token in
18
+ # ~/.git-credentials is byte-identical to the one the working checkouts embed in their remote URL).
19
+ # So the remote is written into .git/config with a shell redirect rather than passed as an argument:
20
+ # the token then never appears in argv (visible in `ps` on a shared node), never in this file, and
21
+ # every git line printed is scrubbed on top of that.
22
+ set -uo pipefail
23
+ ROOT=/proj/dmfexp/zwhong/rsm_rise
24
+ SCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run13}
25
+ PRS=${PRS:-"6 7 8 9 10"}
26
+ export GIT_TERMINAL_PROMPT=0
27
+ scrub(){ sed 's#https://[^@]*@#https://<redacted>@#g'; }
28
+ hdr(){ echo; echo "=================== $* ==================="; date -u; }
29
+ rc_all=0
30
+ chk(){ if [ "$1" -ne 0 ]; then echo "STEP FAILED rc=$1: $2"; rc_all=1; fi; }
31
+ mkdir -p "${SCRATCH:?}" || exit 1
32
+ MERGED=$SCRATCH/merged
33
+
34
+ hdr "0 context"
35
+ echo "host=$(hostname) job=${LSB_JOBID:-none} scratch=$SCRATCH prs='$PRS'"
36
+ df -h "$SCRATCH" | tail -1
37
+
38
+ hdr "1 fresh clone of main from GitHub"
39
+ TOK=$(grep -m1 'https://richardrl:' ~/.git-credentials | sed -E 's|https://richardrl:([^@]*)@.*|\1|')
40
+ [ -n "$TOK" ] || { echo "NO TOKEN in ~/.git-credentials"; exit 1; }
41
+ rm -rf "${MERGED:?}"
42
+ git init --quiet "$MERGED" || exit 1
43
+ printf '[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"
44
+ unset TOK
45
+ git -C "$MERGED" fetch --quiet origin main 2>&1 | scrub
46
+ git -C "$MERGED" checkout --quiet -b main FETCH_HEAD 2>&1 | scrub
47
+ [ -f "$MERGED/README.md" ] || { echo "CLONE/FETCH FAILED -- no worktree"; exit 1; }
48
+ BASE=$(git -C "$MERGED" rev-parse HEAD)
49
+ echo "main = $BASE $(git -C "$MERGED" log -1 --pretty=%s)"
50
+ git -C "$MERGED" config user.email "noreply@anthropic.com"
51
+ git -C "$MERGED" config user.name "merge gate"
52
+
53
+ hdr "2 merge each PR head, in the stated order"
54
+ # A conflict here is the finding: report which files, abort that one merge, and keep the sequence
55
+ # honest by stopping rather than merging the rest onto a half-resolved tree.
56
+ MERGED_OK=""
57
+ for n in $PRS; do
58
+ git -C "$MERGED" fetch --quiet origin "pull/$n/head:pr-$n" 2>&1 | scrub
59
+ sha=$(git -C "$MERGED" rev-parse --short "pr-$n" 2>/dev/null)
60
+ if [ -z "$sha" ]; then echo " #$n FETCH FAILED"; rc_all=1; break; fi
61
+ out=$(git -C "$MERGED" merge --no-ff --no-edit -m "merge PR #$n" "pr-$n" 2>&1)
62
+ if [ $? -eq 0 ]; then
63
+ echo " #$n $sha MERGED CLEAN ($(echo "$out" | tail -1))"
64
+ MERGED_OK="$MERGED_OK $n"
65
+ else
66
+ echo " #$n $sha CONFLICT:"
67
+ git -C "$MERGED" diff --name-only --diff-filter=U | sed 's/^/ /'
68
+ git -C "$MERGED" merge --abort
69
+ rc_all=1
70
+ echo " stopping the sequence here; the remaining PRs are not merged onto a conflicted tree"
71
+ break
72
+ fi
73
+ done
74
+ echo "merged in order:$MERGED_OK"
75
+ echo "result HEAD = $(git -C "$MERGED" rev-parse --short HEAD)"
76
+ echo "--- merged tree vs main ---"
77
+ git -C "$MERGED" diff --stat "$BASE" HEAD | tail -3
78
+
79
+ hdr "3 is the merged tree the same content as PR #10 alone?"
80
+ # #10's branch was built on a merge of #6/#7/#8, so if the five-way merge lands on the same tree,
81
+ # then merge ORDER cannot lose content and the owner has one less thing to get right.
82
+ if git -C "$MERGED" rev-parse pr-10 >/dev/null 2>&1; then
83
+ d=$(git -C "$MERGED" diff --name-only pr-10 HEAD)
84
+ if [ -z "$d" ]; then
85
+ echo "IDENTICAL: merged(#6..#10) tree == PR #10 head tree -- no content depends on merge order"
86
+ else
87
+ echo "DIFFERENT -- files only reachable via the other PRs (expected: #9's mimicgen export):"
88
+ echo "$d" | sed 's/^/ /'
89
+ fi
90
+ fi
91
+
92
+ hdr "4 test-merge the SELFCONTAINED branch (rise-stack-scaffold) onto the result"
93
+ # Reported to #4 as a reading of two diffs; here it is executed. Done on a throwaway branch and
94
+ # always aborted, so the tree that gets built below is the five-PR merge and nothing else.
95
+ git -C "$MERGED" fetch --quiet origin rise-stack-scaffold 2>&1 | scrub
96
+ if git -C "$MERGED" rev-parse origin/rise-stack-scaffold >/dev/null 2>&1; then
97
+ echo "rise-stack-scaffold = $(git -C "$MERGED" rev-parse --short origin/rise-stack-scaffold)"
98
+ git -C "$MERGED" checkout --quiet -b _recon_probe
99
+ if git -C "$MERGED" merge --no-commit --no-ff origin/rise-stack-scaffold >/dev/null 2>&1; then
100
+ echo "RECONCILIATION: merges clean by git's own rules (textually disjoint edits)."
101
+ echo " NOTE this is NOT a semantic all-clear: a clean textual merge of two edits to"
102
+ echo " scripts/check_env.py can still drop neither and still be wrong only if one side"
103
+ echo " reverted the other, which it does not here -- both sides' hunks are present below."
104
+ else
105
+ echo "RECONCILIATION: CONFLICT, files:"
106
+ git -C "$MERGED" diff --name-only --diff-filter=U | sed 's/^/ /'
107
+ fi
108
+ echo "--- does the merged check_env.py keep BOTH sides? ---"
109
+ if [ -f "$MERGED/scripts/check_env.py" ]; then
110
+ echo -n " pin_of fix (mine, 'commit =' parse): "; grep -c "^commit\|commit = \|--print-pin" "$MERGED/scripts/check_env.py"
111
+ echo -n " CPU-threads INFO row (theirs): "; grep -ci "cpu.*thread" "$MERGED/scripts/check_env.py"
112
+ fi
113
+ git -C "$MERGED" merge --abort 2>/dev/null
114
+ git -C "$MERGED" checkout --quiet -
115
+ git -C "$MERGED" branch -D _recon_probe >/dev/null 2>&1
116
+ git -C "$MERGED" status --porcelain | head -5
117
+ else
118
+ echo "rise-stack-scaffold not found on the remote -- skipping"
119
+ fi
120
+
121
+ hdr "5 the pin regression test must pass on the MERGED scripts, before spending a build on them"
122
+ if [ -f "$MERGED/tests/test_rise_stack_pins.py" ]; then
123
+ for f in "$MERGED"/rise_stack/*/UPSTREAM_COMMIT.txt; do
124
+ echo -n " $(basename "$(dirname "$f")"): "
125
+ bash "$MERGED/scripts/setup_env.sh" --print-pin "$(basename "$(dirname "$f")")" 2>&1 | tail -1
126
+ done
127
+ else
128
+ echo "tests/test_rise_stack_pins.py NOT in the merged tree -- #10 did not merge"; rc_all=1
129
+ fi
130
+
131
+ hdr "6 full setup gate on the merged tree"
132
+ if [ "$rc_all" -eq 0 ]; then
133
+ SCRATCH=$SCRATCH SRC=$MERGED bash "$ROOT/scripts/real/patchexport_setup_run.sh"
134
+ chk $? "patchexport_setup_run.sh on the merged tree"
135
+ else
136
+ echo "SKIPPED: the merge sequence itself failed, so a build result would not mean anything."
137
+ fi
138
+
139
+ hdr "done"
140
+ echo "OVERALL rc=$rc_all"
141
+ exit $rc_all
rsm_rise/scripts/real/patchexport_merge_order_probe.sh ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # rsm_real#5 -- which merge BUTTON the owner presses is not a detail.
3
+ #
4
+ # The repo has all three enabled (measured via the API: allow_merge_commit, allow_squash_merge and
5
+ # allow_rebase_merge are all true). My five PRs are not independent: #8 was branched on top of #7,
6
+ # and #10's branch carries a merge of #6/#7/#8. A merge commit preserves those ancestries, so git
7
+ # knows what is already in; a SQUASH merge rewrites each PR into one new commit with no ancestry
8
+ # link, so the next PR in the stack re-applies content main already has -- which is how a stack of
9
+ # PRs that each say "mergeable: clean" produces a conflict on the second or third button press.
10
+ #
11
+ # This probe presses every button, in a scratch clone, and reports what actually happens. It builds
12
+ # nothing: it is pure git and runs in about a minute. The build gate on the merge-commit path is
13
+ # scripts/real/patchexport_merge_gate.sh.
14
+ #
15
+ # Credentials: see the note in patchexport_merge_gate.sh -- credential.helper=store does not
16
+ # authenticate this repo, so the remote goes into .git/config via a redirect and never into argv.
17
+ set -uo pipefail
18
+ SCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run14}
19
+ PRS=${PRS:-"6 7 8 9 10"}
20
+ export GIT_TERMINAL_PROMPT=0
21
+ scrub(){ sed 's#https://[^@]*@#https://<redacted>@#g'; }
22
+ hdr(){ echo; echo "=================== $* ==================="; }
23
+ # rc_all is reserved for things that are WRONG: the merge-commit path (the one I recommend to the
24
+ # owner) conflicting, or a completed sequence whose tree lacks a deliverable file. A squash conflict
25
+ # is a FINDING about which button to press, not a failure of this job, so it is counted separately.
26
+ FINDINGS=0
27
+ mkdir -p "${SCRATCH:?}" || exit 1
28
+ R=$SCRATCH/probe
29
+ rc_all=0
30
+
31
+ hdr "0 context"
32
+ echo "host=$(hostname) job=${LSB_JOBID:-none} scratch=$SCRATCH prs='$PRS'"
33
+
34
+ hdr "1 clone main + every PR head"
35
+ TOK=$(grep -m1 'https://richardrl:' ~/.git-credentials | sed -E 's|https://richardrl:([^@]*)@.*|\1|')
36
+ [ -n "$TOK" ] || { echo "NO TOKEN"; exit 1; }
37
+ rm -rf "${R:?}"
38
+ git init --quiet "$R" || exit 1
39
+ printf '[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"
40
+ unset TOK
41
+ git -C "$R" config user.email "noreply@anthropic.com"; git -C "$R" config user.name "merge probe"
42
+ git -C "$R" fetch --quiet origin main 2>&1 | scrub
43
+ git -C "$R" checkout --quiet -b main FETCH_HEAD 2>&1 | scrub
44
+ # README.md, not scripts/ -- `main` has NO top-level scripts/ directory (measured: it arrives only
45
+ # with PR #6/#10). Checking for scripts/ here made LSF 1889836 report "FETCH FAILED" on a clone that
46
+ # was complete and correct.
47
+ [ -f "$R/README.md" ] || { echo "FETCH FAILED -- no worktree"; exit 1; }
48
+ echo "main = $(git -C "$R" rev-parse --short HEAD)"
49
+ for n in $PRS; do
50
+ git -C "$R" fetch --quiet origin "pull/$n/head:pr-$n" 2>&1 | scrub
51
+ echo " #$n = $(git -C "$R" rev-parse --short "pr-$n") $(git -C "$R" log -1 --pretty=%s "pr-$n" | cut -c1-60)"
52
+ done
53
+
54
+ # The files a clone must end up with for the deliverable to exist at all. Checked after every
55
+ # scenario, because "merged without conflict" and "the result contains the sources" are different
56
+ # claims and only the second one matters to a labmate.
57
+ WANT="rise_stack/openpi/rise_on_pi05.patch
58
+ rise_stack/robomimic/rise_on_robomimic.patch
59
+ rise_stack/rsm_libero/rise_on_rsm_libero.patch
60
+ rise_stack/mimicgen/rise_on_mimicgen.patch
61
+ rise_stack/UPSTREAM_PINS.md
62
+ scripts/setup_env.sh
63
+ scripts/check_env.py
64
+ tests/test_rise_stack_pins.py
65
+ SETUP.md"
66
+
67
+ report_tree(){ # $1 = mode, $2 = 1 if the sequence completed, $3 = 1 if held to the missing-files bar
68
+ local mode="$1" done_ok="$2" strict="$3" miss=0 f
69
+ while read -r f; do
70
+ [ -z "$f" ] && continue
71
+ if [ ! -f "$R/$f" ]; then echo " MISSING $f"; miss=$((miss+1)); fi
72
+ done <<< "$WANT"
73
+ echo " required deliverable files missing: $miss"
74
+ local d; d=$(git -C "$R" diff --name-only HEAD pr-10 | wc -l)
75
+ echo " files differing from PR #10's tree: $d"
76
+ # Only the full merge-commit sequence, run to completion, is held to the missing-files bar.
77
+ # The single-PR scenarios are EXPECTED to be short: #9 (mimicgen) is not an ancestor of #10, so
78
+ # merging #10 alone must come out without rise_stack/mimicgen. That is the point of running them.
79
+ if [ "$miss" -ne 0 ] && [ "$done_ok" -eq 1 ] && [ "$strict" -eq 1 ]; then rc_all=1; fi
80
+ if [ "$miss" -ne 0 ] && [ "$strict" -ne 1 ]; then FINDINGS=$((FINDINGS+1)); fi
81
+ return 0
82
+ }
83
+
84
+ scenario(){ # $1 = strict, $2 = mode (merge|squash), $3 = branch name, $4.. = pr numbers
85
+ local strict="$1" mode="$2" br="$3"; shift 3
86
+ hdr "scenario: $mode $*"
87
+ git -C "$R" checkout --quiet main
88
+ git -C "$R" branch -D "$br" >/dev/null 2>&1
89
+ git -C "$R" checkout --quiet -b "$br" main
90
+ local n ok=1
91
+ for n in "$@"; do
92
+ if [ "$mode" = squash ]; then
93
+ if git -C "$R" merge --squash "pr-$n" >/dev/null 2>&1; then
94
+ git -C "$R" commit --quiet -m "squash PR #$n" >/dev/null 2>&1
95
+ echo " #$n squash OK"
96
+ else
97
+ echo " #$n SQUASH CONFLICT:"
98
+ git -C "$R" diff --name-only --diff-filter=U | sed 's/^/ /'
99
+ git -C "$R" merge --abort 2>/dev/null; git -C "$R" reset --hard --quiet
100
+ ok=0; FINDINGS=$((FINDINGS+1)); break
101
+ fi
102
+ else
103
+ if git -C "$R" merge --no-ff --no-edit -m "merge PR #$n" "pr-$n" >/dev/null 2>&1; then
104
+ echo " #$n merge OK"
105
+ else
106
+ echo " #$n MERGE CONFLICT:"
107
+ git -C "$R" diff --name-only --diff-filter=U | sed 's/^/ /'
108
+ git -C "$R" merge --abort 2>/dev/null
109
+ ok=0; rc_all=1; break
110
+ fi
111
+ fi
112
+ done
113
+ [ "$ok" -eq 1 ] && echo " all of '$*' applied by $mode" || echo " sequence stopped early"
114
+ report_tree "$mode" "$ok" "$strict"
115
+ }
116
+
117
+ scenario 1 merge s_merge_all $PRS # the recommended path: must be clean AND complete
118
+ scenario 0 squash s_squash_all $PRS # what happens if the owner presses "Squash and merge"
119
+ scenario 0 merge s_merge_10 10 # does #10 alone carry everything? (it must not: #9 is not in it)
120
+ scenario 0 squash s_squash_10 10
121
+
122
+ hdr "done"
123
+ echo "squash/ordering findings: $FINDINGS (these are advice for the owner, not job failures)"
124
+ echo "OVERALL rc=$rc_all"
125
+ exit $rc_all
rsm_rise/scripts/real/patchexport_merged_tests.sh ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # rsm_real#5 -- the question the merge gate does NOT answer: after the resolution I published,
3
+ # does #11's own CI suite still pass?
4
+ #
5
+ # The six-way gate measures the CONFLICT set. Conflicts are not the risk here: the risk is the two
6
+ # resolution steps that are not "take one side of a text conflict" --
7
+ # (a) four conflicted files resolved to the #6..#10 side (SETUP.md, openpi/README.md,
8
+ # scripts/check_env.py, scripts/setup_env.sh), and
9
+ # (b) the scorer decision: delete rise_stack/rsm/ and collapse scorers.py to the single fork
10
+ # import (run 13 measured that the vendored copy wins at runtime and lacks #8's item-3 fix).
11
+ # #11 ships tests/test_rise_stack_which_scorer.py whose subject is exactly the module (b) rewrites,
12
+ # and CI is green on #11's own head. Green on the head says nothing about green after the merge.
13
+ # A resolution that turns a green branch red is a defect in MY runbook, and it would land on a
14
+ # human who followed it. So execute the CI command, verbatim, on both trees.
15
+ #
16
+ # Three cases, chosen so a skip cannot be mistaken for a pass:
17
+ # H0 #11 head, robomimic NOT importable -- reproduces the Actions runner (baseline)
18
+ # R0 RESOLVED tree, robomimic NOT importable -- a clone that has not installed the fork yet
19
+ # R1 RESOLVED tree, patched fork on PYTHONPATH -- the state SETUP.md actually produces
20
+ # Exit 2 (never 0) if the baseline collects nothing, if robomimic leaks into H0/R0, or if the fork
21
+ # reconstruction for R1 is not the file carrying #8's item-3 fix.
22
+ #
23
+ # Read-only w.r.t. every real repo: fetches from GitHub, works only inside SCRATCH, pushes nothing.
24
+ set -uo pipefail
25
+ source /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_resolve.sh
26
+ ROOT=/proj/dmfexp/zwhong/rsm_rise
27
+ SCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run29}
28
+ PRS=${PRS:-"6 7 8 9 10"}
29
+ SC_PR=${SC_PR:-11}
30
+ export GIT_TERMINAL_PROMPT=0 PYTHONDONTWRITEBYTECODE=1 OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1
31
+ scrub(){ sed 's#https://[^@]*@#https://<redacted>@#g'; }
32
+ hdr(){ echo; echo "=================== $* ==================="; date -u; }
33
+ rc_all=0
34
+ mkdir -p "${SCRATCH:?}" || exit 1
35
+ M=$SCRATCH/mt
36
+
37
+ hdr "0 context"
38
+ echo "host=$(hostname) job=${LSB_JOBID:-none} scratch=$SCRATCH"
39
+
40
+ hdr "1 fresh clone of main, fetch every PR head"
41
+ TOK=$(grep -m1 'https://richardrl:' ~/.git-credentials | sed -E 's|https://richardrl:([^@]*)@.*|\1|')
42
+ [ -n "$TOK" ] || { echo "NO TOKEN"; exit 1; }
43
+ rm -rf "${M:?}"; git init --quiet "$M" || exit 1
44
+ printf '[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"
45
+ unset TOK
46
+ git -C "$M" fetch --quiet origin main 2>&1 | scrub
47
+ git -C "$M" checkout --quiet -b main FETCH_HEAD 2>&1 | scrub
48
+ [ -f "$M/README.md" ] || { echo "CLONE/FETCH FAILED"; exit 1; }
49
+ git -C "$M" config user.email noreply@anthropic.com; git -C "$M" config user.name "merged-tests gate"
50
+ for n in $PRS $SC_PR; do
51
+ git -C "$M" fetch --quiet origin "pull/$n/head:pr-$n" 2>&1 | scrub
52
+ echo " #$n = $(git -C "$M" rev-parse --short "pr-$n")"
53
+ done
54
+ echo " main = $(git -C "$M" rev-parse --short main)"
55
+ SC_SHA=$(git -C "$M" rev-parse "pr-$SC_PR")
56
+
57
+ hdr "1b staleness guard -- the side under test must BE the live PR head"
58
+ LIVE=$(git -C "$M" ls-remote origin "refs/pull/$SC_PR/head" 2>/dev/null | awk '{print $1}')
59
+ if [ -z "$LIVE" ] || [ "$LIVE" != "$SC_SHA" ]; then
60
+ echo "STALE: fetched $(echo "$SC_SHA" | cut -c1-7) != live $(echo "${LIVE:-none}" | cut -c1-7)"; exit 2
61
+ fi
62
+ echo "staleness guard: OK -- sc == live head of PR #$SC_PR ($(echo "$SC_SHA" | cut -c1-7))"
63
+
64
+ hdr "2 order A merge, then the FULL published resolution (incl. the scorer decision)"
65
+ 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; }; done
66
+ FIVE=$(git -C "$M" rev-parse HEAD)
67
+ echo "five-way = $(git -C "$M" rev-parse --short HEAD) tree $(git -C "$M" rev-parse --short HEAD^{tree})"
68
+ git -C "$M" merge --no-ff -m "Merge PR #$SC_PR" "pr-$SC_PR" >/dev/null 2>&1
69
+ echo "conflicted: $(git -C "$M" diff --name-only --diff-filter=U | tr '\n' ' ')"
70
+ pe_resolve "$M" "$FIVE" scripts/setup_env.sh SETUP.md rise_stack/openpi/README.md scripts/check_env.py
71
+ LEFT=$(git -C "$M" diff --name-only --diff-filter=U | tr '\n' ' ')
72
+ echo "remaining unmerged after text resolution: '$LEFT'"
73
+ [ -z "$LEFT" ] || { echo "RESOLUTION INCOMPLETE -- refusing to report a test result"; exit 2; }
74
+ python3 - "$M/rise_stack/scorers.py" <<'PY'
75
+ import re, sys
76
+ p = sys.argv[1]
77
+ s = open(p).read()
78
+ 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")
79
+ m = pat.search(s)
80
+ if not m:
81
+ print("RESOLUTION PATCH FAILED: fallback block not found"); sys.exit(3)
82
+ names = m.group(1).strip()
83
+ indent = re.match(r"[ \t]*", m.group(0)).group(0)
84
+ s = s[:m.start()] + f"{indent}from robomimic.algo.rsm_scorer import {names}\n" + s[m.end():]
85
+ open(p, "w").write(s)
86
+ print(f"scorers.py resolved -> single import of robomimic.algo.rsm_scorer ({names})")
87
+ PY
88
+ [ $? -eq 0 ] || { echo "SCORERS RESOLUTION FAILED"; exit 2; }
89
+ git -C "$M" add rise_stack/scorers.py
90
+ git -C "$M" rm -rf -f --quiet rise_stack/rsm || { echo "git rm rise_stack/rsm FAILED"; exit 2; }
91
+ git -C "$M" commit --quiet -m "scratch: order-A merge + published resolution" || echo " (commit skipped)"
92
+ RES=$(git -C "$M" rev-parse HEAD)
93
+ echo "resolved commit = $(git -C "$M" rev-parse --short HEAD) tree $(git -C "$M" rev-parse --short HEAD^{tree})"
94
+
95
+ hdr "3 the CI command, taken from the workflow file in the tree under test (not retyped)"
96
+ CIFILES=$(git -C "$M" cat-file -p "$SC_SHA:.github/workflows/deployment.yml" \
97
+ | sed -n 's#^ *\(tests/test_[a-z_]*\.py\) *$#\1#p' | tr '\n' ' ')
98
+ echo "CI test files ($(echo $CIFILES | wc -w)): $CIFILES"
99
+ [ -n "$CIFILES" ] || { echo "could not extract the CI file list"; exit 2; }
100
+ REQ=$SCRATCH/requirements-deployment.txt
101
+ git -C "$M" cat-file -p "$SC_SHA:requirements-deployment.txt" > "$REQ"
102
+ echo "--- requirements-deployment.txt ---"; grep -v '^#' "$REQ" | sed '/^$/d' | sed 's/^/ /'
103
+
104
+ hdr "4 a venv with the CI dependencies (isolated; robomimic must NOT be in it)"
105
+ VENV=$SCRATCH/venv_ci
106
+ if [ ! -x "$VENV/bin/python" ]; then
107
+ python3 -m venv "$VENV" || { echo "venv creation FAILED"; exit 2; }
108
+ "$VENV/bin/python" -m pip install --quiet --upgrade pip 2>&1 | tail -2
109
+ export PIP_CACHE_DIR=$SCRATCH/pipcache
110
+ "$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; }
111
+ "$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; }
112
+ fi
113
+ PY=$VENV/bin/python
114
+ echo "interpreter: $PY ($("$PY" -V 2>&1)) [CI uses 3.10]"
115
+ "$PY" - <<'PY' || { echo "dependency import FAILED -- inconclusive"; exit 2; }
116
+ import importlib, sys
117
+ for m in ("pytest","yaml","numpy","torch","h5py","cv2","hydra","omegaconf"):
118
+ mod = importlib.import_module(m)
119
+ print(" %-10s %s" % (m, getattr(mod, "__version__", "?")))
120
+ PY
121
+ if "$PY" -c "import robomimic" 2>/dev/null; then
122
+ echo " !! robomimic IS importable in the CI venv -- H0/R0 are NOT conclusive"; rc_all=2
123
+ else
124
+ echo " robomimic is NOT importable here -- H0/R0 reproduce the Actions runner"
125
+ fi
126
+
127
+ hdr "5 worktrees"
128
+ WH=$SCRATCH/t_head; WR=$SCRATCH/t_resolved
129
+ rm -rf "$WH" "$WR"
130
+ git -C "$M" worktree add --quiet --detach "$WH" "$SC_SHA" || { echo "worktree head FAILED"; exit 2; }
131
+ git -C "$M" worktree add --quiet --detach "$WR" "$RES" || { echo "worktree resolved FAILED"; exit 2; }
132
+
133
+ run_case(){ # name dir extra_pythonpath
134
+ local name=$1 dir=$2 pp=${3:-}
135
+ hdr "6.$name dir=$(basename "$dir") PYTHONPATH=${pp:-<empty>}"
136
+ ( cd "$dir" && PYTHONPATH=$pp "$PY" -m pytest -q -p no:cacheprovider $CIFILES 2>&1 ) | tail -40 | sed 's/^/ /'
137
+ }
138
+
139
+ hdr "6 EXECUTIONS -- the CI command verbatim"
140
+ run_case "H0 (#11 head, no robomimic = the Actions runner)" "$WH"
141
+ H0LINE=$( cd "$WH" && PYTHONPATH= "$PY" -m pytest -q -p no:cacheprovider $CIFILES 2>&1 | tail -1 )
142
+ run_case "R0 (RESOLVED tree, no robomimic)" "$WR"
143
+ R0LINE=$( cd "$WR" && PYTHONPATH= "$PY" -m pytest -q -p no:cacheprovider $CIFILES 2>&1 | tail -1 )
144
+
145
+ hdr "7 reconstruct the patched fork the DOCUMENTED way (upstream pin + our patch) for R1"
146
+ RM=$SCRATCH/robomimic_fork
147
+ FORK_OK=0
148
+ UP=$(git -C "$M" cat-file -p "$RES:rise_stack/robomimic/UPSTREAM_COMMIT.txt" | head -1 | tr -d '[:space:]')
149
+ URL=$(git -C "$M" cat-file -p "$RES:rise_stack/robomimic/UPSTREAM_COMMIT.txt" | sed -n '2p' | tr -d '[:space:]')
150
+ echo "pin=$UP url=$URL"
151
+ if [ ! -f "$RM/robomimic/algo/rsm_scorer.py" ]; then
152
+ rm -rf "$RM"; git init --quiet "$RM" && git -C "$RM" remote add origin "$URL"
153
+ git -C "$RM" fetch --quiet --depth 1 origin "$UP" 2>&1 | scrub
154
+ git -C "$RM" checkout --quiet FETCH_HEAD 2>&1 | scrub
155
+ git -C "$M" cat-file -p "$RES:rise_stack/robomimic/rise_on_robomimic.patch" > "$SCRATCH/robomimic.patch"
156
+ echo " patch bytes: $(wc -c < "$SCRATCH/robomimic.patch")"
157
+ git -C "$RM" apply --whitespace=nowarn "$SCRATCH/robomimic.patch" 2>&1 | scrub && echo " patch APPLIED clean"
158
+ fi
159
+ if [ -f "$RM/robomimic/algo/rsm_scorer.py" ] && grep -q '_rsm_libero_dir' "$RM/robomimic/algo/rsm_scorer.py"; then
160
+ echo " reconstruction carries #8's item-3 fix (_rsm_libero_dir) -- right file for R1"; FORK_OK=1
161
+ else
162
+ echo " !! fork reconstruction unusable -- R1 INCONCLUSIVE, not a pass"; rc_all=2
163
+ fi
164
+
165
+ R1LINE="(skipped)"
166
+ if [ "$FORK_OK" = 1 ]; then
167
+ run_case "R1 (RESOLVED tree + patched fork on PYTHONPATH = what SETUP.md produces)" "$WR" "$RM"
168
+ R1LINE=$( cd "$WR" && PYTHONPATH=$RM "$PY" -m pytest -q -p no:cacheprovider $CIFILES 2>&1 | tail -1 )
169
+ fi
170
+
171
+ hdr "8 SUMMARY"
172
+ printf " %-62s %s\n" "H0 #11 head, no robomimic (Actions runner)" "$H0LINE"
173
+ printf " %-62s %s\n" "R0 resolved tree, no robomimic" "$R0LINE"
174
+ printf " %-62s %s\n" "R1 resolved tree, patched fork importable" "$R1LINE"
175
+ case "$H0LINE" in *" passed"*) : ;; *) echo " BASELINE DID NOT PASS -- every other line is uninterpretable"; rc_all=2;; esac
176
+ case "$H0LINE" in *"no tests ran"*|*"error"*) echo " BASELINE COLLECTED NOTHING"; rc_all=2;; esac
177
+
178
+ hdr "9 cleanup worktrees"
179
+ git -C "$M" worktree remove --force "$WH" 2>/dev/null; git -C "$M" worktree remove --force "$WR" 2>/dev/null
180
+ hdr "OVERALL rc=$rc_all (2 = something was inconclusive, not a pass)"
181
+ exit $rc_all
rsm_rise/scripts/real/patchexport_merged_tests_detail.sh ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # rsm_real#5 -- run 18 follow-up. The first pass (LSF 1895089) reported
3
+ # H0 #11 head 102 passed, 2 skipped
4
+ # R0 resolved 101 passed, 4 skipped
5
+ # R1 resolved+fork 101 passed, 4 skipped
6
+ # Two things in that table are NOT yet measured, and one of them is a hole in my own guard:
7
+ # (1) R1 == R0 exactly. R1 was supposed to be the state SETUP.md produces -- the patched fork
8
+ # importable -- and in that state the two which_scorer tests should PASS naming the fork, not
9
+ # skip. Identical numbers are the signature of a case that never actually differed: almost
10
+ # certainly `import robomimic.algo.rsm_scorer` still raises in the CI venv (robomimic has
11
+ # runtime deps the deployment requirements do not carry), so the tests skip themselves for the
12
+ # same reason as R0. My guard checked that the FILE was reconstructed, not that it IMPORTS.
13
+ # That is this project's recorded failure mode one level in, so: import it, print the
14
+ # exception if it fails, install what is missing, and only then call R1 a result.
15
+ # (2) 104 collected on the head vs 105 on the resolved tree, and two passes became skips. A count
16
+ # that moves is a test that changed identity; name it rather than subtracting integers.
17
+ # Read-only w.r.t. every real repo: fetches from GitHub, works only inside SCRATCH, pushes nothing.
18
+ set -uo pipefail
19
+ source /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_resolve.sh
20
+ SCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run30}
21
+ VENV=${VENV:-/proj/dmfexp/zwhong/scratch_patchexport/run29/venv_ci}
22
+ RM=${RM:-/proj/dmfexp/zwhong/scratch_patchexport/run29/robomimic_fork}
23
+ PRS=${PRS:-"6 7 8 9 10"}
24
+ SC_PR=${SC_PR:-11}
25
+ export GIT_TERMINAL_PROMPT=0 PYTHONDONTWRITEBYTECODE=1 OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1
26
+ scrub(){ sed 's#https://[^@]*@#https://<redacted>@#g'; }
27
+ hdr(){ echo; echo "=================== $* ==================="; date -u; }
28
+ rc_all=0
29
+ mkdir -p "${SCRATCH:?}" || exit 1
30
+ M=$SCRATCH/mt
31
+ PY=$VENV/bin/python
32
+ [ -x "$PY" ] || { echo "no venv at $VENV -- run patchexport_merged_tests.sh first"; exit 2; }
33
+ [ -f "$RM/robomimic/algo/rsm_scorer.py" ] || { echo "no fork reconstruction at $RM"; exit 2; }
34
+
35
+ hdr "0 context"
36
+ echo "host=$(hostname) job=${LSB_JOBID:-none} scratch=$SCRATCH venv=$VENV fork=$RM"
37
+
38
+ hdr "1 rebuild the resolved tree (same steps as 1895089)"
39
+ TOK=$(grep -m1 'https://richardrl:' ~/.git-credentials | sed -E 's|https://richardrl:([^@]*)@.*|\1|')
40
+ [ -n "$TOK" ] || { echo "NO TOKEN"; exit 1; }
41
+ rm -rf "${M:?}"; git init --quiet "$M" || exit 1
42
+ printf '[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"
43
+ unset TOK
44
+ git -C "$M" fetch --quiet origin main 2>&1 | scrub
45
+ git -C "$M" checkout --quiet -b main FETCH_HEAD 2>&1 | scrub
46
+ git -C "$M" config user.email noreply@anthropic.com; git -C "$M" config user.name "merged-tests detail"
47
+ for n in $PRS $SC_PR; do git -C "$M" fetch --quiet origin "pull/$n/head:pr-$n" 2>&1 | scrub; done
48
+ SC_SHA=$(git -C "$M" rev-parse "pr-$SC_PR")
49
+ LIVE=$(git -C "$M" ls-remote origin "refs/pull/$SC_PR/head" 2>/dev/null | awk '{print $1}')
50
+ [ "$LIVE" = "$SC_SHA" ] || { echo "STALE: $SC_SHA != $LIVE"; exit 2; }
51
+ echo "staleness guard: OK -- sc == live head of PR #$SC_PR ($(echo "$SC_SHA" | cut -c1-7))"
52
+ 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; }; done
53
+ FIVE=$(git -C "$M" rev-parse HEAD)
54
+ git -C "$M" merge --no-ff -m "Merge PR #$SC_PR" "pr-$SC_PR" >/dev/null 2>&1
55
+ # run 23: rise_stack/scorers.py joined the conflict set when the union landed on #8 (c945f90).
56
+ # Its resolution is the same mechanical take-ours, so it goes in this list; the hand patch below is
57
+ # now only a fallback for a tree that predates that commit.
58
+ pe_resolve "$M" "$FIVE" scripts/setup_env.sh SETUP.md rise_stack/openpi/README.md scripts/check_env.py rise_stack/scorers.py
59
+ [ -z "$(git -C "$M" diff --name-only --diff-filter=U)" ] || { echo "RESOLUTION INCOMPLETE"; exit 2; }
60
+ python3 - "$M/rise_stack/scorers.py" <<'PY'
61
+ import re, sys
62
+ p = sys.argv[1]; s = open(p).read()
63
+ 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")
64
+ m = pat.search(s)
65
+ if not m:
66
+ if "from robomimic.algo.rsm_scorer import RSMScorer, chain_continuation_p, chain_cap_fn" in s and ".rsm.rsm_scorer" not in s:
67
+ print("scorers.py already single-source (the union landed on #8) -- nothing to patch")
68
+ sys.exit(0)
69
+ print("RESOLUTION PATCH FAILED"); sys.exit(3)
70
+ names = m.group(1).strip(); indent = re.match(r"[ \t]*", m.group(0)).group(0)
71
+ open(p,"w").write(s[:m.start()] + f"{indent}from robomimic.algo.rsm_scorer import {names}\n" + s[m.end():])
72
+ print(f"scorers.py resolved -> single import of robomimic.algo.rsm_scorer ({names})")
73
+ PY
74
+ [ $? -eq 0 ] || exit 2
75
+ git -C "$M" add rise_stack/scorers.py
76
+ git -C "$M" rm -rf -f --quiet rise_stack/rsm || exit 2
77
+ git -C "$M" commit --quiet -m "scratch: order-A merge + published resolution" || true
78
+ RES=$(git -C "$M" rev-parse HEAD)
79
+ echo "resolved commit = $(git -C "$M" rev-parse --short HEAD) tree $(git -C "$M" rev-parse --short HEAD^{tree})"
80
+ 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' ' ')
81
+ echo "CI test files: $CIFILES"
82
+
83
+ hdr "2 does the reconstructed fork IMPORT in the CI venv? (the check my guard was missing)"
84
+ # Run 18 first pass said R1 == R0 to the test. The reason, measured below, is that the fork does not
85
+ # import at all in the deployment venv (robomimic needs torchvision; requirements-deployment.txt does
86
+ # not carry it), so R1 silently repeated R0. Resolve dependencies in a LOOP -- install exactly the
87
+ # module the interpreter names, retry, and stop the moment the error stops being a missing module --
88
+ # so that "R1 ran" means the fork was really imported and not that the case degraded to R0 again.
89
+ export PIP_CACHE_DIR=/proj/dmfexp/zwhong/scratch_patchexport/run29/pipcache
90
+ # Run 18b measured the real dependency chain of the PATCHED fork: torchvision -> matplotlib ->
91
+ # diffusers -> diffusion_policy. The first three are wheels; `diffusion_policy` is NOT on PyPI --
92
+ # scripts/setup_env.sh clones UWRobotLearning/diffusion_policy at 078ce1e and puts the clone root on
93
+ # sys.path with a .pth (it is a namespace package: `pip install -e` exits 0 having installed zero
94
+ # modules). So R1 must reproduce THAT, not a pip install. Clone it and put it on PYTHONPATH.
95
+ DP=${DP:-/proj/dmfexp/zwhong/scratch_patchexport/run29/diffusion_policy}
96
+ DP_PIN=078ce1e
97
+ if [ ! -d "$DP/diffusion_policy" ]; then
98
+ # `fetch --depth 1 origin <short sha>` fails on github ("couldn't find remote ref 078ce1e") --
99
+ # a sha can only be fetched directly when the server allows it and only in full form. clone_at in
100
+ # setup_env.sh clones whole and then resets to the pin; do the same thing here.
101
+ rm -rf "$DP"
102
+ git clone --quiet https://github.com/UWRobotLearning/diffusion_policy.git "$DP" 2>&1 | scrub
103
+ git -C "$DP" checkout --quiet "$DP_PIN" 2>&1 | scrub || echo " !! checkout of $DP_PIN failed"
104
+ fi
105
+ if [ -d "$DP/diffusion_policy" ]; then
106
+ echo " diffusion_policy clone at $(git -C "$DP" rev-parse --short HEAD) (pin $DP_PIN, the one setup_env.sh uses)"
107
+ FORKPP="$RM:$DP"
108
+ else
109
+ echo " !! diffusion_policy clone FAILED -- R1 will stay inconclusive"; FORKPP="$RM"
110
+ fi
111
+ pkg_for(){ case "$1" in cv2) echo opencv-python;; PIL) echo pillow;; yaml) echo PyYAML;; egl_probe) echo egl_probe;; *) echo "$1";; esac; }
112
+ IMP_OK=0
113
+ for attempt in 1 2 3 4 5 6; do
114
+ 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
115
+ MISS=$(PYTHONPATH=$FORKPP "$PY" -c "
116
+ try:
117
+ import robomimic.algo.rsm_scorer
118
+ except ModuleNotFoundError as e:
119
+ print(e.name)
120
+ except Exception as e:
121
+ print('NON-MODULE-ERROR:'+type(e).__name__+': '+str(e)[:120])
122
+ " 2>/dev/null)
123
+ echo " attempt $attempt: import fails, interpreter names -> ${MISS:-<no name>}"
124
+ case "$MISS" in
125
+ ""|NON-MODULE-ERROR*)
126
+ echo " not a missing dependency; full traceback:"
127
+ PYTHONPATH=$FORKPP "$PY" -c "import robomimic.algo.rsm_scorer" 2>&1 | tail -8 | sed 's/^/ /'
128
+ break ;;
129
+ esac
130
+ PKG=$(pkg_for "$MISS")
131
+ echo " installing $PKG (a DIVERGENCE from the Actions runner, which installs no robomimic at all -- recorded, not hidden)"
132
+ if [ "$PKG" = torchvision ]; then
133
+ "$PY" -m pip install --quiet torchvision --index-url https://download.pytorch.org/whl/cpu 2>&1 | tail -3 | sed 's/^/ /'
134
+ else
135
+ "$PY" -m pip install --quiet "$PKG" 2>&1 | tail -3 | sed 's/^/ /'
136
+ fi
137
+ done
138
+ echo " fork importable in the CI venv: $IMP_OK"
139
+ [ "$IMP_OK" = 1 ] || { echo " R1 INCONCLUSIVE -- reported as such, not as a pass"; rc_all=2; }
140
+ 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
141
+
142
+ hdr "3 per-test outcome tables (-v), head vs resolved"
143
+ WH=$SCRATCH/t_head; WR=$SCRATCH/t_resolved
144
+ rm -rf "$WH" "$WR"
145
+ git -C "$M" worktree add --quiet --detach "$WH" "$SC_SHA" || exit 2
146
+ git -C "$M" worktree add --quiet --detach "$WR" "$RES" || exit 2
147
+ tbl(){ # dir pythonpath outfile
148
+ ( cd "$1" && PYTHONPATH=$2 "$PY" -m pytest -v -p no:cacheprovider $CIFILES 2>&1 ) \
149
+ | sed -n 's#^\(tests/[^ ]*\) \(PASSED\|FAILED\|SKIPPED\|ERROR\|XFAIL\|XPASS\).*#\1 \2#p' | sort > "$3"
150
+ echo " $(wc -l < "$3") test ids -> $(basename "$3")"
151
+ }
152
+ tbl "$WH" "" "$SCRATCH/H0.txt"
153
+ tbl "$WR" "" "$SCRATCH/R0.txt"
154
+ tbl "$WR" "$FORKPP" "$SCRATCH/R1.txt"
155
+ for f in H0 R0 R1; do
156
+ echo " $f: $(awk '{print $2}' "$SCRATCH/$f.txt" | sort | uniq -c | tr '\n' ' ')"
157
+ done
158
+
159
+ hdr "4 what actually differs -- named, not subtracted"
160
+ echo "--- H0 vs R0 (the effect of the merge + my resolution) ---"
161
+ join -a1 -a2 -e MISSING -o 0,1.2,2.2 "$SCRATCH/H0.txt" "$SCRATCH/R0.txt" 2>/dev/null \
162
+ | awk '$2!=$3 {printf " %-88s %s -> %s\n", $1, $2, $3}'
163
+ echo "--- R0 vs R1 (the effect of having the patched fork importable) ---"
164
+ join -a1 -a2 -e MISSING -o 0,1.2,2.2 "$SCRATCH/R0.txt" "$SCRATCH/R1.txt" 2>/dev/null \
165
+ | awk '$2!=$3 {printf " %-88s %s -> %s\n", $1, $2, $3}'
166
+
167
+ hdr "5 why does each changed test skip? (the reason string, from -rs)"
168
+ ( cd "$WR" && PYTHONPATH= "$PY" -m pytest -q -rs -p no:cacheprovider $CIFILES 2>&1 | sed -n '/short test summary/,$p' ) | sed 's/^/ R0 /'
169
+ if [ "$IMP_OK" = 1 ]; then
170
+ ( cd "$WR" && PYTHONPATH=$FORKPP "$PY" -m pytest -q -rs -p no:cacheprovider $CIFILES 2>&1 | sed -n '/short test summary/,$p' ) | sed 's/^/ R1 /'
171
+ fi
172
+
173
+ hdr "6 cleanup"
174
+ git -C "$M" worktree remove --force "$WH" 2>/dev/null; git -C "$M" worktree remove --force "$WR" 2>/dev/null
175
+ hdr "OVERALL rc=$rc_all (2 = something was inconclusive, not a pass)"
176
+ exit $rc_all
rsm_rise/scripts/real/patchexport_models_conflict_probe.sh ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # rsm_real#5 run 30 -- the six-way merge SHAPE CHANGED and the runbook refused. Diagnose it.
3
+ #
4
+ # #11 moved a6c2af21 -> fdfa758f (22:02-22:10Z) and that head modifies real/deployment/models.py
5
+ # (+35 -5) and tests/test_deployment_models.py (+36). Both are now unmerged and neither is in the
6
+ # runbook's take-ours list, so pe_resolve_check refused -- the right behaviour, and the reason a
7
+ # resolution list keyed on five paths has to be re-derived whenever either side moves.
8
+ #
9
+ # This probe does NOT resolve anything. It measures who changed what, whether the two sides' hunks
10
+ # are disjoint (union-able) or overlapping (a genuine disagreement someone must choose), and which of
11
+ # OUR PRs is the other party.
12
+ set -uo pipefail
13
+ source /proj/dmfexp/zwhong/rsm_rise/scripts/real/patchexport_resolve.sh
14
+ SCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run97}
15
+ export GIT_TERMINAL_PROMPT=0
16
+ scrub(){ sed 's#https://[^@]*@#https://<redacted>@#g'; }
17
+ hdr(){ echo; echo "=================== $* ==================="; }
18
+ die(){ echo "PROBE FAILED: $*"; exit 7; }
19
+ mkdir -p "${SCRATCH:?}" || exit 1
20
+ W=$SCRATCH/probe
21
+ TOK=$(grep -m1 'https://richardrl:' ~/.git-credentials | sed -E 's|https://richardrl:([^@]*)@.*|\1|')
22
+ [ -n "$TOK" ] || die "no token"
23
+ rm -rf "${W:?}"; git init --quiet "$W" || exit 1
24
+ 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"
25
+ unset TOK
26
+ git -C "$W" fetch --quiet origin 2>&1 | scrub || die fetch
27
+ git -C "$W" config user.email noreply@anthropic.com; git -C "$W" config user.name richardrl
28
+ for n in 6 7 8 9 10 11; do git -C "$W" fetch --quiet --force origin "pull/$n/head:pr-$n" 2>&1 | scrub; done
29
+ g(){ git -C "$W" "$@"; }
30
+ FILES="real/deployment/models.py tests/test_deployment_models.py"
31
+
32
+ hdr "0 heads"
33
+ echo "main = $(g rev-parse --short origin/main)"
34
+ for n in 6 7 8 9 10 11; do echo "#$n = $(g rev-parse --short pr-$n)"; done
35
+
36
+ hdr "1 which side touches the two new conflict paths, relative to main"
37
+ for f in $FILES; do
38
+ echo "--- $f"
39
+ for n in 6 7 8 9 10 11; do
40
+ st=$(g diff --numstat "origin/main...pr-$n" -- "$f")
41
+ [ -n "$st" ] && echo " #$n +$(echo "$st" | awk '{print $1}') -$(echo "$st" | awk '{print $2}')"
42
+ done
43
+ done
44
+
45
+ hdr "2 the five-way head (main + #6..#10), then #11"
46
+ g checkout --quiet -B probe origin/main 2>&1 | scrub
47
+ for n in 6 7 8 9 10; do
48
+ g merge --no-ff -m "probe #$n" "pr-$n" >/dev/null 2>&1 || die "#$n no longer clean on its own"
49
+ done
50
+ FIVE=$(g rev-parse HEAD); echo "five-way = ${FIVE:0:8}"
51
+ for f in $FILES; do echo " five-way vs main $f: $(g diff --numstat "origin/main..HEAD" -- "$f" | awk '{print "+"$1" -"$2}')"; done
52
+ g merge --no-ff -m "probe #11" pr-11 >/dev/null 2>&1
53
+ echo "unmerged:"; g diff --name-only --diff-filter=U | sed 's/^/ /'
54
+
55
+ hdr "3 the conflict hunks, with their line ranges"
56
+ for f in $FILES; do
57
+ echo "########## $f"
58
+ echo " conflict hunk count: $(grep -c '^<<<<<<<' "$W/$f" 2>/dev/null || echo 0)"
59
+ awk '/^<<<<<<</{inc=1} inc{print FILENAME":"FNR": "$0} /^>>>>>>>/{inc=0}' "$W/$f" | sed 's/^/ /' | head -120
60
+ done
61
+
62
+ hdr "4 are the two sides' changes DISJOINT? base/ours/theirs diffs per file"
63
+ T=$SCRATCH/stage; rm -rf "$T"; mkdir -p "$T"
64
+ for f in $FILES; do
65
+ b=$T/$(basename "$f").base; o=$T/$(basename "$f").ours; t=$T/$(basename "$f").theirs
66
+ g show ":1:$f" > "$b" 2>/dev/null; g show ":2:$f" > "$o" 2>/dev/null; g show ":3:$f" > "$t" 2>/dev/null
67
+ echo "--- $f base=$(wc -l < "$b") ours=$(wc -l < "$o") theirs=$(wc -l < "$t")"
68
+ echo " OURS vs base:"; diff -u "$b" "$o" | sed -n '3,$p' | sed 's/^/ /' | head -60
69
+ echo " THEIRS vs base:"; diff -u "$b" "$t" | sed -n '3,$p' | sed 's/^/ /' | head -80
70
+ echo " diff3 merge attempt (rc says whether a union exists):"
71
+ if diff3 -m "$o" "$b" "$t" > "$T/$(basename "$f").m3" 2>/dev/null; then
72
+ echo " diff3 CLEAN union, $(wc -l < "$T/$(basename "$f").m3") lines"
73
+ else
74
+ echo " diff3 reports overlap: $(grep -c '^<<<<<<<' "$T/$(basename "$f").m3") region(s)"
75
+ fi
76
+ done
77
+
78
+ hdr "5 what #8 does to rise_stack/rsm (the reason models.py disagrees at all)"
79
+ echo " files under rise_stack/rsm on the five-way head:"; g ls-tree -r --name-only "$FIVE" -- rise_stack/rsm | sed 's/^/ /'
80
+ echo " files under rise_stack/rsm on #11:"; g ls-tree -r --name-only pr-11 -- rise_stack/rsm | sed 's/^/ /'
81
+ g merge --abort 2>/dev/null
82
+ hdr "PROBE DONE"
rsm_rise/scripts/real/patchexport_models_union.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """rsm_real#5 run 30 -- union the two rewrites of `dependency_report`'s RSM branch.
3
+
4
+ #11's head fdfa758f grew two NEW conflicting paths outside the runbook's take-ours five:
5
+ `real/deployment/models.py` and `tests/test_deployment_models.py`. Both sides rewrote the SAME
6
+ `if scorer_kind == "rsm":` block, and `diff3 -m` reports a genuine overlap (LSF 1907385), so this is
7
+ not a preference to settle by keeping one side -- taking either alone silently drops a fix that was
8
+ measured:
9
+
10
+ OURS (#8): the pinned rsm_libero may be INSTALLED as a package, so `RSM_LIBERO_DIR` -- an env var
11
+ aimed at somebody's research checkout -- must not be a deployment requirement.
12
+ THEIRS (#11): ASK `which_scorer.resolve()` which implementation will load, instead of demanding the
13
+ fork unconditionally; on a tree carrying `rise_stack/rsm/` neither the fork nor the env
14
+ var is required (LSF 1905498 PROBE C: 3 missing deps in an interpreter that then scored).
15
+
16
+ The two are orthogonal: theirs decides WHICH scorer answers, ours decides what counts as a usable
17
+ rsm_libero SOURCE. The union keeps theirs' structure and transplants ours' source test into both of
18
+ its branches -- including the `else:` branch, which on their side is still the old env-var-only demand
19
+ and is exactly the branch the merged tree takes (#8 deletes `rise_stack/rsm/`, so nothing is vendored).
20
+
21
+ Every edit is ANCHORED on an exact string that must occur exactly once; a missing or repeated anchor
22
+ is a refusal, not a best effort. That is the lesson of the `>=` floors and of the four duplicated
23
+ `deployment.yml` lines: a builder that "mostly finds" its anchor writes a file nobody can reproduce.
24
+ """
25
+ from __future__ import annotations
26
+
27
+ import argparse
28
+ import ast
29
+ import sys
30
+
31
+ MARKER = "# UNION (rsm_real#5 run 30)"
32
+
33
+
34
+ def die(msg: str) -> None:
35
+ print(f" !! models union REFUSED: {msg}", file=sys.stderr)
36
+ raise SystemExit(3)
37
+
38
+
39
+ def once(text: str, anchor: str, what: str) -> None:
40
+ n = text.count(anchor)
41
+ if n != 1:
42
+ die(f"{what}: anchor occurs {n} times, expected exactly 1: {anchor[:70]!r}")
43
+
44
+
45
+ # --------------------------------------------------------------------------------------- models.py
46
+ # Their clause, verbatim from fdfa758f: a RESOLVED scorer whose rsm_libero source is not one of the
47
+ # three known-good values is reported missing. Ours adds a fourth good value -- an INSTALLED package.
48
+ THEIR_SOURCE_TEST = """ if resolved.get("rsm_libero_source") not in ("vendored", "env", "env-invalid"):
49
+ missing.append(
50
+ f"a usable rsm_libero for {resolved['module']} "
51
+ f"(source: {resolved.get('rsm_libero_source')}); set RSM_LIBERO_DIR to a tree with "
52
+ "model.py, train_rsm.py, is_ope.py, data.py, pinned to the scorer's revision")"""
53
+
54
+ UNION_SOURCE_TEST = f""" # {MARKER[2:]}: an INSTALLED `rsm_libero` is the fourth resolved source. #8 ships the
55
+ # pinned gen_q revision to be installed with `pip install -e <clone>`; a deployment machine
56
+ # that did so has the four modules on `sys.path` under no env var and with nothing vendored,
57
+ # and `resolve()` reports the source as "unknown" there because it only looks at the
58
+ # vendored directory and RSM_LIBERO_DIR. Demanding the env var anyway is the same
59
+ # contradiction in the other direction: a missing row for a module that imports.
60
+ if (resolved.get("rsm_libero_source") not in ("vendored", "env", "env-invalid")
61
+ and not _available("rsm_libero")):
62
+ missing.append(
63
+ f"a usable rsm_libero for {{resolved['module']}} "
64
+ f"(source: {{resolved.get('rsm_libero_source')}}): install the gen_q revision in "
65
+ "rise_stack/rsm_libero/UPSTREAM_COMMIT.txt with `pip install -e <clone>`, or set "
66
+ "RSM_LIBERO_DIR to a tree with model.py, train_rsm.py, is_ope.py, data.py, "
67
+ "pinned to the scorer's revision")"""
68
+
69
+ # Their `else:` branch (nothing resolved) is the UNMODIFIED base text, so it still demands
70
+ # RSM_LIBERO_DIR. On the merged tree that branch is the live one, which is why ours goes here.
71
+ THEIR_ELSE_ENVDEMAND = """ rsm_dir = Path(os.environ.get("RSM_LIBERO_DIR", ""))
72
+ 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")):
73
+ 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")"""
74
+
75
+ UNION_ELSE_ENVDEMAND = f""" # {MARKER[2:]}: #8's source test, transplanted into the branch the merged tree takes.
76
+ # The pinned rsm_libero satisfies this either way it was installed: as a package
77
+ # (`pip install -e <gen_q clone>`, see rise_stack/rsm_libero/) or as a directory pointed
78
+ # at by RSM_LIBERO_DIR. The installed package is the supported route on a robot.
79
+ rsm_dir = Path(os.environ.get("RSM_LIBERO_DIR", ""))
80
+ has_dir = bool(os.environ.get("RSM_LIBERO_DIR")) and all(
81
+ (rsm_dir / name).is_file() for name in ("model.py", "train_rsm.py", "is_ope.py"))
82
+ if not (has_dir or _available("rsm_libero")):
83
+ missing.append("the pinned rsm_libero source (model.py, train_rsm.py, is_ope.py): install the "
84
+ "gen_q revision in rise_stack/rsm_libero/UPSTREAM_COMMIT.txt with "
85
+ "`pip install -e <clone>`, or set RSM_LIBERO_DIR pointing to the matching "
86
+ "rsm_libero tree, pinned to the scorer's revision")"""
87
+
88
+
89
+ def union_models(base: str, ours: str, theirs: str) -> str:
90
+ if MARKER in theirs or MARKER in ours:
91
+ die("an input already carries the union marker -- this builder does not run twice")
92
+ # Sanity on the sides themselves: each must carry the thing it is contributing.
93
+ if "which_scorer import resolve" not in theirs:
94
+ die("theirs does not ask which_scorer.resolve -- not the side this union was written for")
95
+ if '_available("rsm_libero")' not in ours:
96
+ die("ours does not test for an installed rsm_libero -- not the side this union was written for")
97
+ out = theirs
98
+ once(out, THEIR_SOURCE_TEST, "models.py resolved-source clause")
99
+ out = out.replace(THEIR_SOURCE_TEST, UNION_SOURCE_TEST)
100
+ once(out, THEIR_ELSE_ENVDEMAND, "models.py else-branch env demand")
101
+ out = out.replace(THEIR_ELSE_ENVDEMAND, UNION_ELSE_ENVDEMAND)
102
+ # Self-checks in the units a "does it parse" test cannot see.
103
+ try:
104
+ ast.parse(out)
105
+ except SyntaxError as exc:
106
+ die(f"the union does not parse: {exc}")
107
+ for need, what in [
108
+ ("which_scorer import resolve", "theirs' resolver question"),
109
+ ('_available("rsm_libero")', "ours' installed-package test"),
110
+ ("has_dir or _available", "ours' else-branch test"),
111
+ ("rise_stack/rsm_libero/UPSTREAM_COMMIT.txt", "ours' install instruction"),
112
+ ("RSM_LIBERO_DIR", "the env-var route"),
113
+ ]:
114
+ if need not in out:
115
+ die(f"the union lost {what} ({need!r})")
116
+ n_src = out.count('_available("rsm_libero")')
117
+ if n_src != 2:
118
+ die(f"ours' installed-package test must land in BOTH branches (resolved and else), found {n_src}")
119
+ if "<<<<<<<" in out or ">>>>>>>" in out:
120
+ die("the union carries conflict markers")
121
+ if len(out.splitlines()) < max(len(ours.splitlines()), len(theirs.splitlines())):
122
+ die("the union is shorter than the longer side -- something was dropped")
123
+ return out
124
+
125
+
126
+ # ------------------------------------------------------------------------- tests/test_deployment_models.py
127
+ def _funcs(text: str) -> dict[str, str]:
128
+ tree = ast.parse(text)
129
+ lines = text.splitlines(keepends=True)
130
+ out = {}
131
+ for node in tree.body:
132
+ if isinstance(node, ast.FunctionDef):
133
+ out[node.name] = "".join(lines[node.lineno - 1: node.end_lineno])
134
+ return out
135
+
136
+
137
+ def union_tests(base: str, ours: str, theirs: str) -> str:
138
+ bf, of, tf = _funcs(base), _funcs(ours), _funcs(theirs)
139
+ ours_new = [n for n in of if n not in bf]
140
+ theirs_new = [n for n in tf if n not in bf]
141
+ if not ours_new:
142
+ die("ours adds no test -- nothing to union")
143
+ if not theirs_new:
144
+ die("theirs adds no test -- nothing to union")
145
+ missing_from_theirs = [n for n in ours_new if n not in tf]
146
+ if not missing_from_theirs:
147
+ die("every test ours adds is already on theirs -- take-theirs would do, refusing to rewrite")
148
+ # Anchor: the first base function that follows the insertion point on BOTH sides.
149
+ anchor = "def test_rsm_does_not_pad_short_chunks("
150
+ once(theirs, anchor, "test file insertion anchor")
151
+ block = "".join(of[n].rstrip("\n") + "\n\n\n" for n in missing_from_theirs)
152
+ out = theirs.replace(anchor, f"# {MARKER[2:]}: #8's test, kept alongside #11's two.\n{block}{anchor}")
153
+ try:
154
+ ast.parse(out)
155
+ except SyntaxError as exc:
156
+ die(f"the test union does not parse: {exc}")
157
+ got = _funcs(out)
158
+ for n in set(of) | set(tf):
159
+ if n not in got:
160
+ die(f"the test union lost {n}")
161
+ dupes = [n for n in got if out.count(f"def {n}(") != 1]
162
+ if dupes:
163
+ die(f"the test union defines these more than once: {dupes}")
164
+ if len(got) != len(set(of) | set(tf)):
165
+ die(f"the test union has {len(got)} tests, expected {len(set(of) | set(tf))}")
166
+ return out
167
+
168
+
169
+ def main() -> int:
170
+ ap = argparse.ArgumentParser()
171
+ ap.add_argument("kind", choices=["models", "tests"])
172
+ ap.add_argument("base"); ap.add_argument("ours"); ap.add_argument("theirs")
173
+ ap.add_argument("-o", "--out", required=True)
174
+ a = ap.parse_args()
175
+ b, o, t = (open(p).read() for p in (a.base, a.ours, a.theirs))
176
+ if not b.strip() or not o.strip() or not t.strip():
177
+ die("one of base/ours/theirs is empty -- a union of nothing is not a resolution")
178
+ out = union_models(b, o, t) if a.kind == "models" else union_tests(b, o, t)
179
+ open(a.out, "w").write(out)
180
+ print(f" models union OK [{a.kind}]: base={len(b.splitlines())} ours={len(o.splitlines())} "
181
+ f"theirs={len(t.splitlines())} -> union={len(out.splitlines())} lines")
182
+ return 0
183
+
184
+
185
+ if __name__ == "__main__":
186
+ raise SystemExit(main())
rsm_rise/scripts/real/patchexport_openpi_numbers.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Measure the openpi patch's own numbers from the patch file, and check both README tables against it.
3
+
4
+ rsm_real#5 run 23. #11's 6c1b8d0 ("The openpi patch's own numbers were written in three places; two
5
+ had drifted") rewrote the per-file table in rise_stack/openpi/README.md. Our side (#6/#10) carries the
6
+ OLDER table, which the six-way runbook resolves by taking ours -- so if their correction is right, the
7
+ merge reinstates numbers they just measured as wrong. Neither table is evidence: this parses the patch.
8
+
9
+ usage: patchexport_openpi_numbers.py <rise_on_pi05.patch> <ours_README.md> <theirs_README.md>
10
+ """
11
+ import re
12
+ import sys
13
+
14
+ patch_p, ours_p, theirs_p = sys.argv[1], sys.argv[2], sys.argv[3]
15
+
16
+ # --- 1 truth: parse the unified diff -----------------------------------------------------------
17
+ files, cur = {}, None
18
+ for line in open(patch_p, errors="replace"):
19
+ if line.startswith("+++ "):
20
+ p = line[4:].strip()
21
+ cur = None if p == "/dev/null" else re.sub(r"^b/", "", p)
22
+ files.setdefault(cur, {"ins": 0, "del": 0, "new": False})
23
+ elif line.startswith("--- "):
24
+ prev = line[4:].strip()
25
+ if prev == "/dev/null":
26
+ pending_new = True
27
+ else:
28
+ pending_new = False
29
+ globals()["_pending_new"] = pending_new
30
+ elif cur is not None and line.startswith("+") and not line.startswith("+++"):
31
+ files[cur]["ins"] += 1
32
+ if globals().get("_pending_new"):
33
+ files[cur]["new"] = True
34
+ elif cur is not None and line.startswith("-") and not line.startswith("---"):
35
+ files[cur]["del"] += 1
36
+
37
+ tot_i = sum(v["ins"] for v in files.values())
38
+ tot_d = sum(v["del"] for v in files.values())
39
+ print(f"MEASURED from {patch_p.split('/')[-1]}: {len(files)} files, {tot_i} insertions, {tot_d} deletions")
40
+ for f, v in sorted(files.items(), key=lambda kv: -kv[1]["ins"]):
41
+ print(f" {f:<45} +{v['ins']:<5} -{v['del']:<4}{' NEW FILE' if v['new'] else ''}")
42
+
43
+ # --- 2 what each README claims ------------------------------------------------------------------
44
+ CLAIM = re.compile(r"\+(\d[\d,]*)")
45
+ def claims(path):
46
+ out = {}
47
+ hdr = None
48
+ for line in open(path, errors="replace"):
49
+ if not line.lstrip().startswith("|"):
50
+ continue
51
+ cells = [c.strip() for c in line.strip().strip("|").split("|")]
52
+ # a row is interesting when its first cell names one or more source paths in backticks
53
+ paths = re.findall(r"`([\w/\.]+\.py)`", cells[0]) if cells else []
54
+ if not paths:
55
+ continue
56
+ nums = [int(n.replace(",", "")) for c in cells[1:] for n in CLAIM.findall(c)]
57
+ if nums:
58
+ out[tuple(paths)] = nums[0] if len(nums) == 1 else nums
59
+ return out
60
+
61
+ def totals(path):
62
+ t = open(path, errors="replace").read()
63
+ m = re.search(r"(\d+) files?, ([\d,]+) insertions?", t)
64
+ return (int(m.group(1)), int(m.group(2).replace(",", ""))) if m else None
65
+
66
+ rc = 0
67
+ for label, p in (("OURS (#6/#10)", ours_p), ("THEIRS (#11)", theirs_p)):
68
+ print(f"\n=== {label} ===")
69
+ tt = totals(p)
70
+ print(f" headline totals claimed: {tt} measured: ({len(files)}, {tot_i})")
71
+ if tt and tt != (len(files), tot_i):
72
+ print(f" !! HEADLINE WRONG")
73
+ c = claims(p)
74
+ print(f" {len(c)} per-file row(s) with a +N")
75
+ for paths, n in sorted(c.items()):
76
+ want = sum(files.get("src/openpi/" + q.split("openpi/")[-1], files.get(q, {"ins": 0}))["ins"]
77
+ if False else 0 for q in paths)
78
+ # resolve each claimed path against the measured set by suffix match
79
+ got = 0
80
+ matched = []
81
+ for q in paths:
82
+ hit = [f for f in files if f.endswith(q) or f.split("/")[-1] == q.split("/")[-1]]
83
+ if hit:
84
+ got += files[hit[0]]["ins"]
85
+ matched.append(hit[0])
86
+ n0 = n if isinstance(n, int) else n[0]
87
+ ok = "OK " if n0 == got else "!! "
88
+ if n0 != got:
89
+ rc = 1
90
+ print(f" {ok}{'+'.join(paths):<50} claims +{n0:<5} measured +{got} {matched if not matched else ''}")
91
+ print(f"\nrc={rc} (1 = at least one README row disagrees with the patch)")
92
+ sys.exit(0)
rsm_rise/scripts/real/patchexport_openpi_readme_fix.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Fold #11's MEASURED openpi per-file table into our rise_stack/openpi/README.md.
3
+
4
+ rsm_real#5 run 23. LSF 1900991 parsed rise_on_pi05.patch and found our table wrong in 5 of 7 rows
5
+ (train.py +232 vs 224, model.py +39 vs 32, data_loader.py +158 vs 156, optimizer.py +41 vs 39,
6
+ weight_loaders.py +11 vs 9) and #11's right in 9 of 9. The runbook resolves this file by taking our
7
+ side, so without this the merge reinstates five numbers #11 has just measured as wrong.
8
+
9
+ Structural and refuses to guess: exactly one `| file |` table in each side, one `* Our changes:` bullet
10
+ in each, or it exits 3. Our prose is kept -- #11's document is a shortened rewrite of ours everywhere
11
+ else, and the run-22 union already measured that.
12
+
13
+ usage: patchexport_openpi_readme_fix.py <ours.md> <theirs.md> <out.md>
14
+ """
15
+ import sys
16
+
17
+ ours_p, theirs_p, out_p = sys.argv[1], sys.argv[2], sys.argv[3]
18
+ ours = open(ours_p).read().splitlines()
19
+ theirs = open(theirs_p).read().splitlines()
20
+
21
+ def one(lines, pred, what):
22
+ hits = [i for i, l in enumerate(lines) if pred(l)]
23
+ if len(hits) != 1:
24
+ print(f"REFUSING: expected exactly 1 {what}, found {len(hits)}", file=sys.stderr)
25
+ sys.exit(3)
26
+ return hits[0]
27
+
28
+ def table(lines):
29
+ s = one(lines, lambda l: l.startswith("| file |"), "per-file table header")
30
+ e = s
31
+ while e + 1 < len(lines) and lines[e + 1].startswith("|"):
32
+ e += 1
33
+ return s, e
34
+
35
+ def bullet(lines):
36
+ return one(lines, lambda l: l.startswith("* Our changes:"), "`* Our changes:` bullet")
37
+
38
+ ob, tb = bullet(ours), bullet(theirs)
39
+ os_, oe = table(ours)
40
+ ts, te = table(theirs)
41
+ # #11 follows its table with a paragraph naming the test that recomputes the numbers; keep it.
42
+ np_s = te + 1
43
+ while np_s < len(theirs) and not theirs[np_s].strip():
44
+ np_s += 1
45
+ np_e = np_s
46
+ while np_e < len(theirs) and theirs[np_e].strip():
47
+ np_e += 1
48
+ note = theirs[np_s:np_e]
49
+ if not any("recomputes" in l or "test_rise_stack_openpi_patch_numbers" in l for l in note):
50
+ print("REFUSING: the paragraph after #11's table is not the one that names the test", file=sys.stderr)
51
+ sys.exit(3)
52
+
53
+ print(f"ours: bullet line {ob+1}, table lines {os_+1}..{oe+1} ({oe-os_+1} rows)")
54
+ print(f"#11 : bullet line {tb+1}, table lines {ts+1}..{te+1} ({te-ts+1} rows), note {np_s+1}..{np_e}")
55
+
56
+ out = list(ours)
57
+ # replace the table first (higher line numbers) so the bullet index stays valid
58
+ out[os_:oe + 1] = theirs[ts:te + 1] + [""] + note
59
+ out[ob] = theirs[tb]
60
+ # #11's f3c0713 added a paragraph that its own test pins: the patch DECLARES 12 pi05_cooking_*
61
+ # TrainConfigs, baselines.yaml WIRES 11, and the twelfth (pi05_cooking_risebn) has never been built.
62
+ # Our line said "All 11 ... still build under the fixed patch", which is the drifted claim their
63
+ # docstring names. Replace ours with theirs, or refuse.
64
+ oi = one(out, lambda l: l.startswith("All 11 `pi05_cooking_*`"), "the `All 11 ...` sentence")
65
+ ds = one(theirs, lambda l: l.startswith("The patch declares **"), "the `The patch declares` paragraph")
66
+ de = ds
67
+ while de + 1 < len(theirs) and theirs[de + 1].strip():
68
+ de += 1
69
+ para = theirs[ds:de + 1]
70
+ for must in ("risebn", "wires up"):
71
+ if not any(must in l for l in para):
72
+ print(f"REFUSING: #11's paragraph does not mention {must!r}", file=sys.stderr)
73
+ sys.exit(3)
74
+ print(f"replacing our line {oi+1} with #11's lines {ds+1}..{de+1} ({len(para)} lines)")
75
+ out[oi:oi + 1] = para
76
+
77
+ open(out_p, "w").write("\n".join(out) + "\n")
78
+ print(f"wrote {out_p}: {len(ours)} -> {len(out)} lines")
79
+
80
+ # the paragraph we must NOT have dropped: ours explains how the patch is regenerated
81
+ kept = "\n".join(out)
82
+ for must in ("git add -A && git diff --cached",
83
+ "One thing you must change to *retrain*",
84
+ "verify_inference_no_split.py"):
85
+ print(f" kept {must!r}: {must in kept}")
86
+ if must not in kept:
87
+ sys.exit(4)
rsm_rise/scripts/real/patchexport_openpi_readme_push.sh ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # SUPERSEDED 2026-09-24 (run 28): this gate trial-merges a SUBSET, not main + #6..#10 + #11.
3
+ # That hole is a measured failure of this stream -- LSF 1902702 caught a conflict AFTER a push whose
4
+ # gate merged only `main -> #6 -> #10`. Do not reuse this script for a new push. Copy
5
+ # scripts/real/patchexport_readme_dedupe_push.sh instead: it does the full merge with pe_resolve, runs
6
+ # #11's control ledger on the merged tree, and diffs pytest against a baseline MEASURED on main alone
7
+ # rather than against a hardcoded expectation.
8
+ # rsm_real#5 run 23 -- fold #11's MEASURED openpi per-file table into our rise_stack/openpi/README.md,
9
+ # on BOTH branches that add the file (#6 and #10), with the blob identical on the two.
10
+ #
11
+ # Why: LSF 1900991 parsed rise_on_pi05.patch itself and found our table wrong in 5 of 7 rows and #11's
12
+ # right in 9 of 9. The runbook resolves this file by taking our side, so leaving it would make the
13
+ # merge reinstate five numbers #11 has just measured as wrong -- and #11 now ships
14
+ # tests/test_rise_stack_openpi_patch_numbers.py, which recomputes them, so the merged tree would go red.
15
+ set -uo pipefail
16
+ S=${S:-/proj/dmfexp/zwhong/scratch_patchexport/run63}
17
+ WT_SETUP=${WT_SETUP:-/proj/dmfexp/zwhong/scratch_patchexport/wt_setup} # #10
18
+ WT_MAIN=${WT_MAIN:-/proj/dmfexp/zwhong/scratch_patchexport/wt_main} # #6
19
+ DO_PUSH=${DO_PUSH:-0}
20
+ D=/proj/dmfexp/zwhong/rsm_rise/scripts/real
21
+ export GIT_TERMINAL_PROMPT=0
22
+ scrub(){ sed 's#https://[^@]*@#https://<redacted>@#g'; }
23
+ hdr(){ echo; echo "=================== $* ==================="; date -u; }
24
+ mkdir -p "$S"; rc=0
25
+
26
+ hdr "0 context"
27
+ echo "host=$(hostname) job=${LSB_JOBID:-none} do_push=$DO_PUSH"
28
+ for wt in "$WT_SETUP" "$WT_MAIN"; do
29
+ echo " $wt on $(git -C "$wt" rev-parse --abbrev-ref HEAD) @ $(git -C "$wt" rev-parse --short HEAD)"
30
+ d=$(git -C "$wt" status --porcelain); [ -z "$d" ] || { echo " DIRTY -- refusing:"; echo "$d"; exit 2; }
31
+ b=$(git -C "$wt" rev-parse --abbrev-ref HEAD)
32
+ git -C "$wt" fetch --quiet origin "$b" 2>&1 | scrub || exit 2
33
+ L=$(git -C "$wt" rev-parse HEAD); R=$(git -C "$wt" rev-parse FETCH_HEAD)
34
+ [ "$L" = "$R" ] || { echo " $b: local ${L:0:7} != origin ${R:0:7} -- REFUSING"; exit 2; }
35
+ done
36
+ A=$(git -C "$WT_SETUP" rev-parse HEAD:rise_stack/openpi/README.md)
37
+ B=$(git -C "$WT_MAIN" rev-parse HEAD:rise_stack/openpi/README.md)
38
+ echo " current blobs: #10 ${A:0:10} #6 ${B:0:10}"
39
+ [ "$A" = "$B" ] || { echo " the two branches already differ on this file -- REFUSING"; exit 2; }
40
+
41
+ hdr "1 live #11 blob + our patch file"
42
+ git -C "$WT_SETUP" fetch --quiet origin 'pull/11/head:refs/remotes/pr/11-now' --force 2>&1 | scrub
43
+ SC=$(git -C "$WT_SETUP" rev-parse refs/remotes/pr/11-now)
44
+ LIVE=$(git -C "$WT_SETUP" ls-remote origin refs/pull/11/head | awk '{print $1}')
45
+ [ -n "$LIVE" ] && [ "$LIVE" = "$SC" ] || { echo "STALENESS GUARD FAILED"; exit 2; }
46
+ echo " #11 live head ${SC:0:7}"
47
+ git -C "$WT_SETUP" show "HEAD:rise_stack/openpi/rise_on_pi05.patch" > "$S/rise_on_pi05.patch"
48
+ git -C "$WT_SETUP" show "HEAD:rise_stack/openpi/README.md" > "$S/ours_README.md"
49
+ git -C "$WT_SETUP" show "$SC:rise_stack/openpi/README.md" > "$S/theirs_README.md"
50
+
51
+ hdr "2 build the corrected README"
52
+ python3 "$D/patchexport_openpi_readme_fix.py" "$S/ours_README.md" "$S/theirs_README.md" "$S/fixed_README.md" || { echo "transform refused"; exit 3; }
53
+
54
+ hdr "3 the corrected file must agree with the patch file on EVERY row"
55
+ python3 "$D/patchexport_openpi_numbers.py" "$S/rise_on_pi05.patch" "$S/fixed_README.md" "$S/theirs_README.md" > "$S/nums_after.log" 2>&1
56
+ sed -n '/=== OURS/,$p' "$S/nums_after.log"
57
+ if grep -qE '^ !! ' "$S/nums_after.log"; then
58
+ echo " a row still disagrees -- REFUSING"; rc=4
59
+ fi
60
+ n=$(grep -cE '^\s*\|' "$S/fixed_README.md"); f=$(grep -c '^```' "$S/fixed_README.md")
61
+ echo " table rows=$n code fences=$f (even=$([ $((f%2)) -eq 0 ] && echo yes || echo NO))"
62
+ [ $((f%2)) -eq 0 ] || rc=4
63
+ grep -qE '^(<<<<<<<|=======|>>>>>>>)' "$S/fixed_README.md" && { echo " conflict markers!"; rc=4; }
64
+ [ $rc -eq 0 ] || { echo "not pushing"; exit $rc; }
65
+
66
+ hdr "4 commit on both branches, same blob"
67
+ MSG=$(cat <<'EOM'
68
+ openpi README: take #11's per-file table, because it is the one that matches the patch file
69
+
70
+ rsm_real#5. The six-way runbook resolves rise_stack/openpi/README.md by taking this side, so any
71
+ number on this page that is wrong here is a number the merge reinstates. #11's 6c1b8d0 rewrote the
72
+ table; rather than trust either document, scripts/real/patchexport_openpi_numbers.py parses
73
+ rise_stack/openpi/rise_on_pi05.patch and counts the +/- lines per file (LSF 1900991):
74
+
75
+ measured: 9 files, 1,185 insertions, 21 deletions
76
+ this side, before: 5 of 7 rows wrong -- train.py +232 (224), model.py +39 (32),
77
+ data_loader.py +158 (156), optimizer.py +41 (39), weight_loaders.py +11 (9)
78
+ #11: 9 of 9 rows right
79
+
80
+ So the table, the "and 21 deletions" headline and the note naming
81
+ tests/test_rise_stack_openpi_patch_numbers.py come from #11 verbatim; every other paragraph on this
82
+ page stays as it is, because #11's document is a shortened rewrite of it everywhere else and the
83
+ run-22 union already measured that (LSF 1898271). The transform is structural -- exactly one table
84
+ and one "* Our changes:" bullet per side or it exits 3 -- and it re-checks that the paragraph on
85
+ regenerating the patch with `git add -A && git diff --cached`, the retrain section and the
86
+ verify_inference_no_split.py pointer all survive.
87
+
88
+ Written identically to patchexport/pi05-bc-inference-sources and patchexport/env-setup: both add this
89
+ file, and they merge cleanly with each other only while the blob is the same. Verified by
90
+ git hash-object on both working copies and both committed trees before either is pushed.
91
+
92
+ Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
93
+ EOM
94
+ )
95
+ for wt in "$WT_SETUP" "$WT_MAIN"; do
96
+ cp "$S/fixed_README.md" "$wt/rise_stack/openpi/README.md"
97
+ git -C "$wt" add rise_stack/openpi/README.md
98
+ done
99
+ X=$(git hash-object "$WT_SETUP/rise_stack/openpi/README.md"); Y=$(git hash-object "$WT_MAIN/rise_stack/openpi/README.md")
100
+ echo " worktree blobs ${X:0:10} / ${Y:0:10}"
101
+ [ "$X" = "$Y" ] || { echo " BLOBS DIFFER -- refusing"; exit 2; }
102
+ for wt in "$WT_SETUP" "$WT_MAIN"; do
103
+ git -C "$wt" commit -q -m "$MSG" || { echo "commit failed in $wt"; exit 2; }
104
+ echo " $(git -C "$wt" rev-parse --abbrev-ref HEAD) -> $(git -C "$wt" rev-parse --short HEAD)"
105
+ done
106
+ X=$(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)
107
+ echo " committed blobs ${X:0:10} / ${Y:0:10}"
108
+ [ "$X" = "$Y" ] || { echo " COMMITTED BLOBS DIFFER -- not pushing"; exit 2; }
109
+
110
+ hdr "5 trial five-way merge"
111
+ T=$(mktemp -d /proj/dmfexp/zwhong/scratch_patchexport/readmemerge.XXXXXX)
112
+ git clone --quiet --shared --no-checkout "$WT_SETUP" "$T/r" 2>/dev/null
113
+ git -C "$T/r" fetch --quiet "$WT_SETUP" HEAD:local-setup
114
+ git -C "$T/r" fetch --quiet "$WT_MAIN" HEAD:local-main
115
+ git -C "$T/r" fetch --quiet "$WT_SETUP" refs/remotes/origin/main:local-mainline
116
+ git -C "$T/r" checkout --quiet -b trial local-mainline
117
+ git -C "$T/r" config user.email noreply@anthropic.com; git -C "$T/r" config user.name "readme merge trial"
118
+ 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
119
+ echo " #6 then #10: MERGED CLEAN"
120
+ else
121
+ echo " TRIAL MERGE CONFLICTED"; git -C "$T/r" diff --name-only --diff-filter=U; rc=5
122
+ fi
123
+ rm -rf "$T"
124
+ [ $rc -eq 0 ] || { echo "not pushing"; exit $rc; }
125
+
126
+ hdr "6 push"
127
+ if [ "$DO_PUSH" = "1" ]; then
128
+ git -C "$WT_MAIN" push origin HEAD:patchexport/pi05-bc-inference-sources 2>&1 | scrub || rc=2
129
+ git -C "$WT_SETUP" push origin HEAD:patchexport/env-setup 2>&1 | scrub || rc=2
130
+ else
131
+ echo " DO_PUSH=0 -- committed locally only"
132
+ fi
133
+ hdr "OVERALL rc=$rc"
134
+ exit $rc
rsm_rise/scripts/real/patchexport_order_cost.sh ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # rsm_real#5 -- what does the OTHER merge order cost?
3
+ #
4
+ # My published recommendation on #5 is: main -> #6 -> #7 -> #8 -> #9 -> #10 -> #11(scaffold).
5
+ # In that order the whole reconciliation is ONE hand-resolution of 5 add/add files (measured, runs
6
+ # 10-11). But a human looking at the PR list is at least as likely to merge #11 FIRST -- it is the
7
+ # biggest PR, it is the successor of the already-merged #1, and its title is the product goal.
8
+ # Nobody has measured that order. If merging #11 first turns one 5-file resolution into five
9
+ # separate ones, that is decision-relevant BEFORE the button is clicked, not after.
10
+ #
11
+ # Method, chosen so that nothing is invented: I do NOT auto-resolve conflicts and then keep merging
12
+ # on top of a tree I made up. Instead:
13
+ # base B = main + #11 (expected clean; GitHub reports #11 mergeable_state=clean)
14
+ # for each N in 6..10: fresh branch from B, merge pr-N, record its conflict set independently.
15
+ # Each number is then a real measurement against a well-defined base. Caveat recorded in the output:
16
+ # these are per-PR independent costs; a human resolving #6 first may reduce #7's set where the two
17
+ # overlap, so the SUM is an upper bound and the OVERLAP table is what says how much it can shrink.
18
+ #
19
+ # Read-only w.r.t. every real repo: fetches main and pull/N/head from GitHub. Pushes nothing,
20
+ # writes nothing outside SCRATCH.
21
+ set -uo pipefail
22
+ SCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run17}
23
+ PRS=${PRS:-"6 7 8 9 10"}
24
+ SC_PR=${SC_PR:-11}
25
+ export GIT_TERMINAL_PROMPT=0
26
+ scrub(){ sed 's#https://[^@]*@#https://<redacted>@#g'; }
27
+ hdr(){ echo; echo "=================== $* ==================="; date -u; }
28
+ rc_all=0
29
+ mkdir -p "${SCRATCH:?}" || exit 1
30
+ M=$SCRATCH/ordercost
31
+
32
+ hdr "0 context"
33
+ echo "host=$(hostname) job=${LSB_JOBID:-none} scratch=$SCRATCH prs='$PRS' sc_pr=#$SC_PR"
34
+
35
+ hdr "1 fresh clone of main"
36
+ TOK=$(grep -m1 'https://richardrl:' ~/.git-credentials | sed -E 's|https://richardrl:([^@]*)@.*|\1|')
37
+ [ -n "$TOK" ] || { echo "NO TOKEN"; exit 1; }
38
+ rm -rf "${M:?}"; git init --quiet "$M" || exit 1
39
+ printf '[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"
40
+ unset TOK
41
+ git -C "$M" fetch --quiet origin main 2>&1 | scrub
42
+ git -C "$M" checkout --quiet -b main FETCH_HEAD 2>&1 | scrub
43
+ [ -f "$M/README.md" ] || { echo "CLONE/FETCH FAILED"; exit 1; }
44
+ git -C "$M" config user.email noreply@anthropic.com
45
+ git -C "$M" config user.name "order cost gate"
46
+ echo "main = $(git -C "$M" rev-parse --short HEAD) $(git -C "$M" log -1 --pretty=%s)"
47
+
48
+ hdr "2 fetch every PR head"
49
+ for n in $PRS $SC_PR; do
50
+ git -C "$M" fetch --quiet origin "pull/$n/head:pr-$n" 2>&1 | scrub
51
+ sha=$(git -C "$M" rev-parse --short "pr-$n" 2>/dev/null)
52
+ [ -n "$sha" ] || { echo " #$n FETCH FAILED"; exit 1; }
53
+ echo " #$n = $sha"
54
+ done
55
+
56
+ # classify one conflicted path: marker count, and whether the two sides are the same blob
57
+ # (a stage-conflicted file with 0 markers is a MODE conflict, not an edit conflict)
58
+ classify(){ # $1=repo $2=path
59
+ local r=$1 p=$2 mk ours theirs om tm
60
+ mk=$(grep -c '^<<<<<<<' "$r/$p" 2>/dev/null); [ -n "$mk" ] || mk=0
61
+ ours=$(git -C "$r" ls-files -u -- "$p" | awk '$3==2{print $2}' | head -1)
62
+ theirs=$(git -C "$r" ls-files -u -- "$p" | awk '$3==3{print $2}' | head -1)
63
+ om=$(git -C "$r" ls-files -u -- "$p" | awk '$3==2{print $1}' | head -1)
64
+ tm=$(git -C "$r" ls-files -u -- "$p" | awk '$3==3{print $1}' | head -1)
65
+ if [ -n "$ours" ] && [ "$ours" = "$theirs" ]; then
66
+ echo "$p|markers=$mk|SAME BLOB ${ours:0:10}|mode ours=$om theirs=$tm|MODE-ONLY"
67
+ else
68
+ echo "$p|markers=$mk|ours=${ours:0:10} theirs=${theirs:0:10}|mode ours=$om theirs=$tm|EDIT"
69
+ fi
70
+ }
71
+
72
+ hdr "3 ORDER B step 1: main + #$SC_PR (the base a human creates by merging the scaffold PR first)"
73
+ git -C "$M" checkout --quiet -b orderB main
74
+ if git -C "$M" merge --no-ff -m "Merge PR #$SC_PR" "pr-$SC_PR" >/dev/null 2>&1; then
75
+ echo " #$SC_PR MERGED CLEAN -> base B = $(git -C "$M" rev-parse --short HEAD)"
76
+ else
77
+ echo " #$SC_PR CONFLICTS (unexpected -- GitHub says clean):"
78
+ git -C "$M" diff --name-only --diff-filter=U | sed 's/^/ /'
79
+ git -C "$M" merge --abort; rc_all=1
80
+ fi
81
+ BASEB=$(git -C "$M" rev-parse HEAD)
82
+ echo " base B tree = $(git -C "$M" rev-parse --short HEAD^{tree})"
83
+
84
+ hdr "4 ORDER B step 2: each of #$PRS merged into base B, measured INDEPENDENTLY"
85
+ SUM=0
86
+ : > "$SCRATCH/orderB_sets.txt"
87
+ for n in $PRS; do
88
+ git -C "$M" checkout --quiet -B "tryB-$n" "$BASEB"
89
+ git -C "$M" reset --hard --quiet "$BASEB"
90
+ if git -C "$M" merge --no-ff -m "Merge PR #$n into B" "pr-$n" >/dev/null 2>&1; then
91
+ echo " #$n -> MERGED CLEAN (0 files to resolve)"
92
+ else
93
+ files=$(git -C "$M" diff --name-only --diff-filter=U)
94
+ cnt=$(printf '%s\n' "$files" | grep -c . )
95
+ echo " #$n -> $cnt file(s) to resolve:"
96
+ while IFS= read -r p; do
97
+ [ -n "$p" ] || continue
98
+ echo " $(classify "$M" "$p")"
99
+ echo "$n|$p" >> "$SCRATCH/orderB_sets.txt"
100
+ done <<< "$files"
101
+ SUM=$((SUM+cnt))
102
+ git -C "$M" merge --abort
103
+ fi
104
+ done
105
+ echo " ORDER B independent total = $SUM file-resolutions (upper bound; see overlap below)"
106
+
107
+ hdr "5 overlap across ORDER B conflict sets -- how much sequential resolution can shrink the sum"
108
+ if [ -s "$SCRATCH/orderB_sets.txt" ]; then
109
+ python3 - "$SCRATCH/orderB_sets.txt" <<'PY'
110
+ import sys, collections
111
+ d=collections.defaultdict(list)
112
+ for line in open(sys.argv[1]):
113
+ line=line.strip()
114
+ if not line: continue
115
+ n,p=line.split('|',1)
116
+ d[p].append(n)
117
+ print(f" {'file':60s} appears in PRs")
118
+ for p,ns in sorted(d.items(), key=lambda kv:(-len(kv[1]),kv[0])):
119
+ print(f" {p:60s} {','.join('#'+x for x in ns)} (x{len(ns)})")
120
+ print(f"\n DISTINCT files needing resolution in order B = {len(d)}")
121
+ print(f" sum over PRs = {sum(len(v) for v in d.values())}")
122
+ PY
123
+ else
124
+ echo " (no conflicts recorded)"
125
+ fi
126
+
127
+ hdr "6 ORDER A for comparison: #$PRS first, then #$SC_PR"
128
+ git -C "$M" checkout --quiet -B orderA main
129
+ git -C "$M" reset --hard --quiet main
130
+ ok=1
131
+ for n in $PRS; do
132
+ if git -C "$M" merge --no-ff -m "Merge PR #$n" "pr-$n" >/dev/null 2>&1; then
133
+ echo " #$n MERGED CLEAN"
134
+ else
135
+ echo " #$n CONFLICTS:"; git -C "$M" diff --name-only --diff-filter=U | sed 's/^/ /'
136
+ git -C "$M" merge --abort; ok=0; rc_all=1; break
137
+ fi
138
+ done
139
+ if [ "$ok" = 1 ]; then
140
+ echo " five-way result = $(git -C "$M" rev-parse --short HEAD) tree $(git -C "$M" rev-parse --short HEAD^{tree})"
141
+ if git -C "$M" merge --no-ff -m "Merge PR #$SC_PR" "pr-$SC_PR" >/dev/null 2>&1; then
142
+ echo " #$SC_PR MERGED CLEAN (0 files to resolve)"
143
+ else
144
+ files=$(git -C "$M" diff --name-only --diff-filter=U)
145
+ cnt=$(printf '%s\n' "$files" | grep -c .)
146
+ echo " #$SC_PR -> $cnt file(s) to resolve:"
147
+ while IFS= read -r p; do
148
+ [ -n "$p" ] || continue
149
+ echo " $(classify "$M" "$p")"
150
+ done <<< "$files"
151
+ echo " ORDER A total = $cnt file-resolutions, in ONE merge"
152
+ git -C "$M" merge --abort
153
+ fi
154
+ fi
155
+
156
+ hdr "7 verdict"
157
+ echo "rc_all=$rc_all"
158
+ echo "Compare: ORDER A total (one merge) vs ORDER B distinct/sum (five merges) above."
159
+ exit 0
rsm_rise/scripts/real/patchexport_owner_handoff.sh ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # rsm_real#5 run 26 -- the owner shipped his OWN installer to main (54c054e, 2026-09-24 19:03-19:11Z)
3
+ # and it consumes THIS STREAM'S export by pinned revision + sha256:
4
+ #
5
+ # real/scripts/setup_bc.py:
6
+ # OPENPI_REVISION = 215abfb217dbac7d5f1273282331b9b1866c0479
7
+ # HANDOFF_REVISION = a373756093472e145072bb9e3cfef3151022e0d8 <- our commit, PR #6/#10
8
+ # PATCH_SHA256 = 33b37d55...8fec4
9
+ # git show $HANDOFF_REVISION:rise_stack/openpi/rise_on_pi05.patch -> verify sha256 -> git apply
10
+ # then apply requirements/openpi-real.patch (his: makes ALOHA sim optional)
11
+ #
12
+ # So issue #5's deliverable is no longer "a PR the owner might read": it is an EXECUTED dependency of
13
+ # his deployment installer. This script runs that dependency path -- and only that path -- for real:
14
+ # no conda, no pip, no checkpoint download, nothing outside $SCRATCH. Read-only w.r.t. GitHub.
15
+ set -uo pipefail
16
+ SCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run81}
17
+ ROOT=/proj/dmfexp/zwhong/rsm_rise
18
+ VENV=${VENV:-/proj/dmfexp/zwhong/scratch_patchexport/run29/venv_ci}
19
+ OPENPI_REVISION=215abfb217dbac7d5f1273282331b9b1866c0479
20
+ HANDOFF_REVISION=a373756093472e145072bb9e3cfef3151022e0d8
21
+ PATCH_SHA256=33b37d559c31823fc350fb15e4216a062273550fd580f890eaf1626063a8fec4
22
+ export GIT_TERMINAL_PROMPT=0 PYTHONDONTWRITEBYTECODE=1
23
+ scrub(){ sed 's#https://[^@]*@#https://<redacted>@#g'; }
24
+ hdr(){ echo; echo "=================== $* ==================="; date -u; }
25
+ rc_all=0
26
+ fail(){ echo "!! $*"; rc_all=1; }
27
+ PY=$VENV/bin/python; [ -x "$PY" ] || PY=$(command -v python3)
28
+ mkdir -p "${SCRATCH:?}" || exit 1
29
+
30
+ hdr "0 context"
31
+ echo "host=$(hostname) job=${LSB_JOBID:-none} scratch=$SCRATCH py=$PY ($($PY -V 2>&1))"
32
+
33
+ TOK=$(grep -m1 'https://richardrl:' ~/.git-credentials | sed -E 's|https://richardrl:([^@]*)@.*|\1|')
34
+ [ -n "$TOK" ] || { echo "NO TOKEN"; exit 1; }
35
+ URL="https://richardrl:$TOK@github.com/jmarangola/rsm_real.git"
36
+
37
+ hdr "1 a DEFAULT clone of rsm_real -- can the installer reach HANDOFF_REVISION?"
38
+ D=$SCRATCH/full; rm -rf "${D:?}"
39
+ git clone --quiet "$URL" "$D" 2>&1 | scrub
40
+ echo " main = $(git -C "$D" rev-parse --short HEAD) $(git -C "$D" log -1 --format=%s | cut -c1-60)"
41
+ echo " branches fetched: $(git -C "$D" branch -r | wc -l)"
42
+ if git -C "$D" cat-file -e "$HANDOFF_REVISION" 2>/dev/null; then
43
+ echo " cat-file -e HANDOFF_REVISION: OK (no fetch needed -- the PR branches live in this repo)"
44
+ else
45
+ fail "cat-file -e HANDOFF_REVISION: MISSING in a default clone"
46
+ fi
47
+ echo -n " is it an ancestor of main? "
48
+ git -C "$D" merge-base --is-ancestor "$HANDOFF_REVISION" HEAD 2>/dev/null && echo "YES" || echo "NO <- it lives only on the PR branches"
49
+ echo -n " reachable from which branches: "
50
+ git -C "$D" branch -r --contains "$HANDOFF_REVISION" 2>/dev/null | tr -d ' ' | tr '\n' ' '; echo
51
+
52
+ hdr "2 the installer's OWN fallback: a single-branch clone, then git fetch origin <sha>"
53
+ S=$SCRATCH/single; rm -rf "${S:?}"
54
+ git clone --quiet --single-branch --branch main "$URL" "$S" 2>&1 | scrub
55
+ echo -n " cat-file -e before fetch: "
56
+ git -C "$S" cat-file -e "$HANDOFF_REVISION" 2>/dev/null && echo "present" || echo "ABSENT (expected -- this is the branch setup_bc.py takes)"
57
+ git -C "$S" fetch --quiet origin "$HANDOFF_REVISION" 2>&1 | scrub; fr=${PIPESTATUS[0]}
58
+ echo " git fetch origin \$HANDOFF_REVISION -> rc=$fr"
59
+ if [ "$fr" -eq 0 ] && git -C "$S" cat-file -e "$HANDOFF_REVISION" 2>/dev/null; then
60
+ echo " FALLBACK WORKS: the sha is fetchable by sha from a single-branch clone"
61
+ else
62
+ fail "FALLBACK BROKEN: setup_bc.py cannot obtain the cooking patch from a single-branch clone"
63
+ fi
64
+
65
+ hdr "3 the patch payload and its pinned sha256"
66
+ git -C "$S" show "$HANDOFF_REVISION:rise_stack/openpi/rise_on_pi05.patch" > "$SCRATCH/cooking.patch" 2>/dev/null || fail "git show failed"
67
+ got=$(sha256sum "$SCRATCH/cooking.patch" | cut -d' ' -f1)
68
+ echo " payload = $(wc -l < "$SCRATCH/cooking.patch") lines, sha256 $got"
69
+ [ "$got" = "$PATCH_SHA256" ] && echo " MATCHES setup_bc.py's PATCH_SHA256" || fail "sha256 MISMATCH: want $PATCH_SHA256"
70
+ echo -n " is the item-1 inference fix inside it? episodes_required_from x"; grep -c 'episodes_required_from' "$SCRATCH/cooking.patch"
71
+ 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"
72
+ git -C "$D" show "54c054e:requirements/openpi-real.patch" > "$SCRATCH/hardware.patch" 2>/dev/null || fail "no requirements/openpi-real.patch on main"
73
+ echo " his hardware patch = $(wc -l < "$SCRATCH/hardware.patch") lines"
74
+
75
+ hdr "4 a clean openpi at the pinned revision (from our local mirror, offline)"
76
+ O=$SCRATCH/openpi; rm -rf "${O:?}"
77
+ git clone --quiet --no-local "$ROOT/third_party/openpi" "$O" 2>&1 | scrub
78
+ git -C "$O" checkout --quiet --detach "$OPENPI_REVISION" 2>&1 | scrub || fail "cannot check out $OPENPI_REVISION"
79
+ echo " HEAD = $(git -C "$O" rev-parse HEAD)"
80
+ [ "$(git -C "$O" rev-parse HEAD)" = "$OPENPI_REVISION" ] || fail "openpi HEAD != OPENPI_REVISION"
81
+ 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"; }
82
+
83
+ # setup_bc.py's apply_once(), reimplemented exactly
84
+ apply_once(){ local src=$1 p=$2 label=$3
85
+ if git -C "$src" apply --reverse --check "$p" >/dev/null 2>&1; then
86
+ echo " $label: ALREADY APPLIED (reverse-check passed) -> no-op"; return 0
87
+ fi
88
+ git -C "$src" apply --check "$p" 2>&1 | sed 's/^/ /'; local c=${PIPESTATUS[0]}
89
+ echo " $label: git apply --check rc=$c"
90
+ [ "$c" -eq 0 ] || { fail "$label does not apply"; return 1; }
91
+ git -C "$src" apply "$p" 2>&1 | sed 's/^/ /'; local a=${PIPESTATUS[0]}
92
+ echo " $label: git apply rc=$a"; [ "$a" -eq 0 ] || fail "$label apply failed"
93
+ return $a
94
+ }
95
+
96
+ hdr "5 apply, in setup_bc.py's order: our cooking patch, then his hardware patch"
97
+ apply_once "$O" "$SCRATCH/cooking.patch" "cooking (ours, $HANDOFF_REVISION)"
98
+ apply_once "$O" "$SCRATCH/hardware.patch" "hardware (his, requirements/openpi-real.patch)"
99
+
100
+ hdr "6 idempotency -- setup_bc.py is re-runnable, so apply_once must no-op the second time"
101
+ apply_once "$O" "$SCRATCH/cooking.patch" "cooking 2nd"
102
+ apply_once "$O" "$SCRATCH/hardware.patch" "hardware 2nd"
103
+
104
+ hdr "7 post-conditions on the installed tree"
105
+ f=$O/src/openpi/policies/cooking_policy.py
106
+ [ -f "$f" ] && echo " cooking_policy.py present ($(wc -l < "$f") lines)" || fail "cooking_policy.py MISSING after apply"
107
+ echo -n " config.py carries the inference fix: "
108
+ grep -c 'episodes_required_from' "$O/src/openpi/training/config.py" 2>/dev/null || fail "episodes_required_from absent"
109
+ # NB: the first version of this check grepped for `exists()` / `is_file()` -- literal empty parens,
110
+ # which the real call `os.path.exists(self.split_json)` can never match. It reported 0 against
111
+ # correct code (LSF 1904259). Assert on the guard's STRUCTURE instead, and require the body to be
112
+ # the one the fix documents: the no-split branch must return None rather than raise.
113
+ echo " episode_subset() guards the split file:"
114
+ $PY - "$O/src/openpi/training/config.py" <<'PYEOF' || fail "episode_subset guard not found"
115
+ import ast, sys
116
+ src = open(sys.argv[1]).read()
117
+ fn = next(n for n in ast.walk(ast.parse(src))
118
+ if isinstance(n, ast.FunctionDef) and n.name == "episode_subset")
119
+ body = ast.get_source_segment(src, fn)
120
+ guard = [n for n in ast.walk(fn) if isinstance(n, ast.If)
121
+ and "exists" in ast.dump(n.test) and "split_json" in ast.dump(n.test)]
122
+ assert guard, "no `if not <...>exists(<...>split_json)` guard in episode_subset"
123
+ g = guard[0]
124
+ rets = [n for n in ast.walk(g) if isinstance(n, ast.Return)]
125
+ raises = [n for n in ast.walk(g) if isinstance(n, ast.Raise)]
126
+ assert rets and all(isinstance(r.value, ast.Constant) and r.value.value is None for r in rets), \
127
+ "the missing-split branch does not return None"
128
+ assert not raises, "the missing-split branch still raises"
129
+ warns = [n for n in ast.walk(g) if isinstance(n, ast.Call)
130
+ and getattr(getattr(n.func, "attr", None), "lower", lambda: "")() == "warning"]
131
+ print(" guard present at line %d; missing split -> return None, no raise, warning=%s"
132
+ % (g.lineno, bool(warns)))
133
+ PYEOF
134
+ echo " pyproject, after his patch:"
135
+ $PY - "$O/pyproject.toml" <<'EOF' || exit_code=1
136
+ import sys, tomllib
137
+ d = tomllib.load(open(sys.argv[1], 'rb'))
138
+ base = d['project']['dependencies']
139
+ opt = d['project'].get('optional-dependencies', {})
140
+ ga_base = [x for x in base if 'gym-aloha' in x]
141
+ ga_opt = {k: [x for x in v if 'gym-aloha' in x] for k, v in opt.items()}
142
+ print(" parses OK; %d base deps" % len(base))
143
+ print(" gym-aloha in base deps :", ga_base or "NO (his patch removed it)")
144
+ print(" gym-aloha in optional-deps :", {k: v for k, v in ga_opt.items() if v} or "NO")
145
+ print(" optional-dependency groups :", sorted(opt))
146
+ assert not ga_base, "gym-aloha still a hard dependency -- MuJoCo <3 would fight aiofranka 0.4"
147
+ assert ga_opt.get('simulation'), "no [project.optional-dependencies] simulation group"
148
+ EOF
149
+ [ $? -eq 0 ] || fail "pyproject post-condition failed"
150
+
151
+ hdr "8 informative: does his patch also apply BEFORE ours? (order-independence)"
152
+ O2=$SCRATCH/openpi_rev; rm -rf "${O2:?}"
153
+ git clone --quiet --no-local "$ROOT/third_party/openpi" "$O2" 2>&1 | scrub
154
+ git -C "$O2" checkout --quiet --detach "$OPENPI_REVISION" 2>&1 | scrub
155
+ git -C "$O2" apply --check "$SCRATCH/hardware.patch" 2>&1 | sed 's/^/ /'; a=${PIPESTATUS[0]}
156
+ git -C "$O2" apply "$SCRATCH/hardware.patch" >/dev/null 2>&1
157
+ git -C "$O2" apply --check "$SCRATCH/cooking.patch" 2>&1 | sed 's/^/ /'; b=${PIPESTATUS[0]}
158
+ echo " hardware-then-cooking: hardware --check rc=$a, cooking --check rc=$b (informative only; the installer's order is 5)"
159
+
160
+ hdr "9 do the owner's pinned constants agree with the pins WE recorded?"
161
+ $PY - "$D" "$SCRATCH" <<'EOF'
162
+ import re, subprocess, sys
163
+ repo, scratch = sys.argv[1], sys.argv[2]
164
+ def show(rev, path):
165
+ try: return subprocess.check_output(["git","-C",repo,"show",f"{rev}:{path}"],text=True,stderr=subprocess.DEVNULL)
166
+ except Exception: return ""
167
+ bc = show("54c054e","real/scripts/setup_bc.py")
168
+ rsm = show("54c054e","real/scripts/setup_rsm.py")
169
+ def const(src, name):
170
+ m = re.search(rf'^{name}\s*=\s*"([^"]+)"', src, re.M); return m.group(1) if m else None
171
+ his = {"openpi": const(bc,"OPENPI_REVISION"),
172
+ "gen_q": const(rsm,"GEN_Q_REVISION"),
173
+ "dinov2": const(rsm,"DINO_REVISION")}
174
+ ours = {}
175
+ ours["openpi"] = show("5a0c682","rise_stack/openpi/UPSTREAM_COMMIT.txt").split("\n")[0].strip()
176
+ lib = show("5a0c682","rise_stack/rsm_libero/UPSTREAM_COMMIT.txt")
177
+ for key, pat in (("gen_q", r'^commit\s*=\s*(\S+)'), ("dinov2", r'^dino_commit\s*=\s*(\S+)')):
178
+ m = re.search(pat, lib, re.M); ours[key] = m.group(1) if m else None
179
+ bad = 0
180
+ for k in ("openpi","gen_q","dinov2"):
181
+ ok = his[k] == ours[k] and his[k]
182
+ print(f" {k:8s} his={his[k]} ours={ours[k]} {'AGREE' if ok else 'DISAGREE'}")
183
+ bad += 0 if ok else 1
184
+ print(" PIN CROSS-CHECK:", "OK -- three independently written pins agree" if not bad else f"{bad} DISAGREE")
185
+ sys.exit(1 if bad else 0)
186
+ EOF
187
+ [ $? -eq 0 ] || fail "pin cross-check disagreed"
188
+
189
+ hdr "OVERALL rc=$rc_all"
190
+ exit $rc_all
rsm_rise/scripts/real/patchexport_pi05_infer.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """rsm_real#5 item 1: dump stock pi0.5 BC actions for a few replay frames from ONE openpi source tree.
3
+
4
+ Run once per source tree (pre-fix patch / post-fix patch) and compare the npz files bit-for-bit.
5
+ The policy rng is jax.random.key(0) split per infer() call (openpi/policies/policy.py:65), so the
6
+ action sequence is a deterministic function of (weights, transforms, frames, call order).
7
+
8
+ python patchexport_pi05_infer.py --src <tree>/src --ckpt <ckpt dir> --out a.npz [--split-json PATH]
9
+
10
+ --split-json overrides LeRobotCookingDataConfig.split_json, which is how the deployment case (the
11
+ training split file simply not present) is exercised: point it at a path that does not exist.
12
+ """
13
+ import argparse, dataclasses, json, sys, time
14
+ from pathlib import Path
15
+
16
+ import numpy as np
17
+
18
+ ROOT = "/proj/dmfexp/zwhong/rsm_rise"
19
+ DATA = f"{ROOT}/data/real/rsm_cooking_v5"
20
+ PROMPT = "Follow the displayed cooking state sequence"
21
+
22
+
23
+ def decode_upto(path, last):
24
+ """Decode frames 0..last inclusive and return them stacked (avoids decoding a whole episode)."""
25
+ import av
26
+ out = []
27
+ with av.open(str(path)) as c:
28
+ st = c.streams.video[0]
29
+ st.thread_type = "AUTO"
30
+ for i, fr in enumerate(c.decode(st)):
31
+ out.append(fr.to_ndarray(format="rgb24"))
32
+ if i >= last:
33
+ break
34
+ return np.stack(out)
35
+
36
+
37
+ def main():
38
+ ap = argparse.ArgumentParser()
39
+ ap.add_argument("--src", required=True, help="openpi source dir to put FIRST on sys.path")
40
+ ap.add_argument("--ckpt", required=True)
41
+ ap.add_argument("--out", required=True)
42
+ ap.add_argument("--config", default="pi05_cooking_stock")
43
+ ap.add_argument("--ep", type=int, default=0)
44
+ ap.add_argument("--stride", type=int, default=10)
45
+ ap.add_argument("--frames", type=int, default=8)
46
+ ap.add_argument("--horizon", type=int, default=10)
47
+ ap.add_argument("--split-json", default=None, help="override split_json (use a missing path to "
48
+ "simulate a deployment machine)")
49
+ args = ap.parse_args()
50
+
51
+ src = str(Path(args.src).resolve())
52
+ sys.path.insert(0, src)
53
+ import openpi
54
+ got = str(Path(openpi.__file__).resolve())
55
+ print(f"[infer] openpi.__file__ = {got}", flush=True)
56
+ if not got.startswith(src):
57
+ # the venv installs the research fork editable via a .pth; if that won this test is void
58
+ raise SystemExit(f"FATAL: imported openpi from {got}, not from {src}")
59
+ import jax
60
+ print(f"[infer] jax {jax.__version__} devices={jax.devices()}", flush=True)
61
+
62
+ from openpi.policies import policy_config as _policy_config
63
+ from openpi.training import config as _config
64
+
65
+ cfg = _config.get_config(args.config)
66
+ note = "default"
67
+ if args.split_json is not None:
68
+ cfg = dataclasses.replace(cfg, data=dataclasses.replace(cfg.data, split_json=args.split_json))
69
+ note = f"split_json={args.split_json} exists={Path(args.split_json).exists()}"
70
+ print(f"[infer] config={args.config} data={type(cfg.data).__name__} {note}", flush=True)
71
+
72
+ # the acceptance check: build the inference transforms the way create_trained_policy does
73
+ t0 = time.time()
74
+ dc = cfg.data.create(cfg.assets_dirs, cfg.model)
75
+ eps = dc.episodes
76
+ print(f"[infer] data.create() OK in {time.time()-t0:.2f}s episodes="
77
+ f"{'None' if eps is None else f'{len(eps)} ids, first {list(eps)[:5]}'} "
78
+ f"episodes_required_from={getattr(dc, 'episodes_required_from', '<field absent>')}", flush=True)
79
+ print(f"[infer] norm_stats keys={sorted(dc.norm_stats) if dc.norm_stats else None} asset_id={dc.asset_id}",
80
+ flush=True)
81
+
82
+ policy = _policy_config.create_trained_policy(cfg, args.ckpt)
83
+ print(f"[infer] policy built in {time.time()-t0:.1f}s", flush=True)
84
+
85
+ import pyarrow.parquet as pq
86
+ tab = pq.read_table(f"{DATA}/data/chunk-000/episode_{args.ep:06d}.parquet").to_pandas()
87
+ S = np.stack(tab["observation.state"].values).astype(np.float32)
88
+ A = np.stack(tab["action"].values).astype(np.float32)
89
+ T = len(tab)
90
+ idxs = [i for i in range(0, T - args.horizon, args.stride)][: args.frames]
91
+ last = max(idxs)
92
+ g = decode_upto(f"{DATA}/videos/chunk-000/observation.images.global/episode_{args.ep:06d}.mp4", last)
93
+ w = decode_upto(f"{DATA}/videos/chunk-000/observation.images.wrist/episode_{args.ep:06d}.mp4", last)
94
+ print(f"[infer] ep {args.ep} T={T} frames={idxs} imgs={g.shape}/{w.shape}", flush=True)
95
+
96
+ preds = []
97
+ for k, i in enumerate(idxs):
98
+ obs = {"observation/image": g[i], "observation/wrist_image": w[i],
99
+ "observation/state": S[i], "prompt": PROMPT}
100
+ t1 = time.time()
101
+ pred = np.asarray(policy.infer(obs)["actions"])[: args.horizon, :10]
102
+ preds.append(pred)
103
+ print(f"[infer] frame {i} ({k+1}/{len(idxs)}) {time.time()-t1:.1f}s "
104
+ f"a0={np.array2string(pred[0], precision=8)}", flush=True)
105
+ # write after every frame so a truncated run is still comparable
106
+ np.savez(args.out, pred=np.stack(preds), idx=np.array(idxs[: len(preds)]),
107
+ gt=np.stack([A[i: i + args.horizon] for i in idxs[: len(preds)]]))
108
+ P = np.stack(preds)
109
+ print(f"[infer] wrote {args.out} pred{P.shape} dtype={P.dtype} "
110
+ f"sha=({float(P.sum()):.10g}) xyz_first_l2_cm="
111
+ f"{100*float(np.linalg.norm((P-np.stack([A[i:i+args.horizon] for i in idxs]))[:,0,:3],axis=-1).mean()):.3f}",
112
+ flush=True)
113
+ json.dump({"src": src, "openpi_file": got, "config": args.config, "ckpt": args.ckpt,
114
+ "split_json": args.split_json, "episodes": (None if eps is None else len(eps)),
115
+ "ep": args.ep, "idxs": idxs, "shape": list(P.shape), "dtype": str(P.dtype)},
116
+ open(args.out + ".json", "w"), indent=1)
117
+
118
+
119
+ if __name__ == "__main__":
120
+ main()
rsm_rise/scripts/real/patchexport_pins_doc_fix_push.sh ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # SUPERSEDED 2026-09-24 (run 28): this gate trial-merges a SUBSET, not main + #6..#10 + #11.
3
+ # That hole is a measured failure of this stream -- LSF 1902702 caught a conflict AFTER a push whose
4
+ # gate merged only `main -> #6 -> #10`. Do not reuse this script for a new push. Copy
5
+ # scripts/real/patchexport_readme_dedupe_push.sh instead: it does the full merge with pe_resolve, runs
6
+ # #11's control ledger on the merged tree, and diffs pytest against a baseline MEASURED on main alone
7
+ # rather than against a hardcoded expectation.
8
+ # rsm_real#5 run 25 -- repair a conflict THIS STREAM introduced, and close the gate hole that let it out.
9
+ #
10
+ # 9605cfc (LSF 1902365) rewrote two rows of rise_stack/UPSTREAM_PINS.md on #10: `diffusion_policy`
11
+ # (line 13) and DINOv2 (line 18). PR #9 rewrites the mimicgen row (line 19). The two edits are
12
+ # semantically independent -- different rows of the same table -- but line 18 and line 19 are
13
+ # ADJACENT, so git's three-way merge cannot separate them and the five-way merge of #6..#10 now
14
+ # conflicts (LSF 1902702: "#10 9605cfc CONFLICTS: rise_stack/UPSTREAM_PINS.md").
15
+ #
16
+ # Why the push gate missed it: its step 8 trial merge was `main -> #6 -> #10` only. #7, #8 and #9
17
+ # were never in the trial, and #9 is the branch that collides. A trial merge that omits branches is
18
+ # the same class of defect as a check that never reaches its comparison -- it passes by not looking.
19
+ # Step 4 below is now the FULL five-way, and step 5 the six-way with #11.
20
+ #
21
+ # The fix keeps every fact and moves the DINOv2 sentence off the adjacent row: the `diffusion_policy`
22
+ # row keeps its inline link (line 13 is 5 lines from the collision and already merged clean), and the
23
+ # DINOv2 note becomes a short paragraph ABOVE the table, 11 lines away from the mimicgen row.
24
+ # Verified with `git merge-file` before this job existed: current #10 -> rc=1, 1 conflict hunk;
25
+ # fixed #10 -> rc=0, 0 markers, and the merged file keeps #9's mimicgen row AND both of our rows.
26
+ set -uo pipefail
27
+ S=${S:-/proj/dmfexp/zwhong/scratch_patchexport/run78}
28
+ WT=${WT:-/proj/dmfexp/zwhong/scratch_patchexport/wt_setup}
29
+ BR=${BR:-patchexport/env-setup}
30
+ DO_PUSH=${DO_PUSH:-0}
31
+ F=rise_stack/UPSTREAM_PINS.md
32
+ export GIT_TERMINAL_PROMPT=0
33
+ scrub(){ sed 's#https://[^@]*@#https://<redacted>@#g'; }
34
+ hdr(){ echo; echo "=================== $* ==================="; date -u; }
35
+ mkdir -p "$S"; rc=0
36
+
37
+ hdr "0 in-sync guard"
38
+ echo "host=$(hostname) job=${LSB_JOBID:-none} do_push=$DO_PUSH"
39
+ [ "$(git -C "$WT" rev-parse --abbrev-ref HEAD)" = "$BR" ] || { echo " wrong branch -- REFUSING"; exit 2; }
40
+ git -C "$WT" fetch --quiet origin "$BR" 2>&1 | scrub || exit 2
41
+ L=$(git -C "$WT" rev-parse HEAD); R=$(git -C "$WT" rev-parse FETCH_HEAD)
42
+ [ "$L" = "$R" ] || { echo " local ${L:0:7} != origin ${R:0:7} -- REFUSING"; exit 2; }
43
+ DIRT=$(git -C "$WT" status --porcelain)
44
+ [ -z "$DIRT" ] || { echo " tree not clean -- REFUSING:"; echo "$DIRT"; exit 2; }
45
+ echo " on $BR @ ${L:0:7}, clean"
46
+
47
+ hdr "1 the transform: DINOv2 row back to its pre-9605cfc text, the note moved above the table"
48
+ python3 - "$WT/$F" <<'PY' || exit 3
49
+ import pathlib, sys, re
50
+ p = pathlib.Path(sys.argv[1]); lines = p.read_text().split("\n")
51
+ dino = [i for i, l in enumerate(lines) if l.startswith("| DINOv2 (image featuriser)")]
52
+ assert len(dino) == 1, f"DINOv2 row appears {len(dino)}x"
53
+ i = dino[0]
54
+ tail = ". The commit is recorded ONCE, as `dino_commit`"
55
+ assert tail in lines[i], "the DINOv2 row does not carry the 9605cfc sentence -- already fixed?"
56
+ lines[i] = lines[i][:lines[i].index(tail)] + " |"
57
+ assert lines[i].count("|") >= 6, lines[i]
58
+ anchor = [j for j, l in enumerate(lines) if l.startswith("`cooking_policy.py` went missing")]
59
+ assert len(anchor) == 1, f"anchor appears {len(anchor)}x"
60
+ note = ["",
61
+ "**Where each pin is recorded.** Every pin above lives in exactly one file,",
62
+ "`rise_stack/<name>/UPSTREAM_COMMIT.txt`, and `scripts/setup_env.sh` and `scripts/check_env.py` both read",
63
+ "it from there rather than carrying a copy -- a script that hardcodes the value it is checking reports a",
64
+ "correctly-cloned tree as wrong the moment the pin moves. DINOv2 is the one exception to the one-file-per-",
65
+ "name rule: its commit is `dino_commit` in [`rise_stack/rsm_libero/UPSTREAM_COMMIT.txt`](rsm_libero/UPSTREAM_COMMIT.txt),",
66
+ "because DINOv2 is the featuriser those checkpoints were built against."]
67
+ lines[anchor[0]+1:anchor[0]+1] = note
68
+ p.write_text("\n".join(lines))
69
+ print(f" DINOv2 row restored (line {i+1}); note inserted after line {anchor[0]+1}")
70
+ PY
71
+ git -C "$WT" --no-pager diff --stat -- "$F" | sed 's/^/ /'
72
+
73
+ hdr "2 every fact that was in 9605cfc is still in the file"
74
+ python3 - "$WT/$F" <<'PY' || rc=4
75
+ import pathlib, sys
76
+ t = pathlib.Path(sys.argv[1]).read_text()
77
+ need = ["diffusion_policy/UPSTREAM_COMMIT.txt", "dino_commit",
78
+ "rsm_libero/UPSTREAM_COMMIT.txt", "scripts/setup_env.sh", "scripts/check_env.py"]
79
+ miss = [n for n in need if n not in t]
80
+ for n in need: print(f" {'ok ' if n not in miss else 'MISSING'} {n}")
81
+ raise SystemExit(1 if miss else 0)
82
+ PY
83
+ [ $rc -eq 0 ] || { echo " a fact was dropped -- REFUSING"; exit $rc; }
84
+
85
+ hdr "3 commit"
86
+ git -C "$WT" add "$F"
87
+ git -C "$WT" commit --quiet -F - <<'EOM'
88
+ Move the DINOv2 pin note off the row that PR #9 also edits
89
+
90
+ rsm_real#5. 9605cfc rewrote two rows of rise_stack/UPSTREAM_PINS.md, `diffusion_policy` and DINOv2.
91
+ PR #9 rewrites the mimicgen row. The two edits are semantically independent -- different rows of the
92
+ same table, describing different dependencies -- but the DINOv2 row and the mimicgen row are ADJACENT
93
+ lines, so git's three-way merge cannot separate them, and the five-way merge of #6..#10 conflicted
94
+ (LSF 1902702). The five-way merge of our own stack must be clean; a conflict between two of our own
95
+ PRs is our problem to remove, not the reviewer's to resolve.
96
+
97
+ Nothing is dropped. The `diffusion_policy` row keeps its inline link to the new pin file -- it is
98
+ five lines from the collision and already merged clean -- and the DINOv2 sentence becomes a short
99
+ "Where each pin is recorded" paragraph above the table, eleven lines from the mimicgen row, which
100
+ says the same thing for every dependency instead of only for DINOv2.
101
+
102
+ Measured with `git merge-file` on the three blobs: the pushed 9605cfc version against #9 gives rc=1
103
+ and one conflict hunk; this version gives rc=0 and zero markers, and the merged file keeps #9's
104
+ rewritten mimicgen row alongside both of ours.
105
+
106
+ The gate that let this out has been fixed in the same run: its trial merge was `main -> #6 -> #10`,
107
+ so #7, #8 and #9 -- the branch that actually collides -- were never in it. A trial merge that omits
108
+ branches passes by not looking. Steps 4 and 5 of scripts/real/patchexport_pins_doc_fix_push.sh are
109
+ the full five-way and the six-way with #11.
110
+
111
+ Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
112
+ EOM
113
+ git -C "$WT" --no-pager log --oneline -1 | sed 's/^/ /'
114
+ NEW=$(git -C "$WT" rev-parse HEAD)
115
+
116
+ hdr "4 the FULL five-way merge -- the step the previous gate did not have"
117
+ M=$S/five; rm -rf "$M"; git clone --quiet --shared "$WT" "$M" 2>&1 | scrub || exit 5
118
+ git -C "$M" remote set-url origin "$(git -C "$WT" remote get-url origin)"
119
+ git -C "$M" fetch --quiet origin main 2>&1 | scrub || exit 5
120
+ for n in 6 7 8 9 11; do git -C "$M" fetch --quiet origin "pull/$n/head:pr-$n" 2>&1 | scrub || exit 5; done
121
+ git -C "$M" checkout --quiet -B trial origin/main
122
+ git -C "$M" config user.email noreply@anthropic.com; git -C "$M" config user.name "pins-doc gate"
123
+ for n in 6 7 8 9; do
124
+ if git -C "$M" merge --no-ff -m "trial #$n" "pr-$n" >/dev/null 2>&1; then echo " #$n MERGED CLEAN"
125
+ 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; fi
126
+ done
127
+ if git -C "$M" merge --no-ff -m "trial #10" "$NEW" >/dev/null 2>&1; then echo " #10 (this commit) MERGED CLEAN"
128
+ else echo " #10 CONFLICTS: $(git -C "$M" diff --name-only --diff-filter=U | tr '\n' ' ')"; rc=6; fi
129
+ [ $rc -eq 0 ] || { echo " the five-way is not clean -- REFUSING"; exit $rc; }
130
+ 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")"
131
+ grep -c '^<<<<<<<' "$M/$F" | sed 's/^/ conflict markers left in the merged file: /'
132
+
133
+ hdr "5 the six-way with #11 -- $F must NOT be in the conflict set"
134
+ git -C "$M" merge --no-ff -m "trial #11" pr-11 >/dev/null 2>&1
135
+ U=$(git -C "$M" diff --name-only --diff-filter=U)
136
+ echo " conflicted: $(echo "$U" | tr '\n' ' ')"
137
+ if echo "$U" | grep -qx "$F"; then echo " !! $F is STILL conflicted against #11 -- REFUSING"; exit 7; fi
138
+ echo " $F is not in the six-way conflict set"
139
+
140
+ hdr "6 push"
141
+ if [ "$DO_PUSH" = 1 ]; then
142
+ git -C "$WT" push origin "$BR" 2>&1 | scrub || { echo " push FAILED"; exit 8; }
143
+ else
144
+ echo " DO_PUSH=0 -- not pushing"
145
+ fi
146
+ hdr "OVERALL rc=$rc"
147
+ exit $rc
rsm_rise/scripts/real/patchexport_pipprobe.sh ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Can a compute node reach PyPI, and does the CI venv accept the two pins it is missing?
3
+ V=/proj/dmfexp/zwhong/scratch_patchexport/run29/venv_ci
4
+ set -x
5
+ $V/bin/python -m pip install --disable-pip-version-check msgpack==1.1.0 pyzmq==26.4.0 2>&1 | tail -20
6
+ $V/bin/python -c "import msgpack, zmq; print('msgpack', msgpack.version, 'zmq', zmq.__version__)"
rsm_rise/scripts/real/patchexport_quickstart_weight.sh ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # rsm_real#5 -- a consequence of my OWN published scorer resolution that I had not measured.
3
+ #
4
+ # The resolution drops rise_stack/rsm/ and single-sources the scorer from the patched fork as
5
+ # `robomimic.algo.rsm_scorer`. #11's replay quickstart advertises "no openpi, no robomimic" and
6
+ # installs only requirements/rise-stack-replay.txt, on the stated premise that the scorer is VENDORED.
7
+ # If the vendored copy goes, does that quickstart still run? Measured, not argued:
8
+ # A. is the fork copy the same module as the vendored copy (modulo a vendoring header)?
9
+ # B. does the module body need the robomimic package at all?
10
+ # C. what does `import robomimic.algo.rsm_scorer` drag in, vs loading the SAME file by path?
11
+ # D. execute a by-path load with ONLY numpy+torch importable, and instantiate nothing else.
12
+ # Read-only: scratch + the research checkout, read. Pushes nothing.
13
+ set -uo pipefail
14
+ SCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run20}
15
+ M=${M:-/proj/dmfexp/zwhong/scratch_patchexport/run19/setupenv}
16
+ RISE=${RISE:-/proj/dmfexp/zwhong/rsm_rise}
17
+ hdr(){ echo; echo "=================== $* ==================="; date -u; }
18
+ rc_all=0
19
+ mkdir -p "${SCRATCH:?}" || exit 1
20
+ [ -d "$M/.git" ] || { echo "no resolved tree at $M"; exit 1; }
21
+
22
+ hdr "0 context"
23
+ echo "host=$(hostname) job=${LSB_JOBID:-none} scratch=$SCRATCH resolved_tree_repo=$M"
24
+
25
+ hdr "A fork copy vs vendored copy -- same module?"
26
+ git -C "$M" show HEAD:rise_stack/rsm/rsm_scorer.py > "$SCRATCH/vendored.py"
27
+ # reconstruct the fork's copy by applying the robomimic patch to an empty dir is overkill; the patch
28
+ # adds the file whole, so extract the added lines of exactly that file.
29
+ git -C "$M" show HEAD:rise_stack/robomimic/rise_on_robomimic.patch > "$SCRATCH/robomimic.patch"
30
+ python3 - "$SCRATCH/robomimic.patch" "$SCRATCH/fork.py" <<'PY'
31
+ import sys
32
+ src,dst=sys.argv[1],sys.argv[2]
33
+ out=[];inside=False
34
+ for line in open(src,encoding='utf-8',errors='replace'):
35
+ if line.startswith('diff --git'):
36
+ inside = 'robomimic/algo/rsm_scorer.py' in line
37
+ continue
38
+ if not inside: continue
39
+ if line.startswith(('--- ','+++ ','index ','new file','@@','old mode','new mode')): continue
40
+ if line.startswith('+'): out.append(line[1:])
41
+ open(dst,'w',encoding='utf-8').writelines(out)
42
+ print(f"extracted {len(out)} lines of robomimic/algo/rsm_scorer.py from the patch")
43
+ PY
44
+ echo "vendored: $(wc -lc < "$SCRATCH/vendored.py" | tr -s ' ') (lines chars)"
45
+ echo "fork : $(wc -lc < "$SCRATCH/fork.py" | tr -s ' ') (lines chars)"
46
+ echo "--- diff fork vs vendored (first 40 lines) ---"
47
+ diff "$SCRATCH/fork.py" "$SCRATCH/vendored.py" | head -40
48
+ echo "--- diff size: $(diff "$SCRATCH/fork.py" "$SCRATCH/vendored.py" | grep -c '^[<>]') differing line(s) ---"
49
+
50
+ hdr "B does the module body need the robomimic package?"
51
+ echo "occurrences of 'robomimic' in the fork copy:"
52
+ grep -n "robomimic" "$SCRATCH/fork.py" | head -20
53
+ echo "count: $(grep -c robomimic "$SCRATCH/fork.py")"
54
+
55
+ hdr 'C what import robomimic.algo.rsm_scorer drags in, before it ever reaches the module'
56
+ INIT=$RISE/code/rise_robomimic/robomimic/algo/__init__.py
57
+ echo "robomimic/algo/__init__.py imports $(grep -cE '^from robomimic' "$INIT") sibling algo module(s):"
58
+ grep -E '^from robomimic' "$INIT" | sed 's/^/ /'
59
+ echo "--- third-party imports those siblings pull in (static scan) ---"
60
+ python3 - "$RISE/code/rise_robomimic/robomimic" <<'PY'
61
+ import os,sys,re,ast,collections
62
+ root=sys.argv[1]
63
+ std=set(sys.stdlib_module_names)
64
+ tops=collections.Counter()
65
+ algo=os.path.join(root,'algo')
66
+ for fn in sorted(os.listdir(algo)):
67
+ if not fn.endswith('.py'): continue
68
+ try: tree=ast.parse(open(os.path.join(algo,fn),encoding='utf-8',errors='replace').read())
69
+ except SyntaxError: continue
70
+ for n in ast.walk(tree):
71
+ if isinstance(n,ast.Import):
72
+ for a in n.names: tops[a.name.split('.')[0]]+=1
73
+ elif isinstance(n,ast.ImportFrom) and n.level==0 and n.module:
74
+ tops[n.module.split('.')[0]]+=1
75
+ ext={k:v for k,v in tops.items() if k not in std and k not in ('robomimic',)}
76
+ print(" non-stdlib top-level modules imported across robomimic/algo/*.py:")
77
+ for k,v in sorted(ext.items(),key=lambda kv:-kv[1]): print(f" {k:<20} {v}")
78
+ PY
79
+
80
+ hdr "D EXECUTE: load the fork copy BY PATH with only numpy+torch, no robomimic package"
81
+ QS_PY=${QS_PY:-/proj/dmfexp/zwhong/rsm_rise/venv_rsm/bin/python}
82
+ echo " interpreter: $QS_PY"
83
+ cd "$SCRATCH"
84
+ mkdir -p bypath && cp fork.py bypath/rsm_scorer_fork.py
85
+ "$QS_PY" - "$SCRATCH/bypath/rsm_scorer_fork.py" <<'PY'
86
+ import sys, importlib.util, types
87
+ path=sys.argv[1]
88
+ # prove robomimic is NOT importable in this interpreter, so a hidden package import would fail loudly
89
+ import importlib
90
+ try:
91
+ importlib.import_module('robomimic'); print(" robomimic IS importable here -- test is not conclusive"); sys.exit(2)
92
+ except ImportError:
93
+ print(" robomimic is NOT importable in this interpreter (as on a labmate's quickstart venv)")
94
+ spec=importlib.util.spec_from_file_location("rsm_scorer_bypath", path)
95
+ mod=importlib.util.module_from_spec(spec)
96
+ sys.modules["rsm_scorer_bypath"]=mod
97
+ try:
98
+ spec.loader.exec_module(mod)
99
+ except Exception as e:
100
+ print(f" !! by-path load FAILED: {type(e).__name__}: {e}"); sys.exit(1)
101
+ names=[n for n in dir(mod) if 'Scorer' in n or 'scorer' in n]
102
+ print(f" by-path load OK -- module {mod.__name__}, scorer symbols: {names}")
103
+ import numpy, torch
104
+ print(f" numpy {numpy.__version__}, torch {torch.__version__}")
105
+ PY
106
+ rc=$?
107
+ [ $rc -eq 0 ] || rc_all=$rc
108
+
109
+ hdr "OVERALL rc=$rc_all"
110
+ exit $rc_all
rsm_rise/scripts/real/patchexport_readme_decide.sh ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # rsm_real#5 run 28 -- the one open runbook question: should rise_stack/openpi/README.md flip from
3
+ # take-OURS to take-THEIRS (#11), with our unique passages folded into their document?
4
+ #
5
+ # It has stayed open for four runs because it was framed as a preference ("each of their pushes costs
6
+ # us a re-merge"). It is not a preference. SELFCONTAINED's 17:05Z note says their 6c1b8d0 corrected
7
+ # two things on that page that are WRONG on our side, and a CI test now enforces them. So the
8
+ # question has a measurable answer: for each numeric claim on each side, compare it to the ground
9
+ # truth -- `git apply --numstat` on the shipped patch and the TrainConfigs the patch declares -- and
10
+ # then measure the fold-in cost in both directions. Whichever side is factually right is the base.
11
+ #
12
+ # Measures, never edits. Exit 3 only if its own parse is inconsistent.
13
+ set -uo pipefail
14
+ SCRATCH=${SCRATCH:-/proj/dmfexp/zwhong/scratch_patchexport/run93}
15
+ R=/proj/dmfexp/zwhong/rsm_rise
16
+ scrub(){ sed 's#https://[^@]*@#https://<redacted>@#g'; }
17
+ hdr(){ echo; echo "=================== $* ==================="; date -u; }
18
+ W=$SCRATCH/w
19
+ mkdir -p "${SCRATCH:?}" || exit 1
20
+
21
+ hdr "0 clone and fetch the three heads"
22
+ TOK=$(grep -m1 'https://richardrl:' ~/.git-credentials | sed -E 's|https://richardrl:([^@]*)@.*|\1|')
23
+ [ -n "$TOK" ] || { echo "no token"; exit 1; }
24
+ rm -rf "${W:?}"; git init --quiet "$W" || exit 1
25
+ 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"
26
+ unset TOK
27
+ for 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; }; done
28
+ for n in 6 10 11; do echo " pr-$n = $(git -C "$W" rev-parse --short pr-$n)"; done
29
+
30
+ P=rise_stack/openpi/README.md
31
+ PATCH=rise_stack/openpi/rise_on_pi05.patch
32
+ mkdir -p "$SCRATCH/x"
33
+ git -C "$W" show "pr-10:$P" > "$SCRATCH/x/ours.md" || { echo "no $P on #10"; exit 1; }
34
+ git -C "$W" show "pr-11:$P" > "$SCRATCH/x/theirs.md" || { echo "no $P on #11"; exit 1; }
35
+ git -C "$W" show "pr-6:$P" > "$SCRATCH/x/pr6.md" || { echo "no $P on #6"; exit 1; }
36
+ git -C "$W" show "pr-10:$PATCH" > "$SCRATCH/x/ours.patch" || { echo "no patch on #10"; exit 1; }
37
+ git -C "$W" show "pr-11:$PATCH" > "$SCRATCH/x/theirs.patch" || { echo "no patch on #11"; exit 1; }
38
+ echo " README bytes: ours=$(wc -c < "$SCRATCH/x/ours.md") theirs=$(wc -c < "$SCRATCH/x/theirs.md") pr6=$(wc -c < "$SCRATCH/x/pr6.md")"
39
+ echo " #6 README == #10 README ? $(cmp -s "$SCRATCH/x/ours.md" "$SCRATCH/x/pr6.md" && echo YES || echo NO)"
40
+ echo " patch bytes identical on #10 and #11 ? $(cmp -s "$SCRATCH/x/ours.patch" "$SCRATCH/x/theirs.patch" && echo YES || echo NO)"
41
+ echo " patch sha256 = $(sha256sum "$SCRATCH/x/ours.patch" | cut -c1-16)"
42
+
43
+ hdr "1 GROUND TRUTH from the shipped patch: numstat + declared TrainConfigs"
44
+ git -C "$W" apply --numstat "$SCRATCH/x/ours.patch" > "$SCRATCH/x/numstat.txt" 2>"$SCRATCH/x/numstat.err" \
45
+ || { echo " git apply --numstat FAILED:"; cat "$SCRATCH/x/numstat.err"; exit 3; }
46
+ awk '{i+=$1; d+=$2; n++} END{printf " %d file(s), +%d insertions, -%d deletions\n", n, i, d}' "$SCRATCH/x/numstat.txt"
47
+ sed 's/^/ /' "$SCRATCH/x/numstat.txt"
48
+ echo " --- pi05_cooking_* TrainConfigs DECLARED by the patch (added lines only) ---"
49
+ grep -E '^\+' "$SCRATCH/x/ours.patch" | grep -oE 'name="pi05_cooking_[A-Za-z0-9_]*"' | sort -u | sed 's/^/ /'
50
+ NCFG=$(grep -E '^\+' "$SCRATCH/x/ours.patch" | grep -oE 'name="pi05_cooking_[A-Za-z0-9_]*"' | sort -u | wc -l)
51
+ echo " declared count = $NCFG"
52
+
53
+ hdr "2 every numeric claim on each README, against that ground truth"
54
+ python3 "$R/scripts/real/patchexport_readme_numbers.py" \
55
+ "$SCRATCH/x/numstat.txt" "$NCFG" ours:"$SCRATCH/x/ours.md" theirs:"$SCRATCH/x/theirs.md"
56
+ NRC=$?
57
+ echo " numbers checker rc=$NRC"
58
+
59
+ hdr "3 fold-in cost in BOTH directions (the existing residual tool)"
60
+ echo "--- if OURS is the base: what of THEIRS would have to be folded in ---"
61
+ python3 "$R/scripts/real/patchexport_union_residual.py" "$SCRATCH/x/ours.md:$SCRATCH/x/ours.md:$SCRATCH/x/theirs.md"
62
+ echo "--- if THEIRS is the base: what of OURS would have to be folded in ---"
63
+ python3 "$R/scripts/real/patchexport_union_residual.py" "$SCRATCH/x/theirs.md:$SCRATCH/x/ours.md:$SCRATCH/x/theirs.md"
64
+
65
+ hdr "4 does #11 ship a test that PINS that page, and what does it assert about?"
66
+ git -C "$W" grep -l "openpi/README" pr-11 -- tests/ | sed 's/^/ /'
67
+ for f in $(git -C "$W" grep -l "openpi/README" pr-11 -- tests/ | sed 's#^pr-11:##'); do
68
+ echo " --- $f (on #11) ---"
69
+ git -C "$W" show "pr-11:$f" | grep -nE "openpi/README|def test_|assert " | head -30 | sed 's/^/ /'
70
+ done
71
+ echo " --- do those files exist on #10? ---"
72
+ for f in $(git -C "$W" grep -l "openpi/README" pr-11 -- tests/ | sed 's#^pr-11:##'); do
73
+ git -C "$W" cat-file -e "pr-10:$f" 2>/dev/null && echo " present on #10: $f" || echo " ABSENT on #10: $f"
74
+ done
75
+
76
+ hdr "DONE"