-
-
Notifications
You must be signed in to change notification settings - Fork 6.9k
Expand file tree
/
Copy pathinstall.sh
More file actions
executable file
·5606 lines (5285 loc) · 300 KB
/
Copy pathinstall.sh
File metadata and controls
executable file
·5606 lines (5285 loc) · 300 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/sh
# Unsloth Studio Installer. Usage, supported options and the web one-liner live in the README under "Unsloth Studio (web UI)" and are deliberately not repeated here: this file ships inside the Linux desktop bundle, where a header rehearsing download-and-run command lines is the first thing a generic script classifier reads. A piped install takes options as environment variables after the pipe (UNSLOTH_NO_TORCH, UNSLOTH_SKIP_AUTOSTART, UNSLOTH_ISOLATE_UV_CACHE, UNSLOTH_PYTHON, UNSLOTH_STUDIO_HOME), because a bare `--no-torch` after the pipe would be read as an option to sh itself; a local run takes the equivalent flags (--no-torch, --isolated-uv-cache, --python, --local). Install dir priority: UNSLOTH_STUDIO_HOME > STUDIO_HOME > $HOME/.unsloth/studio
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
set -e
# ── Why the installer lives in a function ──
# Under a piped web install, sh is the pipe READER. This file is ~150KB, so a top-level `exit` left most of it unread, the write end failed, and curl tacked "(56) Failure writing output to destination" onto our own error message. Wrapping the body forces sh to parse to the closing brace first, so the pipe always drains. The body is deliberately NOT reindented, and `exit` still exits the shell from inside a function. Do not add `exec < /dev/null`: for a piped shell that closes the script's own source.
_unsloth_main() {
# ── Output style (aligned with studio/setup.sh) ──
RULE=""
_rule_i=0
while [ "$_rule_i" -lt 52 ]; do
RULE="${RULE}─"
_rule_i=$((_rule_i + 1))
done
if [ -n "${NO_COLOR:-}" ]; then
C_TITLE= C_DIM= C_OK= C_WARN= C_ERR= C_RST=
elif [ -t 1 ] || [ -n "${FORCE_COLOR:-}" ]; then
_ESC="$(printf '\033')"
C_TITLE="${_ESC}[38;5;150m"
C_DIM="${_ESC}[38;5;245m"
C_OK="${_ESC}[38;5;108m"
C_WARN="${_ESC}[38;5;136m"
C_ERR="${_ESC}[91m"
C_RST="${_ESC}[0m"
else
C_TITLE= C_DIM= C_OK= C_WARN= C_ERR= C_RST=
fi
step() { printf " ${C_DIM}%-15.15s${C_RST}${3:-$C_OK}%s${C_RST}\n" "$1" "$2"; }
substep() { printf " ${C_DIM}%-15s${2:-$C_DIM}%s${C_RST}\n" "" "$1"; }
# ── Parse flags ──
STUDIO_LOCAL_INSTALL=false
PACKAGE_NAME="unsloth"
TAURI_MODE=false
_USER_PYTHON=""
_NO_TORCH_FLAG=false
_SKIP_AUTOSTART=false
_ISOLATE_UV_CACHE=false
_VERBOSE=false
_SHORTCUTS_ONLY=false
_next_is_package=false
_next_is_python=false
_next_is_llama_cpp_dir=false
_WITH_LLAMA_CPP_DIR="${UNSLOTH_LOCAL_LLAMA_CPP_DIR:-}"
for arg in "$@"; do
if [ "$_next_is_package" = true ]; then
PACKAGE_NAME="$arg"
_next_is_package=false
continue
fi
if [ "$_next_is_python" = true ]; then
_USER_PYTHON="$arg"
_next_is_python=false
continue
fi
if [ "$_next_is_llama_cpp_dir" = true ]; then
_WITH_LLAMA_CPP_DIR="$arg"
_next_is_llama_cpp_dir=false
continue
fi
case "$arg" in
--local) STUDIO_LOCAL_INSTALL=true ;;
--package) _next_is_package=true ;;
--tauri) TAURI_MODE=true ;;
--python) _next_is_python=true ;;
--no-torch) _NO_TORCH_FLAG=true ;;
--isolated-uv-cache) _ISOLATE_UV_CACHE=true ;;
--verbose|-v) _VERBOSE=true ;;
--shortcuts-only) _SHORTCUTS_ONLY=true ;;
--with-llama-cpp-dir) _next_is_llama_cpp_dir=true ;;
esac
done
# Env-var equivalents for piped installs; an explicit flag still wins.
case "${UNSLOTH_NO_TORCH:-}" in 1|true|TRUE|yes|YES|on|ON) _NO_TORCH_FLAG=true ;; esac
case "${UNSLOTH_SKIP_AUTOSTART:-}" in 1|true|TRUE|yes|YES|on|ON) _SKIP_AUTOSTART=true ;; esac
case "${UNSLOTH_ISOLATE_UV_CACHE:-}" in 1|true|TRUE|yes|YES|on|ON) _ISOLATE_UV_CACHE=true ;; esac
[ -z "$_USER_PYTHON" ] && [ -n "${UNSLOTH_PYTHON:-}" ] && _USER_PYTHON="$UNSLOTH_PYTHON"
if [ "$_VERBOSE" = true ]; then
export UNSLOTH_VERBOSE=1
fi
# Custom Unsloth roots are unsupported with --tauri unless override == legacy default.
if [ "$TAURI_MODE" = true ]; then
_tauri_override_var=""
_tauri_override="${UNSLOTH_STUDIO_HOME:-}"
if [ -n "$_tauri_override" ]; then
_tauri_override_var="UNSLOTH_STUDIO_HOME"
else
_tauri_override="${STUDIO_HOME:-}"
[ -n "$_tauri_override" ] && _tauri_override_var="STUDIO_HOME"
fi
# Strip whitespace so " " is treated as unset (matches Python .strip()).
_tauri_override=$(printf '%s' "$_tauri_override" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
if [ -n "$_tauri_override" ]; then
case "$_tauri_override" in
"~") _tauri_override="$HOME" ;;
"~/"*) _tauri_override="$HOME/${_tauri_override#'~/'}" ;;
esac
# Canonicalize both sides so CDPATH / a symlinked $HOME cannot break equality.
if [ -d "$_tauri_override" ]; then
_tauri_override_abs=$(CDPATH= cd -P -- "$_tauri_override" 2>/dev/null && pwd -P) \
|| _tauri_override_abs="$_tauri_override"
else
_tauri_override_abs="$_tauri_override"
fi
# Strip trailing separators so ".../studio/" matches ".../studio".
while [ "$_tauri_override_abs" != "/" ] \
&& [ "${_tauri_override_abs%/}" != "$_tauri_override_abs" ]; do
_tauri_override_abs=${_tauri_override_abs%/}
done
_tauri_legacy_root="$HOME/.unsloth/studio"
if [ -d "$_tauri_legacy_root" ]; then
_tauri_legacy_root=$(CDPATH= cd -P -- "$_tauri_legacy_root" 2>/dev/null && pwd -P) \
|| _tauri_legacy_root="$HOME/.unsloth/studio"
fi
while [ "$_tauri_legacy_root" != "/" ] \
&& [ "${_tauri_legacy_root%/}" != "$_tauri_legacy_root" ]; do
_tauri_legacy_root=${_tauri_legacy_root%/}
done
if [ "$_tauri_override_abs" != "$_tauri_legacy_root" ]; then
echo "ERROR: $_tauri_override_var is not supported with --tauri." >&2
echo " The desktop app still uses the legacy ~/.unsloth/studio root." >&2
echo " Run install.sh without --tauri for custom-root shell installs," >&2
echo " or unset the env var for default desktop installs." >&2
exit 1
fi
fi
fi
_is_verbose() {
[ "${UNSLOTH_VERBOSE:-0}" = "1" ]
}
run_maybe_quiet() {
if _is_verbose; then
"$@"
else
"$@" > /dev/null 2>&1
fi
}
_trim_index_path_slashes() {
_tips_v="$1"
case "$_tips_v" in
*[?#]*)
_tips_head="${_tips_v%%[?#]*}"
_tips_tail="${_tips_v#"$_tips_head"}"
;;
*)
_tips_head="$_tips_v"
_tips_tail=""
;;
esac
while [ -n "$_tips_head" ] && [ "${_tips_head%/}" != "$_tips_head" ]; do
_tips_head="${_tips_head%/}"
done
printf '%s%s' "$_tips_head" "$_tips_tail"
}
_redact_install_output() {
sed -E \
-e 's#(https?://)[^/@[:space:]`]+@#\1<redacted>@#g' \
-e 's#([?&][^=[:space:]&`]+)=[^&#[:space:]`]+#\1=<redacted>#g' \
-e 's|(https?://[^[:space:]`#]+)#[^[:space:]`]+|\1#<redacted>|g' \
"$@"
}
# Large downloads become markers the app consumes and does not display; forwarding uv's own chatter would put dozens of lines in front of the user.
: "${UNSLOTH_DL_MARKER_MIN_BYTES:=52428800}"
# $1 is the child's output sink: a log file for the quiet path, empty to pass it along stdout for the verbose one. Markers go to stderr to stay clear of the verbose path's redactor, since sed block-buffers and a marker queued behind it would arrive only once the download it announces had finished.
_uv_download_markers() {
# Minimal images ship without awk, which the uv version probe below also allows for. This pipe now carries every install command, so a missing awk must cost the markers and nothing else: without this the pipeline closes and the child dies of SIGPIPE.
if ! command -v awk >/dev/null 2>&1; then
if [ -n "$1" ]; then cat >> "$1"; else cat; fi
return
fi
awk -v logf="$1" -v minb="$2" -v tauri="${TAURI_MODE:-false}" -v err=/dev/stderr '
{ if (logf == "") print; else print >> logf }
tauri != "true" { next }
# Field-relative so a leading status glyph cannot shift the match.
/(^| )Downloading [^ ]+ \([0-9.]+[KMG]iB\)$/ {
size = $NF
gsub(/[()]/, "", size)
n = size; sub(/[KMG]iB$/, "", n)
u = size; sub(/^[0-9.]+/, "", u)
mult = (u == "GiB") ? 1073741824 : (u == "MiB") ? 1048576 : 1024
if (n * mult >= minb) {
announced[$(NF - 1)] = 1
print "[TAURI:DL] " $(NF - 1) " " size > err
fflush(err)
}
next
}
# Only close what was opened: uv also reports completion for unannounced packages.
/(^| )Downloaded [^ ]+$/ && ($NF in announced) {
delete announced[$NF]
print "[TAURI:DL_DONE] " $NF > err
fflush(err)
}
'
}
run_install_cmd() {
_label="$1"
shift
# For --default-index, clear inherited uv index vars so a uv.toml cannot outrank the CLI pin.
case " $* " in
*" --default-index "*) set -- env -u UV_DEFAULT_INDEX -u UV_INDEX_URL -u UV_INDEX -u UV_EXTRA_INDEX_URL -u UV_TORCH_BACKEND -u UV_FIND_LINKS -u UV_CONFIG_FILE UV_NO_CONFIG=1 "$@" ;;
esac
if _is_verbose; then
# Stream through the redactor; the rc file carries the exit code (no pipefail in sh).
_rcf=$(mktemp)
tauri_stream_log stdout "OUTPUT_CLEAR" "$_label"
{
if "$@" 2>&1; then
_cmd_rc=0
else
_cmd_rc=$?
fi
printf '%s' "$_cmd_rc" > "$_rcf"
} | _uv_download_markers "" "$UNSLOTH_DL_MARKER_MIN_BYTES" | _redact_install_output
_rc=$(cat "$_rcf" 2>/dev/null || echo 1)
rm -f "$_rcf"
_rc=${_rc:-1}
if [ "$_rc" -eq 0 ] 2>/dev/null; then
tauri_clear_install_error "$_label recovered"
return 0
fi
tauri_stream_log stdout "ERROR_OUTPUT" "$_label failed (exit code $_rc)"
step "error" "$_label failed (exit code $_rc)" "$C_ERR" >&2
return "$_rc"
fi
_log=$(mktemp)
_rcf=$(mktemp)
tauri_stream_log stderr "OUTPUT_CLEAR" "$_label"
# rc file because the marker filter is a pipe, and plain sh reports only its last stage.
{
if "$@" 2>&1; then
_cmd_rc=0
else
_cmd_rc=$?
fi
printf '%s' "$_cmd_rc" > "$_rcf"
} | _uv_download_markers "$_log" "$UNSLOTH_DL_MARKER_MIN_BYTES"
_rc=$(cat "$_rcf" 2>/dev/null || echo 1)
rm -f "$_rcf"
_rc=${_rc:-1}
if [ "$_rc" -eq 0 ] 2>/dev/null; then
rm -f "$_log"
tauri_clear_install_error "$_label recovered"
return 0
fi
step "error" "$_label failed (exit code $_rc)" "$C_ERR" >&2
_redact_install_output "$_log" >&2
tauri_stream_log stderr "ERROR_OUTPUT" "$_label failed (exit code $_rc)"
rm -f "$_log"
return $_rc
}
# Returns the last exit code so the set -e rollback trap still fires.
: "${UNSLOTH_INSTALL_RETRIES:=3}"
: "${UNSLOTH_INSTALL_RETRY_DELAY:=3}"
run_install_cmd_retry() {
_ricr_label="$1"
# Default 3, bounds 1..100 retries and 0..3600s delay; 0?* rejects octal delays.
case "$UNSLOTH_INSTALL_RETRIES" in
''|*[!0-9]*|0) _ricr_max=3 ;;
*) if [ "${#UNSLOTH_INSTALL_RETRIES}" -le 3 ] && [ "$UNSLOTH_INSTALL_RETRIES" -ge 1 ] 2>/dev/null && [ "$UNSLOTH_INSTALL_RETRIES" -le 100 ] 2>/dev/null; then _ricr_max=$UNSLOTH_INSTALL_RETRIES; else _ricr_max=3; fi ;;
esac
case "$UNSLOTH_INSTALL_RETRY_DELAY" in
''|*[!0-9]*|0?*) _ricr_delay=3 ;;
*) if [ "${#UNSLOTH_INSTALL_RETRY_DELAY}" -le 4 ] && [ "$UNSLOTH_INSTALL_RETRY_DELAY" -ge 0 ] 2>/dev/null && [ "$UNSLOTH_INSTALL_RETRY_DELAY" -le 3600 ] 2>/dev/null; then _ricr_delay=$UNSLOTH_INSTALL_RETRY_DELAY; else _ricr_delay=3; fi ;;
esac
_ricr_attempt=1
while :; do
# AND-OR (not `if`) preserves the real failure code for the rollback path.
run_install_cmd "$@" && return 0
_ricr_rc=$?
if [ "$_ricr_attempt" -ge "$_ricr_max" ]; then
return "$_ricr_rc"
fi
substep "retrying \"$_ricr_label\" after transient failure (attempt $((_ricr_attempt + 1))/$_ricr_max, waiting ${_ricr_delay}s)..." "$C_WARN"
sleep "$_ricr_delay" || true
_ricr_attempt=$((_ricr_attempt + 1))
_ricr_delay=$((_ricr_delay * 2))
done
}
# True when the runtime target is gfx906 (MI50/Radeon VII): the prebuilt AMD bitsandbytes wheel carries no gfx906 kernels, and force-reinstalling it would clobber a user's source-built bnb, the only 4-bit path on this arch, on every `studio update`. _gfx906_target is set during torch-index resolution; an explicit UNSLOTH_ROCM_GFX_ARCH is honored too so a pinned-index install still skips, normalized (gfx906:sramecc-:xnack- to gfx906) so a copied HIP gcnArchName counts.
_is_gfx906_bnb_skip() {
[ "${_gfx906_target:-false}" = true ] && return 0
_bnb_gfx_env=$(printf '%s' "${UNSLOTH_ROCM_GFX_ARCH:-}" | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]')
_bnb_gfx_env=${_bnb_gfx_env%%:*}
[ "$_bnb_gfx_env" = "gfx906" ] && return 0
# A pinned index (UNSLOTH_TORCH_INDEX_URL/_FAMILY) skips the reroute block that sets _gfx906_target, so a real gfx906 host with a pinned rocm6.3 index and no UNSLOTH_ROCM_GFX_ARCH would otherwise clobber a source-built bnb. Probe here in that gap; skip only when gfx906 is the SOLE distinct arch, mirroring the reroute block's de-dup rule.
if [ -z "$_bnb_gfx_env" ] && [ "${_torch_index_pinned:-false}" = true ]; then
_bnb_gfx_probe=$(_probe_amd_gfx_arch | awk 'NF && !seen[$0]++')
[ "$_bnb_gfx_probe" = "gfx906" ] && return 0
fi
return 1
}
# `pip install unsloth` resolves its unconditional bitsandbytes dep to a generic CUDA wheel (no gfx906 kernels) once we skip the prebuilt one. Snapshot bnb before the unsloth install, then drop a freshly pulled wheel afterwards while leaving a pre-existing source build in place.
_gfx906_bnb_installed() {
"$_VENV_PY" -c "import importlib.util as u, sys; sys.exit(0 if u.find_spec('bitsandbytes') else 1)" >/dev/null 2>&1
}
_gfx906_bnb_snapshot() {
_gfx906_bnb_absent_before=false
_is_gfx906_bnb_skip || return 0
_gfx906_bnb_installed || _gfx906_bnb_absent_before=true
}
_gfx906_bnb_prune() {
_is_gfx906_bnb_skip || return 0
[ "${_gfx906_bnb_absent_before:-false}" = true ] || return 0
_gfx906_bnb_installed || return 0
substep "gfx906: removing generic bitsandbytes pulled in as a dependency (no gfx906 kernels; build from source for 4-bit QLoRA)" "$C_WARN"
uv pip uninstall --python "$_VENV_PY" bitsandbytes >/dev/null 2>&1 \
|| "$_VENV_PY" -m pip uninstall -y bitsandbytes >/dev/null 2>&1 || true
}
# Install bitsandbytes on AMD ROCm hosts. bnb <= 0.49.2 NaNs at 4-bit decode shape on every AMD GPU; the fix (bnb #1887) ships in continuous-release_main and, on PyPI, first in 0.50.0. Keep this floor in step with the amd extra in pyproject.toml and studio/install_python_stack.py.
_BNB_ROCM_PYPI_FALLBACK="bitsandbytes>=0.50.0"
# Intel XPU: separate constant, same floor by coincidence. 0.50.0 manylinux is the first with libbitsandbytes_xpu2025.so / _xpu2026.so; studio/setup.ps1's XPU pass uses the same floor.
_BNB_XPU_SPEC="bitsandbytes>=0.50.0"
# bitsandbytes ships no ROCm binary in its aarch64 wheel at any version: the PyPI 0.50.0 and continuous-release_main aarch64 wheels both carry only libbitsandbytes_cpu.so plus CUDA variants. So neither install path below gives aarch64 a 4-bit backend, and the messages must not claim one.
_bnb_rocm_arch_has_binary() {
case "$_ARCH" in
aarch64|arm64) return 1 ;;
*) return 0 ;;
esac
}
_warn_bnb_no_rocm_binary() {
_bnb_rocm_arch_has_binary && return 0
substep "[WARN] aarch64: bitsandbytes ships no ROCm kernels on this arch; 4-bit QLoRA needs a source build -- https://docs.unsloth.ai/get-started/install-and-update/amd" "$C_WARN"
}
_install_bnb_rocm() {
_label="$1"
_venv_py="$2"
case "$_ARCH" in
x86_64|amd64)
_bnb_whl_url="https://github.com/bitsandbytes-foundation/bitsandbytes/releases/download/continuous-release_main/bitsandbytes-1.33.7.preview-py3-none-manylinux_2_24_x86_64.whl"
;;
aarch64|arm64)
_bnb_whl_url="https://github.com/bitsandbytes-foundation/bitsandbytes/releases/download/continuous-release_main/bitsandbytes-1.33.7.preview-py3-none-manylinux_2_24_aarch64.whl"
;;
*)
_bnb_whl_url=""
;;
esac
# uv rejects the pre-release wheel: filename version (1.33.7rc0) does not match metadata (0.50.x.dev0). pip accepts it, so bootstrap pip and use it.
if ! "$_venv_py" -m pip --version >/dev/null 2>&1; then
if ! run_maybe_quiet "$_venv_py" -m ensurepip --upgrade; then
run_maybe_quiet uv pip install --python "$_venv_py" pip || \
substep "[WARN] could not bootstrap pip; bitsandbytes install will likely fail" "$C_WARN"
fi
fi
if [ -n "$_bnb_whl_url" ]; then
substep "installing bitsandbytes for AMD ROCm (pre-release, PR #1887)..."
_bnb_log=$(mktemp)
if "$_venv_py" -m pip install \
--disable-pip-version-check \
--force-reinstall --no-cache-dir --no-deps \
--retries 8 --timeout 90 \
"$_bnb_whl_url" >"$_bnb_log" 2>&1; then
rm -f "$_bnb_log"
_warn_bnb_no_rocm_binary
return 0
fi
_bnb_rc=$?
if _is_verbose; then
_redact_install_output "$_bnb_log" >&2
fi
rm -f "$_bnb_log"
step "warning" "$_label (pre-release) failed (exit code $_bnb_rc)" "$C_WARN" >&2
if _bnb_rocm_arch_has_binary; then
substep "[WARN] bnb pre-release install failed; falling back to PyPI $_BNB_ROCM_PYPI_FALLBACK, which carries the ROCm 4-bit fix" "$C_WARN"
else
substep "[WARN] bnb pre-release install failed; falling back to PyPI $_BNB_ROCM_PYPI_FALLBACK" "$C_WARN"
fi
fi
run_install_cmd "$_label (pypi fallback)" "$_venv_py" -m pip install \
--force-reinstall --no-cache-dir --no-deps "$_BNB_ROCM_PYPI_FALLBACK"
_bnb_pypi_rc=$?
_warn_bnb_no_rocm_binary
return $_bnb_pypi_rc
}
if [ "$_next_is_package" = true ]; then
echo "❌ ERROR: --package requires an argument." >&2
exit 1
fi
if [ "$_next_is_python" = true ]; then
echo "❌ ERROR: --python requires a version argument (e.g. --python 3.12)." >&2
exit 1
fi
if [ "$_next_is_llama_cpp_dir" = true ]; then
echo "❌ ERROR: --with-llama-cpp-dir requires a path argument." >&2
exit 1
fi
# Validate --package: a leading letter/digit stops uv parsing it as a flag.
case "$PACKAGE_NAME" in
[!a-zA-Z0-9]*)
echo "❌ ERROR: --package name must start with a letter or digit." >&2
exit 1 ;;
*[!a-zA-Z0-9._-]*)
echo "❌ ERROR: --package name contains invalid characters (allowed: a-z A-Z 0-9 . _ -)" >&2
exit 1 ;;
esac
# ── Tauri structured output ──
tauri_log() {
if [ "$TAURI_MODE" = true ]; then
echo "[TAURI:$1] $2"
fi
}
tauri_stream_log() {
_tsl_stream="$1"
_tsl_tag="$2"
shift 2
if [ "$TAURI_MODE" = true ]; then
if [ "$_tsl_stream" = stderr ]; then
printf '[TAURI:%s] %s\n' "$_tsl_tag" "$*" >&2
else
printf '[TAURI:%s] %s\n' "$_tsl_tag" "$*"
fi
fi
}
rollback_substep() {
if [ "$TAURI_MODE" = true ]; then
tauri_log "PROGRESS" "$1"
else
substep "$@"
fi
}
tauri_clear_install_error() {
if [ "$TAURI_MODE" = true ]; then
tauri_log "ERROR_CLEAR" "$1"
printf '[TAURI:ERROR_CLEAR] %s\n' "$1" >&2
fi
}
tauri_diag_marker() {
_diag_gpu_branch="${1:-unknown}"
_diag_torch_index_family="${2:-none}"
tauri_log "DIAG" "diag_schema=1 platform=${OS:-unknown} arch=${_ARCH:-unknown} python_version=${PYTHON_VERSION:-unknown} skip_torch=${SKIP_TORCH:-false} mac_intel=${MAC_INTEL:-false} gpu_branch=${_diag_gpu_branch} torch_index_family=${_diag_torch_index_family}"
}
_tauri_torch_index_family() {
if [ "${SKIP_TORCH:-false}" = true ]; then
echo "none"
return
fi
_diag_url="${1:-}"
_diag_url="${_diag_url%%\?*}"
_diag_url="${_diag_url%%#*}"
_diag_url="${_diag_url%/}"
case "$_diag_url" in
*/cu118) echo "cu118" ;;
*/cu124) echo "cu124" ;;
*/cu126) echo "cu126" ;;
*/cu128) echo "cu128" ;;
*/cu130) echo "cu130" ;;
*/cpu) echo "cpu" ;;
*/xpu) echo "xpu" ;;
*/rocm[0-9]*.[0-9]*)
_diag_family=${_diag_url##*/}
case "$_diag_family" in
rocm[0-9]*.[0-9]*) echo "$_diag_family" ;;
*) echo "auto" ;;
esac ;;
# AMD arch-specific index (Strix Halo/Point; torch 2.11+rocm7.13 has the real fix).
*repo.amd.com/rocm/whl/gfx*|*rocm/whl/gfx*) echo "rocm7.13" ;;
"") echo "none" ;;
*) echo "auto" ;;
esac
}
_tauri_gpu_branch() {
_diag_family="${1:-unknown}"
_diag_radeon="${2:-false}"
if [ "${SKIP_TORCH:-false}" = true ]; then
echo "no_torch"
return
fi
if [ "${OS:-}" = "macos" ]; then
echo "mac"
return
fi
case "$_diag_family" in
# Require a digit after cu so /current or /custom is not branded CUDA.
cu[0-9]*) echo "cuda" ;;
rocm*)
if [ "$_diag_radeon" = true ]; then
echo "rocm_radeon"
else
echo "rocm"
fi ;;
radeon) echo "rocm_radeon" ;;
xpu) echo "xpu" ;;
cpu) echo "cpu" ;;
none) echo "no_torch" ;;
*) echo "unknown" ;;
esac
}
PYTHON_VERSION="" # resolved after platform detection
_resolve_studio_destinations() {
_override_var=""
_override="${UNSLOTH_STUDIO_HOME:-}"
if [ -n "$_override" ]; then
_override_var="UNSLOTH_STUDIO_HOME"
else
_override="${STUDIO_HOME:-}"
[ -n "$_override" ] && _override_var="STUDIO_HOME"
fi
# Strip surrounding whitespace so " " is treated as unset (matches Python .strip()).
_override=$(printf '%s' "$_override" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
# Tilde expansion: quoted env vars aren't subject to it on assignment.
case "$_override" in
"~") _override="$HOME" ;;
"~/"*) _override="$HOME/${_override#'~/'}" ;;
esac
if [ -n "$_override" ]; then
mkdir -p -- "$_override" 2>/dev/null || { echo "ERROR: $_override_var=$_override cannot be created." >&2; exit 1; }
[ -w "$_override" ] || { echo "ERROR: $_override_var=$_override is not writable." >&2; exit 1; }
STUDIO_HOME="$(CDPATH= cd -P -- "$_override" && pwd -P)" || exit 1
DATA_DIR="$STUDIO_HOME/share"
_LOCAL_BIN="$STUDIO_HOME/bin"
_STUDIO_HOME_REDIRECT=env
substep "custom $_override_var=$STUDIO_HOME"
return 0
fi
_default_home=""
if command -v getent >/dev/null 2>&1; then
_default_home=$(getent passwd "${USER:-$(whoami)}" 2>/dev/null | cut -d: -f6)
elif [ "$(uname)" = "Darwin" ] && command -v dscl >/dev/null 2>&1; then
_default_home=$(dscl . -read "/Users/${USER:-$(whoami)}" NFSHomeDirectory 2>/dev/null | awk '{print $2}')
fi
_home_canon="$HOME"
if [ -d "$_home_canon" ]; then
_home_canon=$(CDPATH= cd -P -- "$_home_canon" 2>/dev/null && pwd -P) || _home_canon="$HOME"
fi
_default_home_canon="$_default_home"
if [ -n "$_default_home_canon" ] && [ -d "$_default_home_canon" ]; then
_default_home_canon=$(CDPATH= cd -P -- "$_default_home_canon" 2>/dev/null && pwd -P) || _default_home_canon="$_default_home"
fi
if [ -n "$_default_home_canon" ] && [ "$_home_canon" != "$_default_home_canon" ]; then
STUDIO_HOME="$HOME/.unsloth/studio"
DATA_DIR="$HOME/.local/share/unsloth"
_LOCAL_BIN="$HOME/.local/bin"
_STUDIO_HOME_REDIRECT=home
substep "HOME redirected ($HOME); install follows \$HOME"
return 0
fi
STUDIO_HOME="$HOME/.unsloth/studio"
DATA_DIR="$HOME/.local/share/unsloth"
_LOCAL_BIN="$HOME/.local/bin"
_STUDIO_HOME_REDIRECT=default
}
# Records which cache this install used, so an update reuses it rather than guessing: the launch below repoints the backend at the Studio cache even in shared mode, so one on-demand install makes an empty Studio cache look full. Never fatal. A relative UV_CACHE_DIR names a different directory in each phase of one install, since uv resolves it against its working directory and setup.sh changes into its own before the dependency pass, so make it absolute once, here.
_absolutize_uv_cache_dir() {
case "$UV_CACHE_DIR" in
/*) return 0 ;;
esac
_uv_cache_base="${UV_WORKING_DIR:-$PWD}"
case "$_uv_cache_base" in
/*) ;;
*) _uv_cache_base="$PWD/$_uv_cache_base" ;;
esac
UV_CACHE_DIR="$_uv_cache_base/$UV_CACHE_DIR"
}
_record_uv_cache_choice() {
# In place, before anything reads it: every branch records, so this is the one point every phase of the install and the marker are made to agree on one directory.
_absolutize_uv_cache_dir
_uv_marker_dir="$STUDIO_HOME/cache"
_uv_marker_file="$_uv_marker_dir/uv-cache-dir"
_uv_marker_value="$UV_CACHE_DIR"
# Remembered so a failed install can put it back.
if [ "$_UV_MARKER_SAVED" != true ]; then
if [ -e "$_uv_marker_file" ] || [ -L "$_uv_marker_file" ]; then
# One we cannot read is one we cannot put back, so leave it alone.
_UV_MARKER_PREVIOUS=$(cat "$_uv_marker_file" 2>/dev/null) || return 0
_UV_MARKER_EXISTED=true
else
_UV_MARKER_PREVIOUS=""
_UV_MARKER_EXISTED=false
fi
_UV_MARKER_SAVED=true
fi
(
mkdir -p "$_uv_marker_dir" 2>/dev/null &&
# Unlinked first: a redirection follows a symlink and truncates its target.
rm -f "$_uv_marker_file" 2>/dev/null &&
# And only once gone: rm can fail on a link in an undeletable directory.
! { [ -e "$_uv_marker_file" ] || [ -L "$_uv_marker_file" ]; } &&
printf '%s\n' "$_uv_marker_value" > "$_uv_marker_file" 2>/dev/null
) || true
}
_restore_uv_cache_marker() {
[ "${_STUDIO_INSTALL_COMMITTED:-false}" = true ] && return 0
[ "$_UV_MARKER_SAVED" = true ] || return 0
_uv_marker_file="$STUDIO_HOME/cache/uv-cache-dir"
rm -f "$_uv_marker_file" 2>/dev/null || true
if [ "$_UV_MARKER_EXISTED" = true ] \
&& ! { [ -e "$_uv_marker_file" ] || [ -L "$_uv_marker_file" ]; }; then
printf '%s\n' "$_UV_MARKER_PREVIOUS" > "$_uv_marker_file" 2>/dev/null || true
fi
_UV_MARKER_SAVED=false
}
_configure_uv_cache() {
_uv_studio_cache="$STUDIO_HOME/cache/uv"
case "${UV_CACHE_DIR-}" in
*[![:space:]]*)
_UV_CACHE_MODE=custom
export UV_CACHE_DIR
# Recorded like any other choice; a caller still outranks the marker.
_record_uv_cache_choice
step "uv cache" "preserving custom UV_CACHE_DIR ($UV_CACHE_DIR)"
return 0
;;
esac
if [ "$_ISOLATE_UV_CACHE" = true ]; then
UV_CACHE_DIR="$_uv_studio_cache"
_UV_CACHE_MODE=isolated
export UV_CACHE_DIR
_record_uv_cache_choice
step "uv cache" "forced Studio cache isolation ($UV_CACHE_DIR); already-cached packages may download again" "$C_WARN"
return 0
fi
# Ask uv so uv.toml / UV_CONFIG_FILE / platform defaults count; -u so a blank inherited value cannot override them; last line so a notice ahead of the path does not become the path.
_uv_default_cache=$(env -u UV_CACHE_DIR uv cache dir 2>/dev/null \
| sed -e 's/[[:space:]]*$//' -e '/^$/d' | tail -n 1) || _uv_default_cache=""
if [ -z "$_uv_default_cache" ]; then
if [ -n "${XDG_CACHE_HOME:-}" ]; then
_uv_default_cache="${XDG_CACHE_HOME}/uv"
elif [ -n "${HOME:-}" ]; then
_uv_default_cache="${HOME}/.cache/uv"
fi
fi
_uv_default_populated=false
_uv_scan_blocked=false
if [ -n "$_uv_default_cache" ] && [ -d "$_uv_default_cache" ] && [ -r "$_uv_default_cache" ]; then
# Warm means package BYTES: wheels-* is metadata only (.msgpack/.http on uv 0.10), so a bare `--dry-run` used to read as warm. -L to match Get-ChildItem.
for _uv_bucket in \
"$_uv_default_cache"/archive-* \
"$_uv_default_cache"/builds-* \
"$_uv_default_cache"/built-wheels-* \
"$_uv_default_cache"/wheels-* \
"$_uv_default_cache"/sdists-*; do
[ -d "$_uv_bucket" ] || continue
# Unreadable is not empty; remembered so the message below says why.
if [ ! -r "$_uv_bucket" ] || [ ! -x "$_uv_bucket" ]; then
_uv_scan_blocked=true
continue
fi
_uv_artifact=$(find -L "$_uv_bucket" -type f \
! -name CACHEDIR.TAG ! -name .git ! -name .gitignore \
! -name '*.lock' ! -name '*.msgpack' ! -name '*.http' ! -name '*.rev' \
-print 2>/dev/null | head -n 1) || _uv_artifact=""
if [ -n "$_uv_artifact" ]; then
_uv_default_populated=true
break
fi
done
fi
if [ "$_uv_default_populated" = true ]; then
UV_CACHE_DIR="$_uv_default_cache"
_UV_CACHE_MODE=shared
else
UV_CACHE_DIR="$_uv_studio_cache"
_UV_CACHE_MODE=studio
fi
export UV_CACHE_DIR
_record_uv_cache_choice
case "$_UV_CACHE_MODE" in
shared)
step "uv cache" "reusing existing shared cache ($UV_CACHE_DIR) to avoid duplicate Torch/CUDA downloads; use --isolated-uv-cache to isolate"
;;
studio)
if [ "$_uv_scan_blocked" = true ]; then
step "uv cache" "using new Studio-owned cache ($UV_CACHE_DIR); part of $_uv_default_cache could not be read, so cached packages may download again" "$C_WARN"
else
step "uv cache" "using new Studio-owned cache ($UV_CACHE_DIR)"
fi
;;
esac
}
_prepare_studio_uv_cache_for_launch() {
[ "${_UV_CACHE_MODE:-}" = shared ] || return 0
UV_CACHE_DIR="$STUDIO_HOME/cache/uv"
export UV_CACHE_DIR
}
_resolve_studio_destinations
# The PATH we inherited, before anything below prepends to it. The shim setup at the end asks whether a NEW login shell will find _LOCAL_BIN, and by then this process has prepended it several times (uv bootstrap, venv), so testing $PATH there answers yes for a shell that would answer no and the profile entry never gets written. astral's installer used to write that line for us; the pinned path does not.
_UNSLOTH_LOGIN_PATH="$PATH"
VENV_DIR="$STUDIO_HOME/unsloth_studio"
# Claim the root before anything of ours goes into it: the uv cache, the venv and the venv's own
# marker all land inside $STUDIO_HOME, so an install that dies in between used to leave a
# directory the uninstaller could only identify by guessing at leftovers. Never fatal.
#
# Only a root this run may take over: in env mode $STUDIO_HOME is a user-chosen workspace, so an
# empty one, or one already carrying an unambiguous marker, and nothing else, or a run that
# aborts at the venv-step guard leaves somebody's project marked. Shorter than that guard's list
# on purpose: it only refuses to overwrite, this authorizes a delete, so no bin/unsloth.
# A sentinel this list may trust: a regular file, never a link, never inside a linked directory
# ($2). -f follows a link and -L answers for the named file only, so a planted marker or a linked
# `share` holding a genuine one would otherwise short-circuit the emptiness test below.
_claim_sentinel() {
[ -f "$1" ] || return 1
[ -L "$1" ] && return 1
[ -n "${2:-}" ] && [ -L "$2" ] && return 1
return 0
}
_claim_studio_root() {
_claim_marker="$STUDIO_HOME/.unsloth-studio-owned"
# Already ours and the right shape: leave it. A run killed between the unlink and the write
# would lose the only proof this root is ours.
_claim_sentinel "$_claim_marker" && return 0
if [ "$_STUDIO_HOME_REDIRECT" = "env" ] \
&& ! _claim_sentinel "$VENV_DIR/.unsloth-studio-owned" "$VENV_DIR" \
&& ! _claim_sentinel "$STUDIO_HOME/share/studio.conf" "$STUDIO_HOME/share"; then
if [ -d "$STUDIO_HOME" ]; then
# Not enumerable: without read the globs cannot expand and an occupied workspace
# reads as empty. Fail closed like _dir_has_entries.
{ [ -r "$STUDIO_HOME" ] && [ -x "$STUDIO_HOME" ]; } || return 0
# The globs ARE the emptiness check, so a caller's `sh -f` would make every workspace
# look empty. Saved and restored like _dir_has_entries.
_claim_glob=on
case $- in *f*) _claim_glob=off ;; esac
set +f
_claim_empty=true
for _claim_entry in "$STUDIO_HOME"/* "$STUDIO_HOME"/.[!.]* "$STUDIO_HOME"/..?*; do
if [ -e "$_claim_entry" ] || [ -L "$_claim_entry" ]; then _claim_empty=false; break; fi
done
[ "$_claim_glob" = off ] && set -f
[ "$_claim_empty" = true ] || return 0
fi
fi
mkdir -p "$STUDIO_HOME" 2>/dev/null || true
# Unlink first, then confirm it: the redirection follows a symlink here and truncates its
# TARGET, and rm can fail on a root we cannot write while that target stays writable. No
# marker is fine; the venv writes its own later.
rm -f "$_claim_marker" 2>/dev/null || true
if [ -e "$_claim_marker" ] || [ -L "$_claim_marker" ]; then return 0; fi
printf '' > "$_claim_marker" 2>/dev/null || true
}
_claim_studio_root
# Keep uv's cache on the same filesystem as the venv it fills.
# uv hardlinks wheels within one filesystem and copies across a boundary, so a moved STUDIO_HOME paid double the disk and stranded the cache. An explicit UV_CACHE_DIR wins. The fallback is required, since uv aborts on a cache it cannot create; mkdir -p exits 0 for an existing unwritable directory and -w reads the mode rather than the filesystem, so probe with a real create.
if [ -z "${UV_CACHE_DIR:-}" ]; then
UV_CACHE_DIR="$STUDIO_HOME/cache/uv"
export UV_CACHE_DIR
# mktemp, not a $$ name: a predictable path in another account's directory can be pre-created as a symlink for `: >` to follow and truncate as root.
_uv_cache_probe=""
if ! mkdir -p "$UV_CACHE_DIR" 2>/dev/null \
|| ! _uv_cache_probe=$(mktemp "$UV_CACHE_DIR/.unsloth-write-probe.XXXXXX" 2>/dev/null); then
echo "[WARN] Cannot write to $UV_CACHE_DIR -- using uv's default cache." >&2
echo "[WARN] Wheels will be copied into the venv rather than hardlinked, costing extra disk." >&2
unset UV_CACHE_DIR
fi
[ -z "$_uv_cache_probe" ] || rm -f "$_uv_cache_probe" 2>/dev/null || true
unset _uv_cache_probe
fi
_VENV_ROLLBACK_DIR=""
_VENV_ROLLBACK_TARGET="$VENV_DIR"
_VENV_ROLLBACK_ACTIVE=false
# The marker travels with the environment. See _record_uv_cache_choice.
_UV_MARKER_SAVED=false
_UV_MARKER_EXISTED=false
_UV_MARKER_PREVIOUS=""
# One flag for both rollbacks: two leave a window either way round, where a signal restores half a committed install.
_STUDIO_INSTALL_COMMITTED=false
_start_studio_venv_replacement() {
_existing_dir="$1"
_stamp=$(date +%Y%m%d%H%M%S 2>/dev/null || echo "time")
_candidate="$STUDIO_HOME/unsloth_studio.rollback.$_stamp.$$"
_suffix=0
while [ -e "$_candidate" ] || [ -L "$_candidate" ]; do
_suffix=$((_suffix + 1))
_candidate="$STUDIO_HOME/unsloth_studio.rollback.$_stamp.$$.$_suffix"
done
_VENV_ROLLBACK_DIR="$_candidate"
_VENV_ROLLBACK_TARGET="$_existing_dir"
_VENV_ROLLBACK_ACTIVE=true
# Publish the rollback state before the atomic rename so a signal cannot land after mv but before the exit handlers know where the old venv went.
if ! mv "$_existing_dir" "$_candidate"; then
_VENV_ROLLBACK_ACTIVE=false
_VENV_ROLLBACK_DIR=""
return 1
fi
substep "previous environment preserved for rollback"
}
# uv creates only into a path that is absent or an empty directory. Everything else is occupied, hidden entries and non-resolving symlinks included.
_dir_has_entries() { # dir
if [ ! -d "$1" ]; then
# Still an existing path to mkdir(2), which answers EEXIST for a file or for a symlink "dangling or not", so uv refuses it too. -d follows the link and -e misses a dangling one, hence the -L.
{ [ -e "$1" ] || [ -L "$1" ]; } && return 0
return 1
fi
# Not enumerable: the globs cannot expand without read, and the tests below fail on every name without search, so it would read as empty. Fail closed like install.ps1's catch; the rename only needs write on the parent.
{ [ -r "$1" ] && [ -x "$1" ]; } || return 0
# The globs are the whole check, so a caller's set -f would make every directory look empty. Mirrors _path_has_dir, which saves the flag too.
_dhe_glob=on
case $- in *f*) _dhe_glob=off ;; esac
set +f
_dhe_found=1
for _dhe_entry in "$1"/* "$1"/.[!.]* "$1"/..?*; do
if [ -e "$_dhe_entry" ] || [ -L "$_dhe_entry" ]; then
_dhe_found=0
break
fi
done
[ "$_dhe_glob" = off ] && set -f
return "$_dhe_found"
}
# Clear $VENV_DIR for a recreate without ever destroying the only copy. The legacy-layout migration below moves $STUDIO_HOME/.venv straight into $VENV_DIR without going through _start_studio_venv_replacement, so a plain `rm -rf` there is unrecoverable: if the `uv venv` that follows cannot resolve an interpreter the user is left with no environment at all. Move it aside instead and let the exit/signal traps put it back. When a replacement is already in flight the rollback copy holds the user's real environment and $VENV_DIR is this run's own work, so plain removal stays correct.
_discard_venv_for_recreate() { # venv dir
if [ "$_VENV_ROLLBACK_ACTIVE" != true ] && [ -d "$1" ] \
&& _start_studio_venv_replacement "$1"; then
return 0
fi
rm -rf "$1"
}
_restore_studio_venv_replacement() {
# The flag the marker restore consults too, so a signal mid-commit cannot split them.
[ "${_STUDIO_INSTALL_COMMITTED:-false}" = true ] && return 0
[ "$_VENV_ROLLBACK_ACTIVE" = true ] || return 0
# -e/-L, not -d: a rollback holds whatever _dir_has_entries called occupied, and -d would drop a file or a dangling link and strand the original.
[ -n "$_VENV_ROLLBACK_DIR" ] \
&& { [ -e "$_VENV_ROLLBACK_DIR" ] || [ -L "$_VENV_ROLLBACK_DIR" ]; } || {
_VENV_ROLLBACK_ACTIVE=false
return 0
}
rollback_substep "restoring previous environment after failed install..." "$C_WARN"
rm -rf "$_VENV_ROLLBACK_TARGET"
if mv "$_VENV_ROLLBACK_DIR" "$_VENV_ROLLBACK_TARGET"; then
rollback_substep "restored previous environment"
_VENV_ROLLBACK_ACTIVE=false
_VENV_ROLLBACK_DIR=""
else
echo "⚠️ Could not restore previous environment from $_VENV_ROLLBACK_DIR to $_VENV_ROLLBACK_TARGET" >&2
fi
}
_studio_venv_rollback_must_be_preserved() {
_rollback_name=${1##*/}
_rollback_metadata=${_rollback_name#unsloth_studio.rollback.}
_rollback_stamp=${_rollback_metadata%%.*}
_rollback_process=${_rollback_metadata#*.}
# Preserve anything outside the installer's timestamp.PID[.suffix] format.
[ "$_rollback_process" != "$_rollback_metadata" ] || return 0
case "$_rollback_stamp" in
time) ;;
''|*[!0-9]*) return 0 ;;
*) [ "${#_rollback_stamp}" -eq 14 ] || return 0 ;;
esac
_rollback_pid=${_rollback_process%%.*}
case "$_rollback_pid" in
''|*[!0-9]*) return 0 ;;
esac
_rollback_suffix=${_rollback_process#*.}
if [ "$_rollback_suffix" != "$_rollback_process" ]; then
case "$_rollback_suffix" in ''|*[!0-9]*) return 0 ;; esac
fi
kill -0 "$_rollback_pid" 2>/dev/null
}
_prune_stale_studio_venv_rollbacks() {
for _stale_rollback in "$STUDIO_HOME"/unsloth_studio.rollback.*; do
[ -d "$_stale_rollback" ] || continue
if [ -L "$_stale_rollback" ]; then
echo "⚠️ Refusing to remove rollback symlink $_stale_rollback" >&2
continue
fi
# A concurrent installer may have moved its live venv aside. The PID in the generated name keeps this successful run from deleting its rescue copy.
_studio_venv_rollback_must_be_preserved "$_stale_rollback" && continue
if rm -rf "$_stale_rollback"; then
substep "removed stale environment rollback ${_stale_rollback##*/}"
else
echo "⚠️ Could not remove stale environment rollback $_stale_rollback" >&2
fi
done
}
_commit_studio_venv_replacement() {
# First and alone, because a signal can land between any two statements. A first install rolls nothing back and still commits.
_STUDIO_INSTALL_COMMITTED=true
_UV_MARKER_SAVED=false
if [ "$_VENV_ROLLBACK_ACTIVE" = true ]; then
_rollback_to_remove="$_VENV_ROLLBACK_DIR"
# The new environment is already committed. Clear the restore state before deletion so an interrupt cannot replace it with a half-deleted backup.
_VENV_ROLLBACK_ACTIVE=false
_VENV_ROLLBACK_DIR=""
# Same shapes as the restore, or such a backup is never cleaned up.
if [ -n "$_rollback_to_remove" ] \
&& { [ -e "$_rollback_to_remove" ] || [ -L "$_rollback_to_remove" ]; }; then
if ! rm -rf "$_rollback_to_remove"; then
echo "⚠️ Could not remove environment rollback $_rollback_to_remove" >&2
fi
fi
fi
# Only prune older orphaned copies after the replacement has succeeded, so an interrupted install never discards the last known-good environment.
_prune_stale_studio_venv_rollbacks
}
_cleanup_install_temporaries() {
[ -n "${_UV_OVERRIDE_TMPDIR:-}" ] && rm -rf "$_UV_OVERRIDE_TMPDIR" 2>/dev/null || true
[ -n "${_UV_INSTALL_NAME_TOOL_SHIM_DIR:-}" ] && rm -rf "$_UV_INSTALL_NAME_TOOL_SHIM_DIR" 2>/dev/null || true
[ -n "${_UV_VENV_CAPTURE_DIR:-}" ] && rm -rf "$_UV_VENV_CAPTURE_DIR" 2>/dev/null || true
[ -n "${_UNSLOTH_TORCH_OVERRIDES:-}" ] && rm -f "$_UNSLOTH_TORCH_OVERRIDES" 2>/dev/null || true
# The pinned uv path's own cleanup only runs when that function returns, so a Ctrl-C left the unpacked archive behind plus a staging file inside a directory that is on PATH.
[ -n "${_UIP_WORK:-}" ] && rm -rf "$_UIP_WORK" 2>/dev/null || true
[ -n "${_UIP_STAGE:-}" ] && rm -f "$_UIP_STAGE" 2>/dev/null || true
[ -n "${_UIP_STAGE2:-}" ] && rm -f "$_UIP_STAGE2" 2>/dev/null || true
[ -n "${_ROCM_TAG_MEMO_DIR:-}" ] && rm -rf "$_ROCM_TAG_MEMO_DIR" 2>/dev/null || true
}
_on_install_exit() {
_status=$?
if [ "$_status" -ne 0 ]; then
_restore_studio_venv_replacement
# Separate from the venv restore: an install can fail before one is in flight.
_restore_uv_cache_marker
fi
_cleanup_install_temporaries
exit "$_status"
}
_on_install_signal() {
_signal_status="$1"
# EXIT is disabled to avoid a second cleanup pass. Ignore further termination signals until the old environment is back in place.
trap - EXIT
trap '' HUP INT TERM
_restore_studio_venv_replacement
_restore_uv_cache_marker
_cleanup_install_temporaries
exit "$_signal_status"
}
# Clear inherited cleanup targets before installing traps.
_UV_OVERRIDE_TMPDIR=""
_UV_INSTALL_NAME_TOOL_SHIM_DIR=""
_UV_VENV_CAPTURE_DIR=""
_UNSLOTH_TORCH_OVERRIDES=""
_UIP_WORK=""
_UIP_STAGE=""
_UIP_STAGE2=""
_ROCM_TAG_MEMO_DIR=""
_ROCM_TAG_MEMO=""
trap _on_install_exit EXIT
trap '_on_install_signal 129' HUP
trap '_on_install_signal 130' INT
trap '_on_install_signal 143' TERM
# ── Helper: download a URL to a file (supports curl and wget) ──
download() {
if command -v curl >/dev/null 2>&1; then
curl -LsSf "$1" -o "$2"
elif command -v wget >/dev/null 2>&1; then
wget -qO "$2" "$1"
else
echo "Error: neither curl nor wget found. Install one and re-run."
exit 1
fi
}
# ── Helper: check if a single package is available on the system ──
_is_pkg_installed() {
case "$1" in
build-essential) command -v gcc >/dev/null 2>&1 ;;
libcurl4-openssl-dev)
command -v dpkg >/dev/null 2>&1 && dpkg -s "$1" >/dev/null 2>&1 ;;
pciutils)