-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmuscriptor_manager.ps1
More file actions
1454 lines (1284 loc) · 53.4 KB
/
Copy pathmuscriptor_manager.ps1
File metadata and controls
1454 lines (1284 loc) · 53.4 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
[CmdletBinding()]
param (
[Alias('d')]
[string]$Directory,
[Alias('t')]
[string]$Token,
[Alias('m')]
[ValidateSet('small', 'medium', 'large')]
[string]$Model = 'large',
[ValidateSet('auto', 'cpu', 'cuda')]
[string]$Device = 'auto',
[ValidateSet('auto', 'cpu', 'cu118', 'cu121', 'cu124', 'cu126', 'cu128', 'cu130')]
[string]$TorchBackend = 'auto',
[Alias('p')]
[ValidateRange(1, 65535)]
[int]$Port = 8222,
[ValidateRange(1, 3600)]
[int]$StartupTimeout = 180,
[string]$BindAddress = '127.0.0.1',
[Alias('h')]
[Switch]$Help,
[Switch]$Install,
[Switch]$Update,
[Switch]$Download,
[Switch]$DownloadAll,
[Switch]$ForceDownload,
[Switch]$ListModels,
[Switch]$GpuInfo,
[Switch]$Start,
[Switch]$Restart,
[Switch]$Stop,
[Switch]$Status,
[Switch]$Uninstall,
[Switch]$SaveToken,
[Switch]$ClearSavedToken,
[Switch]$NonInteractive,
[Switch]$Pause
)
Set-StrictMode -Version 2.0
$ErrorActionPreference = 'Stop'
$ModelNames = @('small', 'medium', 'large')
$EnvPath = $null
$CachePath = $null
$LogPath = $null
$PidFile = $null
$StateFile = $null
$InstallMarker = $null
$PythonExe = $null
$MuscriptorExe = $null
$StdOutLog = $null
$StdErrLog = $null
$InstallationVariableName = 'Muscriptor'
function Write-Step {
param([Parameter(Mandatory = $true)][string]$Message)
Write-Host "`n== $Message ==" -ForegroundColor Cyan
}
function Pause-IfRequested {
if (-not $Pause -or -not [Environment]::UserInteractive) {
return
}
Write-Host "`nPress any key to continue..." -ForegroundColor DarkGray
[void][Console]::ReadKey($true)
}
function Enable-Utf8Runtime {
# MuScriptor emits Unicode symbols while processing audio. Windows consoles
# configured for a legacy code page (for example cp1251) otherwise crash Python's print().
$utf8 = New-Object System.Text.UTF8Encoding($false)
[Console]::OutputEncoding = $utf8
$global:OutputEncoding = $utf8
$env:PYTHONUTF8 = '1'
$env:PYTHONIOENCODING = 'utf-8'
}
function Set-ManagerPaths {
param([Parameter(Mandatory = $true)][string]$TargetDirectory)
$script:Directory = $TargetDirectory.Trim().Trim('"')
if ([string]::IsNullOrWhiteSpace($script:Directory)) {
throw 'The installation directory is empty. Specify -Directory explicitly.'
}
$script:EnvPath = Join-Path $script:Directory 'muscriptor_env'
$script:CachePath = Join-Path $script:Directory 'HuggingFaceCache'
$script:LogPath = Join-Path $script:Directory 'logs'
$script:PidFile = Join-Path $script:Directory 'muscriptor.pid'
$script:StateFile = Join-Path $script:Directory 'muscriptor.state.json'
$script:InstallMarker = Join-Path $script:Directory '.muscriptor-manager'
$script:PythonExe = Join-Path $script:EnvPath 'Scripts\python.exe'
$script:MuscriptorExe = Join-Path $script:EnvPath 'Scripts\muscriptor.exe'
$script:StdOutLog = Join-Path $script:LogPath 'muscriptor.out.log'
$script:StdErrLog = Join-Path $script:LogPath 'muscriptor.err.log'
}
function Get-DefaultInstallationDirectory {
if (Test-Path -LiteralPath 'D:\') {
return 'D:\Muscriptor'
}
return 'C:\Muscriptor'
}
function Test-MuScriptorEnvironmentDirectory {
param([string]$TargetDirectory)
if ([string]::IsNullOrWhiteSpace($TargetDirectory)) {
return $false
}
$cleanDirectory = $TargetDirectory.Trim().Trim('"')
$python = Join-Path $cleanDirectory 'muscriptor_env\Scripts\python.exe'
$executable = Join-Path $cleanDirectory 'muscriptor_env\Scripts\muscriptor.exe'
return (Test-Path -LiteralPath $python -PathType Leaf) -and
(Test-Path -LiteralPath $executable -PathType Leaf)
}
function Get-RegisteredInstallationDirectory {
foreach ($scope in @('Machine', 'User')) {
$candidate = [Environment]::GetEnvironmentVariable($InstallationVariableName, $scope)
if ((-not [string]::IsNullOrWhiteSpace($candidate)) -and
(Test-MuScriptorEnvironmentDirectory -TargetDirectory $candidate)) {
return [PSCustomObject]@{
Directory = $candidate.Trim().Trim('"')
Scope = $scope
}
}
}
return $null
}
function Test-IsAdministrator {
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object Security.Principal.WindowsPrincipal($identity)
return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}
function Register-InstallationDirectory {
Set-Content -LiteralPath $InstallMarker -Value 'Managed by MuScriptor Manager.' -Encoding Ascii
$target = Get-NormalizedPathEntry -PathEntry $Directory
$machineDirectory = [Environment]::GetEnvironmentVariable($InstallationVariableName, 'Machine')
if ((-not [string]::IsNullOrWhiteSpace($machineDirectory)) -and
(Get-NormalizedPathEntry -PathEntry $machineDirectory) -eq $target) {
[Environment]::SetEnvironmentVariable($InstallationVariableName, $Directory, 'Process')
return
}
$scope = 'Machine'
if (-not (Test-IsAdministrator)) {
$scope = 'User'
$userDirectory = [Environment]::GetEnvironmentVariable($InstallationVariableName, 'User')
if ((-not [string]::IsNullOrWhiteSpace($userDirectory)) -and
(Get-NormalizedPathEntry -PathEntry $userDirectory) -eq $target) {
[Environment]::SetEnvironmentVariable($InstallationVariableName, $Directory, 'Process')
return
}
Write-Warning "Run PowerShell as Administrator to store $InstallationVariableName as a system variable. It will be stored for the current user instead."
}
[Environment]::SetEnvironmentVariable($InstallationVariableName, $Directory, $scope)
[Environment]::SetEnvironmentVariable($InstallationVariableName, $Directory, 'Process')
Write-Host "Registered $InstallationVariableName=$Directory ($scope environment)." -ForegroundColor Green
}
function Unregister-InstallationDirectory {
$target = Get-NormalizedPathEntry -PathEntry $Directory
foreach ($scope in @('Machine', 'User')) {
$registeredDirectory = [Environment]::GetEnvironmentVariable($InstallationVariableName, $scope)
if ([string]::IsNullOrWhiteSpace($registeredDirectory) -or
(Get-NormalizedPathEntry -PathEntry $registeredDirectory) -ne $target) {
continue
}
if ($scope -eq 'Machine' -and -not (Test-IsAdministrator)) {
throw "Run PowerShell as Administrator to remove the system variable $InstallationVariableName."
}
[Environment]::SetEnvironmentVariable($InstallationVariableName, $null, $scope)
Write-Host "Removed $InstallationVariableName from the $scope environment." -ForegroundColor Yellow
}
$processDirectory = [Environment]::GetEnvironmentVariable($InstallationVariableName, 'Process')
if ((-not [string]::IsNullOrWhiteSpace($processDirectory)) -and
(Get-NormalizedPathEntry -PathEntry $processDirectory) -eq $target) {
[Environment]::SetEnvironmentVariable($InstallationVariableName, $null, 'Process')
}
}
function Resolve-InstallationDirectory {
if (-not [string]::IsNullOrWhiteSpace($Directory)) {
Set-ManagerPaths -TargetDirectory $Directory
return
}
$defaultDirectory = Get-DefaultInstallationDirectory
$registeredInstallation = Get-RegisteredInstallationDirectory
if ($registeredInstallation) {
Set-ManagerPaths -TargetDirectory $registeredInstallation.Directory
Write-Host "Existing installation detected: $Directory (registered in $($registeredInstallation.Scope) environment)." -ForegroundColor Green
return
}
Set-ManagerPaths -TargetDirectory $defaultDirectory
$needsInstallation = -not ($Status -or $Stop -or $Uninstall -or $ListModels -or $GpuInfo)
if (-not $needsInstallation -or $NonInteractive) {
if ($NonInteractive -and $needsInstallation) {
Write-Host "Installation directory was not specified. Using: $defaultDirectory" -ForegroundColor Yellow
}
return
}
$selectedDirectory = Read-Host "Installation directory [$defaultDirectory]"
if ([string]::IsNullOrWhiteSpace($selectedDirectory)) {
$selectedDirectory = $defaultDirectory
}
Set-ManagerPaths -TargetDirectory $selectedDirectory
Write-Host "Installation directory: $Directory" -ForegroundColor Cyan
}
function Show-HelpMessage {
Write-Host @'
MuScriptor Manager for Windows
USAGE
.\muscriptor_manager.ps1 [options]
RUN OPTIONS
-Model small|medium|large Model to run (default: large)
-Device auto|cpu|cuda Inference device (default: auto)
-TorchBackend auto|cpu|cu118|cu121|cu124|cu126|cu128|cu130
PyTorch build used during installation; auto detects GPU
-Port <1-65535> Web UI port (default: 8222)
-BindAddress <address> Bind address (default: 127.0.0.1)
-Start Start in the background
-Restart Restart in the background
-Stop Stop the managed server
-Status Show server, environment, and model status
INSTALL AND MODEL OPTIONS
-Install Install/repair the environment, then exit
-Update Upgrade to the newest GPU-compatible PyTorch build
-Download Download the selected model, then exit
-DownloadAll Download small, medium, and large, then exit
-ForceDownload Re-download files with -Download/-DownloadAll
-ListModels Show which model variants are cached
-GpuInfo Show GPU, driver, and recommended PyTorch CUDA build
-Token <hf_...> Hugging Face read token for this run
-SaveToken Save the token in the user environment (plain text)
-NonInteractive Never prompt; fail if a required token is absent
MAINTENANCE OPTIONS
-Directory <path> Environment/cache directory; prompted on first install
-Uninstall Remove the managed environment and model cache
-ClearSavedToken Also remove the user-level HF_TOKEN
-StartupTimeout <seconds> Background readiness timeout (default: 180)
-Pause Wait for a key before the script closes
-Help Show this help
EXAMPLES
.\muscriptor_manager.ps1 -Model medium
.\muscriptor_manager.ps1 -Model small -Device cpu -Start
.\muscriptor_manager.ps1 -GpuInfo
.\muscriptor_manager.ps1 -Update
.\muscriptor_manager.ps1 -DownloadAll
.\muscriptor_manager.ps1 -ListModels
.\muscriptor_manager.ps1 -Status
Without an action switch, the script installs anything missing, downloads the
selected model if necessary, and runs the server in the current console.
'@ -ForegroundColor Gray
}
function Assert-Windows {
if ($env:OS -ne 'Windows_NT') {
throw 'This manager targets Windows PowerShell. Use the official uvx command on Linux or macOS.'
}
}
function Initialize-ManagerDirectory {
if ([string]::IsNullOrWhiteSpace($Directory)) {
throw 'The installation directory is empty. Specify -Directory explicitly.'
}
if (-not (Test-Path -LiteralPath $Directory)) {
[void](New-Item -ItemType Directory -Path $Directory -Force)
}
if (-not (Test-Path -LiteralPath $CachePath)) {
[void](New-Item -ItemType Directory -Path $CachePath -Force)
}
# Keep the cache private to this manager instead of changing user-wide settings.
$env:HF_HOME = $CachePath
$env:HF_HUB_DISABLE_TELEMETRY = '1'
}
function Test-CanRemoveInstallationRoot {
if (-not (Test-Path -LiteralPath $Directory -PathType Container)) {
return $false
}
$fullDirectory = [IO.Path]::GetFullPath($Directory).TrimEnd('\\')
$rootDirectory = [IO.Path]::GetPathRoot($fullDirectory).TrimEnd('\\')
if ($fullDirectory -eq $rootDirectory) {
return $false
}
$managedNames = @('muscriptor_env', 'HuggingFaceCache', 'logs', 'muscriptor.pid', 'muscriptor.state.json', '.muscriptor-manager')
$items = @(Get-ChildItem -LiteralPath $Directory -Force -ErrorAction Stop)
if ($items.Count -eq 0) {
return $false
}
return @($items | Where-Object { $_.Name -notin $managedNames }).Count -eq 0
}
function Invoke-ExternalCommand {
param(
[Parameter(Mandatory = $true)][string]$FilePath,
[Parameter(Mandatory = $true)][string[]]$ArgumentList,
[Parameter(Mandatory = $true)][string]$FailureMessage
)
& $FilePath @ArgumentList | Out-Host
if ($LASTEXITCODE -ne 0) {
throw "$FailureMessage (exit code $LASTEXITCODE)."
}
}
function Update-ProcessPath {
$machinePath = [Environment]::GetEnvironmentVariable('Path', 'Machine')
$userPath = [Environment]::GetEnvironmentVariable('Path', 'User')
$env:Path = "$machinePath;$userPath"
}
function Get-NormalizedPathEntry {
param([Parameter(Mandatory = $true)][string]$PathEntry)
$value = $PathEntry.Trim().Trim('"')
if ([string]::IsNullOrWhiteSpace($value)) {
return ''
}
try {
return [IO.Path]::GetFullPath($value).TrimEnd('\\').ToUpperInvariant()
} catch {
return $value.TrimEnd('\\').ToUpperInvariant()
}
}
function Update-CurrentProcessPath {
param([Parameter(Mandatory = $true)][string[]]$Entries)
$env:Path = ($Entries -join ';')
}
function Add-InstallationDirectoryToUserPath {
$target = Get-NormalizedPathEntry -PathEntry $Directory
$userPath = [Environment]::GetEnvironmentVariable('Path', 'User')
$entries = @($userPath -split ';' | ForEach-Object { $_.Trim() } | Where-Object { $_ })
$containsTarget = @($entries | Where-Object { (Get-NormalizedPathEntry -PathEntry $_) -eq $target }).Count -gt 0
if (-not $containsTarget) {
$entries += $Directory
[Environment]::SetEnvironmentVariable('Path', ($entries -join ';'), 'User')
Write-Host "Added installation directory to user PATH: $Directory" -ForegroundColor Green
}
$processEntries = @($env:Path -split ';' | ForEach-Object { $_.Trim() } | Where-Object { $_ })
if (@($processEntries | Where-Object { (Get-NormalizedPathEntry -PathEntry $_) -eq $target }).Count -eq 0) {
Update-CurrentProcessPath -Entries @($processEntries + $Directory)
}
}
function Remove-InstallationDirectoryFromUserPath {
$target = Get-NormalizedPathEntry -PathEntry $Directory
$userPath = [Environment]::GetEnvironmentVariable('Path', 'User')
$entries = @($userPath -split ';' | ForEach-Object { $_.Trim() } | Where-Object { $_ })
$remainingEntries = @($entries | Where-Object { (Get-NormalizedPathEntry -PathEntry $_) -ne $target })
if ($remainingEntries.Count -ne $entries.Count) {
[Environment]::SetEnvironmentVariable('Path', ($remainingEntries -join ';'), 'User')
Write-Host "Removed installation directory from user PATH: $Directory" -ForegroundColor Yellow
}
$processEntries = @($env:Path -split ';' | ForEach-Object { $_.Trim() } | Where-Object { $_ })
Update-CurrentProcessPath -Entries @($processEntries | Where-Object {
(Get-NormalizedPathEntry -PathEntry $_) -ne $target
})
}
function Find-UvExecutable {
$command = Get-Command 'uv.exe' -CommandType Application -ErrorAction SilentlyContinue
if ($command) {
return $command.Source
}
$candidates = @()
if (-not [string]::IsNullOrWhiteSpace($env:USERPROFILE)) {
$candidates += Join-Path $env:USERPROFILE '.local\bin\uv.exe'
$candidates += Join-Path $env:USERPROFILE '.cargo\bin\uv.exe'
}
if (-not [string]::IsNullOrWhiteSpace($env:LOCALAPPDATA)) {
$candidates += Join-Path $env:LOCALAPPDATA 'Microsoft\WinGet\Links\uv.exe'
}
foreach ($candidate in $candidates) {
if (Test-Path -LiteralPath $candidate -PathType Leaf) {
return $candidate
}
}
return $null
}
function Install-Uv {
Write-Step 'Installing uv'
Write-Host 'uv was not found. Installing it with the official Astral installer...' -ForegroundColor Yellow
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$temporaryInstaller = Join-Path ([IO.Path]::GetTempPath()) "uv-install-$([Guid]::NewGuid().ToString('N')).ps1"
try {
(New-Object Net.WebClient).DownloadFile('https://astral.sh/uv/install.ps1', $temporaryInstaller)
$powerShellExecutable = Join-Path $PSHOME 'powershell.exe'
if (-not (Test-Path -LiteralPath $powerShellExecutable -PathType Leaf)) {
$powerShellExecutable = Join-Path $PSHOME 'pwsh.exe'
}
if (-not (Test-Path -LiteralPath $powerShellExecutable -PathType Leaf)) {
throw 'Unable to locate the current PowerShell executable.'
}
Invoke-ExternalCommand -FilePath $powerShellExecutable `
-ArgumentList @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $temporaryInstaller) `
-FailureMessage 'The official uv installer failed'
} catch {
throw "Unable to install uv automatically: $($_.Exception.Message)"
} finally {
Remove-Item -LiteralPath $temporaryInstaller -Force -ErrorAction SilentlyContinue
}
Update-ProcessPath
$uvExecutable = Find-UvExecutable
if (-not $uvExecutable) {
throw 'uv installation completed, but uv.exe was not found. Open a new terminal and run the script again.'
}
return $uvExecutable
}
function Get-UvExecutable {
$uvExecutable = Find-UvExecutable
if ($uvExecutable) {
return $uvExecutable
}
return Install-Uv
}
function Test-EnvironmentInstalled {
return (Test-Path -LiteralPath $PythonExe -PathType Leaf) -and
(Test-Path -LiteralPath $MuscriptorExe -PathType Leaf)
}
function Get-MuScriptorVersion {
if (-not (Test-Path -LiteralPath $PythonExe -PathType Leaf)) {
return $null
}
try {
$version = & $PythonExe -c "import importlib.metadata; print(importlib.metadata.version('muscriptor'))" 2>$null
if ($LASTEXITCODE -eq 0) {
return ($version | Select-Object -Last 1).Trim()
}
} catch {
return $null
}
return $null
}
function Get-NvidiaGpuInfo {
$nvidiaSmi = Get-Command 'nvidia-smi.exe' -CommandType Application -ErrorAction SilentlyContinue
if (-not $nvidiaSmi) {
$nvidiaSmi = Get-Command 'nvidia-smi' -CommandType Application -ErrorAction SilentlyContinue
}
if (-not $nvidiaSmi) {
return @()
}
try {
$rawOutput = & $nvidiaSmi.Source '--query-gpu=name,driver_version,compute_cap,memory.total' `
'--format=csv,noheader,nounits' 2>$null
if ($LASTEXITCODE -ne 0 -or -not $rawOutput) {
return @()
}
$devices = @()
foreach ($row in ($rawOutput | ConvertFrom-Csv -Header 'Name', 'DriverVersion', 'ComputeCapability', 'MemoryMiB')) {
try {
$capability = [double]::Parse($row.ComputeCapability.Trim(), [Globalization.CultureInfo]::InvariantCulture)
$driver = [Version]$row.DriverVersion.Trim()
$memory = [int]$row.MemoryMiB.Trim()
$devices += [PSCustomObject]@{
Name = $row.Name.Trim()
DriverVersion = $driver
ComputeCapability = $capability
MemoryMiB = $memory
}
} catch {
continue
}
}
return $devices
} catch {
return @()
}
}
function Get-RecommendedTorchBackend {
param([object[]]$GpuInfo = @(Get-NvidiaGpuInfo))
$devices = @($GpuInfo)
if ($devices.Count -eq 0) {
return [PSCustomObject]@{
Backend = 'cpu'
MinimumDriver = $null
RequiresDriverUpgrade = $false
PreferredBackend = 'cpu'
PreferredDriver = $null
DriverUpgradeRecommended = $false
Reason = 'No NVIDIA GPU was detected through nvidia-smi.'
}
}
$primaryGpu = $devices[0]
if ($primaryGpu.ComputeCapability -lt 5.0) {
return [PSCustomObject]@{
Backend = 'cpu'
MinimumDriver = $null
RequiresDriverUpgrade = $false
PreferredBackend = 'cpu'
PreferredDriver = $null
DriverUpgradeRecommended = $false
Reason = "GPU compute capability $($primaryGpu.ComputeCapability) is unsupported by current PyTorch CUDA wheels."
}
}
# PyTorch CUDA 12.6 is the newest binary line that still includes Pascal.
# CUDA 12.8+ and CUDA 13 drop Pascal, while 12.6 supports Pascal through PyTorch 2.12.
$candidateBackends = @()
if ($primaryGpu.ComputeCapability -ge 10.0) {
# RTX 50xx / Blackwell needs a wheel built with Blackwell support.
# Native Windows cu128 builds have known kernel-launch failures on some
# RTX 50xx cards, so require the current cu130 build instead.
$candidateBackends += [PSCustomObject]@{ Name = 'cu130'; MinimumDriver = [Version]'580.65'; MinimumCapability = 10.0 }
} elseif ($primaryGpu.ComputeCapability -ge 7.5) {
# Turing (RTX 20xx), Ampere (30xx), and Ada (40xx).
$candidateBackends += @(
[PSCustomObject]@{ Name = 'cu130'; MinimumDriver = [Version]'580.65'; MinimumCapability = 7.5 },
[PSCustomObject]@{ Name = 'cu126'; MinimumDriver = [Version]'560.76'; MinimumCapability = 5.0 },
[PSCustomObject]@{ Name = 'cu124'; MinimumDriver = [Version]'551.61'; MinimumCapability = 5.0 },
[PSCustomObject]@{ Name = 'cu121'; MinimumDriver = [Version]'531.14'; MinimumCapability = 5.0 },
[PSCustomObject]@{ Name = 'cu118'; MinimumDriver = [Version]'520.06'; MinimumCapability = 5.0 }
)
} else {
# Maxwell, Pascal, and Volta. cu126 is the newest PyTorch binary line
# that retains native support for the older architectures.
$candidateBackends += @(
[PSCustomObject]@{ Name = 'cu126'; MinimumDriver = [Version]'560.76'; MinimumCapability = 5.0 },
[PSCustomObject]@{ Name = 'cu124'; MinimumDriver = [Version]'551.61'; MinimumCapability = 5.0 },
[PSCustomObject]@{ Name = 'cu121'; MinimumDriver = [Version]'531.14'; MinimumCapability = 5.0 },
[PSCustomObject]@{ Name = 'cu118'; MinimumDriver = [Version]'520.06'; MinimumCapability = 5.0 }
)
}
$selected = $candidateBackends | Where-Object {
$primaryGpu.DriverVersion -ge $_.MinimumDriver -and $primaryGpu.ComputeCapability -ge $_.MinimumCapability
} | Select-Object -First 1
$preferred = $candidateBackends | Select-Object -First 1
if ($selected) {
return [PSCustomObject]@{
Backend = $selected.Name
MinimumDriver = $selected.MinimumDriver
RequiresDriverUpgrade = $false
PreferredBackend = $preferred.Name
PreferredDriver = $preferred.MinimumDriver
DriverUpgradeRecommended = $selected.Name -ne $preferred.Name
Reason = "GPU compute capability $($primaryGpu.ComputeCapability), NVIDIA driver $($primaryGpu.DriverVersion)."
}
}
return [PSCustomObject]@{
Backend = 'cpu'
MinimumDriver = $preferred.MinimumDriver
RequiresDriverUpgrade = $true
PreferredBackend = $preferred.Name
PreferredDriver = $preferred.MinimumDriver
DriverUpgradeRecommended = $true
Reason = "NVIDIA driver $($primaryGpu.DriverVersion) is too old for supported PyTorch CUDA wheels."
}
}
function Get-TorchBackendPlan {
$gpuInfo = @(Get-NvidiaGpuInfo)
$recommended = Get-RecommendedTorchBackend -GpuInfo $gpuInfo
if ($Device -eq 'cpu' -or $TorchBackend -eq 'cpu') {
return [PSCustomObject]@{
Backend = 'cpu'
Recommended = $recommended
GpuInfo = $gpuInfo
IsManual = $TorchBackend -ne 'auto'
}
}
if ($TorchBackend -eq 'auto') {
return [PSCustomObject]@{
Backend = $recommended.Backend
Recommended = $recommended
GpuInfo = $gpuInfo
IsManual = $false
}
}
$minimumCapability = 5.0
$minimumDriver = [Version]'520.06'
switch ($TorchBackend) {
'cu121' { $minimumDriver = [Version]'531.14' }
'cu124' { $minimumDriver = [Version]'551.61' }
'cu126' { $minimumDriver = [Version]'560.76' }
'cu128' { $minimumDriver = [Version]'570.65'; $minimumCapability = 7.5 }
'cu130' { $minimumDriver = [Version]'580.65'; $minimumCapability = 7.5 }
}
if ($gpuInfo.Count -gt 0) {
$primaryGpu = $gpuInfo[0]
if ($primaryGpu.ComputeCapability -ge 10.0 -and $TorchBackend -ne 'cu130') {
throw "-TorchBackend $TorchBackend cannot run reliably on $($primaryGpu.Name) (compute capability $($primaryGpu.ComputeCapability)). RTX 50xx/Blackwell on Windows requires cu130."
}
if ($primaryGpu.ComputeCapability -lt $minimumCapability) {
throw "-TorchBackend $TorchBackend is unsupported by $($primaryGpu.Name) (compute capability $($primaryGpu.ComputeCapability)). Use $($recommended.Backend), or update the NVIDIA driver and use cu126 for Pascal/Volta."
}
if ($primaryGpu.DriverVersion -lt $minimumDriver) {
throw "-TorchBackend $TorchBackend requires NVIDIA driver $minimumDriver or newer; detected $($primaryGpu.DriverVersion)."
}
}
return [PSCustomObject]@{
Backend = $TorchBackend
Recommended = $recommended
GpuInfo = $gpuInfo
IsManual = $true
}
}
function Show-GpuStatus {
$plan = Get-TorchBackendPlan
if ($plan.GpuInfo.Count -eq 0) {
Write-Host 'NVIDIA GPU: not detected through nvidia-smi' -ForegroundColor Yellow
Write-Host 'Recommended PyTorch backend: cpu' -ForegroundColor Yellow
return $plan
}
foreach ($gpu in $plan.GpuInfo) {
$memoryGiB = $gpu.MemoryMiB / 1024
Write-Host "NVIDIA GPU: $($gpu.Name) | compute capability $($gpu.ComputeCapability) | $($memoryGiB.ToString('N1')) GB VRAM" -ForegroundColor Green
Write-Host "NVIDIA driver: $($gpu.DriverVersion)" -ForegroundColor Gray
}
Write-Host "Recommended PyTorch backend: $($plan.Recommended.Backend)" -ForegroundColor Cyan
if ($plan.Recommended.Backend -eq 'cu126' -and $plan.GpuInfo[0].ComputeCapability -lt 7.5) {
Write-Host 'cu126 is the newest supported PyTorch CUDA build for this Pascal/Volta-class GPU.' -ForegroundColor Gray
}
if ($plan.Recommended.DriverUpgradeRecommended -and -not $plan.Recommended.RequiresDriverUpgrade) {
Write-Warning "Current driver supports $($plan.Recommended.Backend). Update the NVIDIA driver to $($plan.Recommended.PreferredDriver) or newer for $($plan.Recommended.PreferredBackend). Driver download: https://www.nvidia.com/Download/index.aspx"
}
if ($plan.Recommended.RequiresDriverUpgrade) {
Write-Warning "Update the NVIDIA driver to $($plan.Recommended.MinimumDriver) or newer, then run -Update. Driver download: https://www.nvidia.com/Download/index.aspx"
}
return $plan
}
function Ensure-Environment {
param([Switch]$Upgrade)
$installedVersion = Get-MuScriptorVersion
$environmentReady = (Test-EnvironmentInstalled) -and (-not [string]::IsNullOrWhiteSpace($installedVersion))
if ($environmentReady -and -not $Upgrade) {
Register-InstallationDirectory
Add-InstallationDirectoryToUserPath
Write-Host "Environment detected (MuScriptor $installedVersion)." -ForegroundColor Green
return
}
$uvExecutable = Get-UvExecutable
if (-not (Test-Path -LiteralPath $PythonExe -PathType Leaf)) {
Write-Step 'Creating Python environment'
$venvArguments = @('venv', '--python', '3.12')
if (Test-Path -LiteralPath $EnvPath) {
$venvArguments += '--clear'
}
$venvArguments += $EnvPath
Invoke-ExternalCommand -FilePath $uvExecutable -ArgumentList $venvArguments `
-FailureMessage 'Unable to create the Python 3.12 environment'
}
Write-Step 'Installing MuScriptor'
$torchPlan = Get-TorchBackendPlan
$effectiveBackend = $torchPlan.Backend
Write-Host "Selected PyTorch backend: $effectiveBackend" -ForegroundColor Cyan
if ($torchPlan.Recommended.RequiresDriverUpgrade) {
Write-Warning "NVIDIA driver update required for CUDA. Installing the CPU build. Download: https://www.nvidia.com/Download/index.aspx"
}
$installArguments = @(
'pip', 'install',
'--python', $PythonExe,
'--torch-backend', $effectiveBackend
)
if ($Upgrade) {
$installArguments += '--upgrade'
}
$installArguments += 'muscriptor>=0.2.1'
Invoke-ExternalCommand -FilePath $uvExecutable -ArgumentList $installArguments `
-FailureMessage 'Unable to install MuScriptor'
if (-not (Test-EnvironmentInstalled)) {
throw 'Installation finished without creating the expected muscriptor.exe.'
}
$checkCode = 'import huggingface_hub, muscriptor, torch; print("torch=" + torch.__version__)'
Invoke-ExternalCommand -FilePath $PythonExe -ArgumentList @('-c', $checkCode) `
-FailureMessage 'The installed Python environment failed its import check'
$version = Get-MuScriptorVersion
Register-InstallationDirectory
Add-InstallationDirectoryToUserPath
Write-Host "MuScriptor $version is ready." -ForegroundColor Green
}
function Get-ModelState {
param(
[Parameter(Mandatory = $true)]
[ValidateSet('small', 'medium', 'large')]
[string]$Name
)
$repository = "MuScriptor/muscriptor-$Name"
$repositoryCache = Join-Path $CachePath "hub\models--MuScriptor--muscriptor-$Name"
$weightsPath = $null
$mainReference = Join-Path $repositoryCache 'refs\main'
if (Test-Path -LiteralPath $mainReference -PathType Leaf) {
try {
$revision = (Get-Content -LiteralPath $mainReference -Raw).Trim()
if ($revision -match '^[0-9a-fA-F]+$') {
$referencedWeights = Join-Path $repositoryCache "snapshots\$revision\model.safetensors"
if (Test-Path -LiteralPath $referencedWeights -PathType Leaf) {
$weightsPath = $referencedWeights
}
}
} catch {
$weightsPath = $null
}
}
if (-not $weightsPath) {
$snapshotPath = Join-Path $repositoryCache 'snapshots'
if (Test-Path -LiteralPath $snapshotPath -PathType Container) {
$candidate = Get-ChildItem -LiteralPath $snapshotPath -Filter 'model.safetensors' `
-File -Recurse -ErrorAction SilentlyContinue |
Where-Object { $_.Name -notlike '*.incomplete' -and $_.Length -gt 1024 } |
Sort-Object LastWriteTimeUtc -Descending |
Select-Object -First 1
if ($candidate) {
$weightsPath = $candidate.FullName
}
}
}
$cached = $false
$sizeBytes = [int64]0
$configPath = $null
if ($weightsPath -and (Test-Path -LiteralPath $weightsPath -PathType Leaf)) {
$weightItem = Get-Item -LiteralPath $weightsPath
if ($weightItem.Length -gt 1024) {
$cached = $true
$sizeBytes = $weightItem.Length
$possibleConfig = Join-Path $weightItem.DirectoryName 'config.json'
if (Test-Path -LiteralPath $possibleConfig -PathType Leaf) {
$configPath = $possibleConfig
}
}
}
return [PSCustomObject]@{
Name = $Name
Repository = $repository
Cached = $cached
Weights = $weightsPath
Config = $configPath
SizeBytes = $sizeBytes
}
}
function Show-ModelStatus {
$rows = foreach ($name in $ModelNames) {
$state = Get-ModelState -Name $name
$size = '-'
if ($state.Cached) {
$size = '{0:N2} GB' -f ($state.SizeBytes / 1GB)
}
[PSCustomObject]@{
Model = $state.Name
Status = $(if ($state.Cached) { 'downloaded' } else { 'not downloaded' })
Size = $size
}
}
$rows | Format-Table -AutoSize | Out-Host
}
function Convert-SecureStringToText {
param([Parameter(Mandatory = $true)][System.Security.SecureString]$SecureValue)
$pointer = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureValue)
try {
return [Runtime.InteropServices.Marshal]::PtrToStringBSTR($pointer)
} finally {
[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($pointer)
}
}
function Resolve-HuggingFaceToken {
$resolvedToken = $Token
if ([string]::IsNullOrWhiteSpace($resolvedToken)) {
$resolvedToken = $env:HF_TOKEN
}
if ([string]::IsNullOrWhiteSpace($resolvedToken)) {
$resolvedToken = [Environment]::GetEnvironmentVariable('HF_TOKEN', 'User')
}
if ([string]::IsNullOrWhiteSpace($resolvedToken) -and (Test-Path -LiteralPath $PythonExe -PathType Leaf)) {
try {
$hubToken = & $PythonExe -c 'from huggingface_hub import get_token; print(get_token() or "")' 2>$null
if ($LASTEXITCODE -eq 0) {
$resolvedToken = ($hubToken | Select-Object -Last 1).Trim()
}
} catch {
$resolvedToken = $null
}
}
if ([string]::IsNullOrWhiteSpace($resolvedToken)) {
if ($NonInteractive) {
throw 'HF_TOKEN is required to download a gated model, but -NonInteractive prevents prompting.'
}
Write-Host "`nThe model is gated on Hugging Face." -ForegroundColor Yellow
Write-Host 'Accept its license in the browser, then enter a read token.' -ForegroundColor Yellow
Write-Host 'Token page: https://huggingface.co/settings/tokens' -ForegroundColor Cyan
$secureToken = Read-Host 'HF_TOKEN' -AsSecureString
$resolvedToken = Convert-SecureStringToText -SecureValue $secureToken
}
if ([string]::IsNullOrWhiteSpace($resolvedToken)) {
throw 'A non-empty Hugging Face token is required to download MuScriptor models.'
}
$resolvedToken = $resolvedToken.Trim()
$env:HF_TOKEN = $resolvedToken
if ($SaveToken) {
[Environment]::SetEnvironmentVariable('HF_TOKEN', $resolvedToken, 'User')
Write-Host 'HF_TOKEN was saved for the current Windows user.' -ForegroundColor Green
}
return $resolvedToken
}
function Test-HuggingFaceModelAccess {
param([Parameter(Mandatory = $true)][string]$Repository)
$env:MUSCRIPTOR_ACCESS_REPOSITORY = $Repository
$accessCheckCode = @'
import os
from huggingface_hub import hf_hub_download
from huggingface_hub.errors import GatedRepoError, RepositoryNotFoundError
try:
hf_hub_download(
repo_id=os.environ["MUSCRIPTOR_ACCESS_REPOSITORY"],
filename="config.json",
token=os.environ.get("HF_TOKEN"),
)
print("ACCESS_GRANTED")
except (GatedRepoError, RepositoryNotFoundError):
print("ACCESS_DENIED")
except Exception:
print("ACCESS_CHECK_FAILED")
'@
try {
$output = & $PythonExe -c $accessCheckCode 2>$null
$status = ([string]($output | Select-Object -Last 1)).Trim()
if ($status -eq 'ACCESS_GRANTED') {
return $true
}
if ($status -eq 'ACCESS_DENIED') {
return $false
}
throw 'The Hugging Face access check could not be completed. Check your internet connection and token.'
} finally {
Remove-Item Env:MUSCRIPTOR_ACCESS_REPOSITORY -ErrorAction SilentlyContinue
}
}
function Confirm-HuggingFaceModelAccess {
param([Parameter(Mandatory = $true)][string]$Name)
$repository = "MuScriptor/muscriptor-$Name"
while (-not (Test-HuggingFaceModelAccess -Repository $repository)) {
Write-Warning "Your Hugging Face account does not have access to model '$Name' yet."
Write-Host "Open this page, accept the terms or request access: https://huggingface.co/$repository" -ForegroundColor Cyan
if ($NonInteractive) {
throw "Model '$Name' requires Hugging Face access. Grant access at https://huggingface.co/$repository, then run the command again."
}
$response = Read-Host 'After access is granted, press Enter to retry; type Q to cancel'
if ($response -match '^[Qq]$') {
throw "Download cancelled. Grant access at https://huggingface.co/$repository, then run the command again."
}
}
}
function Invoke-ModelDownload {
param(
[Parameter(Mandatory = $true)]
[ValidateSet('small', 'medium', 'large')]
[string]$Name,
[Switch]$Force
)
$repository = "MuScriptor/muscriptor-$Name"
Write-Step "Downloading model '$Name'"
Write-Host "License page: https://huggingface.co/$repository" -ForegroundColor Cyan
$previousOfflineValue = $env:HF_HUB_OFFLINE
$env:HF_HUB_OFFLINE = '0'
$env:MUSCRIPTOR_DOWNLOAD_REPO = $repository
$env:MUSCRIPTOR_FORCE_DOWNLOAD = $(if ($Force) { '1' } else { '0' })
$downloadCode = @'
import os
import sys
from huggingface_hub import hf_hub_download
from huggingface_hub.errors import GatedRepoError
repo = os.environ["MUSCRIPTOR_DOWNLOAD_REPO"]
force = os.environ.get("MUSCRIPTOR_FORCE_DOWNLOAD") == "1"
try:
print("Downloading config.json...", flush=True)
for filename in ("config.json", "model.safetensors"):
if filename == "model.safetensors":
print("Downloading model weights. This can take several minutes...", flush=True)
path = hf_hub_download(repo_id=repo, filename=filename, force_download=force)
print(f"cached: {path}")
except GatedRepoError:
print("ACCESS_DENIED")
sys.exit(3)
except Exception:
print("DOWNLOAD_FAILED")
sys.exit(1)
'@
try {
& $PythonExe -c $downloadCode | Out-Host
if ($LASTEXITCODE -ne 0) {
throw "Unable to download '$Name'. Check your internet connection and run the command again."
}
} catch {
throw $_.Exception.Message
} finally {
Remove-Item Env:MUSCRIPTOR_DOWNLOAD_REPO -ErrorAction SilentlyContinue
Remove-Item Env:MUSCRIPTOR_FORCE_DOWNLOAD -ErrorAction SilentlyContinue
if ($null -eq $previousOfflineValue) {
Remove-Item Env:HF_HUB_OFFLINE -ErrorAction SilentlyContinue
} else {
$env:HF_HUB_OFFLINE = $previousOfflineValue
}
}
$state = Get-ModelState -Name $Name
if (-not $state.Cached) {
throw "The download command completed, but '$Name' was not found in the expected cache."
}
Write-Host "Model '$Name' is ready ($('{0:N2}' -f ($state.SizeBytes / 1GB)) GB)." -ForegroundColor Green
}
function Ensure-Models {
param(