forked from microsoft/BitNet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild_complete.ps1
More file actions
2132 lines (1823 loc) · 84.6 KB
/
build_complete.ps1
File metadata and controls
2132 lines (1823 loc) · 84.6 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
# BitNet Complete Build Script for Windows
# This script is completely self-contained and will set up everything needed
# It works on any Windows machine with the required tools installed
# EXPECTED TOOL LOCATIONS AND INSTALLATION INSTRUCTIONS:
#
# 1. VISUAL STUDIO 2022 COMMUNITY:
# - Download: https://visualstudio.microsoft.com/vs/community/
# - Install with these components:
# * Desktop development with C++
# * C++ CMake Tools for Windows (optional - standalone CMake preferred)
# * Git for Windows
# * C++ Clang Compiler for Windows (ClangCL)
# * MSVC v143 - VS 2022 C++ x64/x86 build tools
# - Expected path: C:\Program Files\Microsoft Visual Studio\2022\Community\
#
# 2. CMAKE (RECOMMENDED: Standalone, Fallback: VS bundled):
# - **PREFERRED:** Standalone CMake 3.31.9 (stable)
# * Download: https://cmake.org/download/ (Windows x64 Installer)
# * Install to: C:\Program Files\CMake\
# * Expected: C:\Program Files\CMake\bin\cmake.exe
# - **FALLBACK:** Visual Studio 2022 bundled CMake (if no stable system CMake found)
# * Path: C:\Program Files\Microsoft Visual Studio\2022\Community\...\cmake.exe
# - Script auto-detects and prefers stable CMake 3.27-3.99, rejects 4.x (buggy)
#
# 3. CLANG COMPILER (ClangCL):
# - Included with Visual Studio ("C++ Clang Compiler for Windows")
# - Used for: Standard CPU, BitNet CPU builds
# - Auto-detected in Visual Studio installation
#
# 4. MSVC COMPILER:
# - Included with Visual Studio (MSVC build tools)
# - Used for: GPU builds (CUDA, Vulkan, OpenCL)
# - Auto-detected in Visual Studio installation
#
# 5. VULKAN SDK ( for Vulkan GPU acceleration):
# - Download: https://vulkan.lunarg.com/sdk/home#windows
# - Install only "Vulkan SDK Core" components
# - Expected: C:\VulkanSDK\<version>\ (auto-detected)
# - GLSL Compiler: C:\VulkanSDK\<version>\Bin\glslc.exe
#
# 6. CUDA TOOLKIT (Required for NVIDIA GPU builds):
# - Download: https://developer.nvidia.com/cuda-downloads
# - Recommended: CUDA 12.8 or latest
# - Expected: C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.8\
# - CUDA Compiler: C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.8\bin\nvcc.exe
# - Note: CUDA 12.8 requires -allow-unsupported-compiler flag for VS 2026
#
# 7. GIT ( for version control):
# - Download: https://git-scm.com/
# - Add to PATH during installation
# - Expected: Accessible as "git" from command line
#
# 8. PYTHON REQUIREMENTS (Required for BitNet GPU Python CUDA build):
# - **CRITICAL:** Python 3.9, 3.10, or 3.11 ONLY (NOT 3.13+)
# - Reason: PyTorch 2.3.1 does not support Python 3.13+
# - Download Python 3.11: https://www.python.org/downloads/release/python-3119/
# - Script creates virtual environment: bitnet-gpu-env-windows
# - Auto-installs required packages:
# * PyTorch 2.3.1+cu121 (CUDA 12.1 compatible)
# * xformers 0.0.27 (requires PyTorch 2.3.1 exactly)
# * transformers, safetensors, etc.
# - Script will EXIT with error if Python 3.13+ detected
param(
[string]$BuildDir = "BitnetRelease",
[switch]$CleanBuild = $false,
[string[]]$BuildVariants = @(), # Build only specific variants (e.g., "zen2", "portable", "zen3")
[switch]$ListVariants = $false # List available build variants and exit
)
# Colors for output
$Green = "$([char]27)[92m"
$Yellow = "$([char]27)[93m"
$Red = "$([char]27)[91m"
$Cyan = "$([char]27)[96m"
$Reset = "$([char]27)[0m"
# Handle -ListVariants flag
if ($ListVariants) {
Write-Host "`n=== AVAILABLE BUILD VARIANTS ===" -ForegroundColor Cyan
Write-Host "`nTo build specific variants, use: -BuildVariants <variant1>,<variant2>`n" -ForegroundColor Yellow
Write-Host "STANDARD BUILDS:" -ForegroundColor Yellow
Write-Host " standard - Standard llama.cpp (no BitNet, any CPU)" -ForegroundColor White
Write-Host " gpu-cuda-vulkan - CUDA + Vulkan GPU build (NVIDIA)" -ForegroundColor White
Write-Host " gpu-opencl - OpenCL GPU build (Universal)" -ForegroundColor White
Write-Host " python-cuda - BitNet Python CUDA kernels" -ForegroundColor White
Write-Host "`nBITNET CPU VARIANTS (COMPLETE MATRIX):" -ForegroundColor Yellow
Write-Host " portable - AVX2 baseline (any modern CPU)" -ForegroundColor White
Write-Host "`n AMD Ryzen:" -ForegroundColor Yellow
Write-Host " amd-zen1 - AMD Ryzen 1000/2000 series (Zen 1)" -ForegroundColor White
Write-Host " amd-zen2 - AMD Ryzen 3000 series (Zen 2)" -ForegroundColor White
Write-Host " amd-zen3 - AMD Ryzen 5000 series (Zen 3)" -ForegroundColor White
Write-Host " amd-zen4 - AMD Ryzen 7000 series (Zen 4)" -ForegroundColor White
Write-Host " amd-zen5 - AMD Ryzen 9000 series (Zen 5)" -ForegroundColor White
Write-Host "`n Intel Core:" -ForegroundColor Yellow
Write-Host " intel-haswell - Intel 4th gen (Haswell)" -ForegroundColor White
Write-Host " intel-broadwell - Intel 5th gen (Broadwell)" -ForegroundColor White
Write-Host " intel-skylake - Intel 6th-9th gen (Skylake)" -ForegroundColor White
Write-Host " intel-icelake - Intel 10th gen (Ice Lake)" -ForegroundColor White
Write-Host " intel-rocketlake - Intel 11th gen (Rocket Lake)" -ForegroundColor White
Write-Host " intel-alderlake - Intel 12th-14th gen (Alder Lake)" -ForegroundColor White
Write-Host "`nEXAMPLES:" -ForegroundColor Cyan
Write-Host " # Build only zen2 variant:" -ForegroundColor Gray
Write-Host " .\build_complete.ps1 -BuildVariants amd-zen2`n" -ForegroundColor Gray
Write-Host " # Build zen2 + portable:" -ForegroundColor Gray
Write-Host " .\build_complete.ps1 -BuildVariants amd-zen2,portable`n" -ForegroundColor Gray
Write-Host " # Build all GPU variants:" -ForegroundColor Gray
Write-Host " .\build_complete.ps1 -BuildVariants gpu-cuda-vulkan,gpu-opencl,python-cuda`n" -ForegroundColor Gray
Write-Host " # Build everything (default):" -ForegroundColor Gray
Write-Host " .\build_complete.ps1`n" -ForegroundColor Gray
exit 0
}
function Write-Status {
param([string]$Message, [string]$Color = $Green)
Write-Host "${Color}${Message}${Reset}"
}
function Write-ErrorAndExit {
param([string]$Message)
Write-Host "${Red}ERROR: ${Message}${Reset}"
exit 1
}
function Should-BuildVariant {
param([string]$VariantName)
# If no variants specified, build everything
if ($BuildVariants.Count -eq 0) {
return $true
}
# Otherwise, check if this variant is in the list
return $BuildVariants -contains $VariantName
}
function Should-SkipBuild {
param(
[string]$BuildDir,
[string]$ReleaseDir,
[int]$MinFiles = 5
)
# If CleanBuild flag is set, never skip
if ($CleanBuild) {
return $false
}
# Check if build directory exists
if (!(Test-Path $BuildDir)) {
Write-Status " [BUILD] Build directory missing: $BuildDir" $Yellow
return $false
}
# Check if Release output directory exists
if (!(Test-Path $ReleaseDir)) {
Write-Status " [BUILD] Release output missing: $ReleaseDir" $Yellow
return $false
}
# Check if Release directory has files
$fileCount = (Get-ChildItem $ReleaseDir -File -ErrorAction SilentlyContinue).Count
if ($fileCount -lt $MinFiles) {
Write-Status " [BUILD] Release incomplete: only $fileCount files (need $MinFiles+)" $Yellow
return $false
}
# All checks passed - skip this build!
Write-Status " [SKIP] Already built: $fileCount files in $ReleaseDir" $Green
return $true
}
function Test-CommandExists {
param([string]$Command)
try {
# Try multiple ways to check if command exists
$result = Get-Command $Command -ErrorAction SilentlyContinue
if ($result) {
return $true
}
# Try using where command as fallback
$whereResult = where.exe $Command 2>$null
if ($whereResult -and $whereResult.Length -gt 0) {
return $true
}
return $false
} catch {
return $false
}
}
function Invoke-FullBitNetSetup {
param([string]$PythonCmd)
Write-Status " Running full BitNet setup process..."
# Install GGUF package
Write-Status " Installing GGUF package..."
& $PythonCmd -m pip install 3rdparty/llama.cpp/gguf-py
if ($LASTEXITCODE -ne 0) {
Write-Status " Warning: Failed to install GGUF package, continuing..." $Yellow
}
# Generate kernel code (this is what gen_code() does in setup_env.py)
Write-Status " Generating kernel code..."
try {
# For x86_64 architecture, we use codegen_tl2.py
if (Test-Path "utils\codegen_tl2.py") {
& $PythonCmd utils\codegen_tl2.py --model Llama3-8B-1.58-100B-tokens --BM 256,128,256,128 --BK 96,96,96,96 --bm 32,32,32
if ($LASTEXITCODE -eq 0) {
Write-Status " Kernel code generated successfully"
} else {
Write-Status " Warning: Kernel code generation failed, using preset kernels..." $Yellow
# Copy preset kernels as fallback
Copy-PresetKernels
}
} else {
Write-Status " Warning: codegen_tl2.py not found, using preset kernels..." $Yellow
Copy-PresetKernels
}
} catch {
Write-Status " Warning: Kernel code generation failed, using preset kernels..." $Yellow
Copy-PresetKernels
}
}
function Copy-PresetKernels {
Write-Status " Copying preset kernels as fallback..."
try {
# Try to copy the most appropriate preset kernel
$presetPath = "preset_kernels\Llama3-8B-1.58-100B-tokens"
if (Test-Path $presetPath) {
# Copy the TL2 kernel file (since we're building for x86 TL2)
$tl2Kernel = "$presetPath\bitnet-lut-kernels-tl2.h"
if (Test-Path $tl2Kernel) {
Copy-Item $tl2Kernel "include\bitnet-lut-kernels.h" -Force
Write-Status " Copied TL2 preset kernel"
} else {
# Fallback to TL1 if TL2 not available
$tl1Kernel = "$presetPath\bitnet-lut-kernels-tl1.h"
if (Test-Path $tl1Kernel) {
Copy-Item $tl1Kernel "include\bitnet-lut-kernels.h" -Force
Write-Status " Copied TL1 preset kernel"
}
}
}
# If still no kernel file, create a minimal one
if (!(Test-Path "include\bitnet-lut-kernels.h") -or (Get-Content "include\bitnet-lut-kernels.h" | Measure-Object).Count -eq 0) {
Write-Status " Creating minimal kernel header..." $Yellow
$minimalKernel = @"
#if defined(GGML_BITNET_X86_TL2) || defined(GGML_BITNET_ARM_TL1)
#define GGML_BITNET_MAX_NODES 8192
static bool initialized = false;
static bitnet_tensor_extra * bitnet_tensor_extras = nullptr;
static size_t bitnet_tensor_extras_index = 0;
static bool is_type_supported(enum ggml_type type) {
return (type == GGML_TYPE_TL2 || type == GGML_TYPE_TL1 || type == GGML_TYPE_Q4_0);
}
#endif
"@
$minimalKernel | Out-File -FilePath "include\bitnet-lut-kernels.h" -Encoding UTF8
}
} catch {
Write-Status " Warning: Failed to copy preset kernels..." $Yellow
}
}
Write-Status "=== BitNet Complete Build Script ==="
Write-Status ""
# 1. VERIFY ALL REQUIRED TOOLS FIRST (fail fast before spending time on Python setup)
Write-Status "1. Verifying ALL required tools before proceeding..."
Write-Status ""
$allToolsFound = $true
$criticalToolsMissing = @()
# Check CMake and Visual Studio - Prefer stable system CMake, fallback to VS bundled
Write-Status " Checking CMake and Visual Studio..."
# Step 1: Check for stable system CMake (preferred)
$cmakePath = $null
$cmakeVersion = $null
$systemCmake = "C:\Program Files\CMake\bin"
if (Test-Path "$systemCmake\cmake.exe") {
$versionOutput = & "$systemCmake\cmake.exe" --version 2>&1 | Select-Object -First 1
if ($versionOutput -match "cmake version (\d+)\.(\d+)\.(\d+)") {
$major = [int]$matches[1]
$minor = [int]$matches[2]
$cmakeVersion = "$major.$minor.$($matches[3])"
# Accept CMake 3.27+ but reject 4.0+ (experimental)
if ($major -eq 3 -and $minor -ge 27) {
$cmakePath = $systemCmake
Write-Status " [OK] Using stable system CMake $cmakeVersion" $Green
Write-Status " [PATH] $systemCmake\cmake.exe" $Cyan
} elseif ($major -ge 4) {
Write-Status " [WARN] System CMake $cmakeVersion is experimental (4.x)" $Yellow
Write-Status " [INFO] Will try Visual Studio's bundled CMake instead..." $Yellow
} elseif ($major -eq 3 -and $minor -lt 27) {
Write-Status " [WARN] System CMake $cmakeVersion is too old (need 3.27+)" $Yellow
Write-Status " [INFO] Will try Visual Studio's bundled CMake instead..." $Yellow
}
}
}
# Step 2: Detect Visual Studio 2022 installation (for compilers and fallback CMake)
$vsInstallPath = "C:\Program Files\Microsoft Visual Studio\2022\Community"
if (Test-Path $vsInstallPath) {
# If no stable system CMake, use VS's bundled CMake as fallback
if (-not $cmakePath) {
$testPath = "$vsInstallPath\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin"
if (Test-Path "$testPath\cmake.exe") {
$vsCmakeVersion = & "$testPath\cmake.exe" --version 2>&1 | Select-Object -First 1
if ($vsCmakeVersion -match "cmake version ([\d\.]+)") {
$cmakePath = $testPath
$cmakeVersion = "Visual Studio 2022 bundled $($matches[1])"
Write-Status " [OK] Using Visual Studio 2022's bundled CMake $($matches[1])" $Yellow
Write-Status " [PATH] $testPath\cmake.exe" $Cyan
}
}
}
} else {
Write-Status " [FAIL] Visual Studio 2022 Community not found at: $vsInstallPath" $Red
$criticalToolsMissing += "Visual Studio 2022"
$allToolsFound = $false
}
# Step 3: Add CMake to PATH and verify
if ($cmakePath) {
$env:PATH = "$cmakePath;$env:PATH"
Write-Status " [OK] CMake ready: $cmakeVersion" $Green
} else {
Write-Status " [FAIL] No suitable CMake found!" $Red
Write-Status " [TIP] Install CMake 3.27+ from https://cmake.org/download/" $Yellow
$criticalToolsMissing += "CMake"
$allToolsFound = $false
}
# Check Clang (ClangCL from Visual Studio 2022)
Write-Status " Checking Clang..."
$clangPath = "$vsInstallPath\VC\Tools\Llvm\x64\bin"
if (Test-Path "$clangPath\clang.exe") {
$clangVersion = & "$clangPath\clang.exe" --version 2>$null | Select-Object -First 1
Write-Status " [OK] Clang found: $clangVersion" $Green
} else {
Write-Status " [FAIL] Clang not found in VS 2022 at: $clangPath" $Red
$criticalToolsMissing += "Clang (ClangCL)"
$allToolsFound = $false
}
# Check CUDA (look for all versions)
Write-Status " Checking CUDA..."
$cudaBasePath = "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA"
if (Test-Path $cudaBasePath) {
$cudaVersions = Get-ChildItem $cudaBasePath -Directory | Where-Object { $_.Name -match "^v\d" } | Sort-Object Name -Descending
if ($cudaVersions) {
$cudaDir = $cudaVersions[0].FullName
$env:PATH = "$cudaDir\bin;$env:PATH"
$env:CUDA_PATH = $cudaDir
$env:CUDA_HOME = $cudaDir
Write-Status " [OK] CUDA found: $($cudaVersions[0].Name)" $Green
} else {
Write-Status " [WARN] CUDA directory exists but no versions found" $Yellow
}
} else {
Write-Status " [WARN] CUDA not found - GPU builds will not work" $Yellow
}
# Check Vulkan SDK
Write-Status " Checking Vulkan SDK..."
$vulkanBasePath = "C:\VulkanSDK\1.4.328.1"
$vulkanPath = "$vulkanBasePath\Bin"
if (Test-Path $vulkanPath) {
$env:PATH = "$vulkanPath;$env:PATH"
$env:VULKAN_SDK = $vulkanBasePath
# Check if VULKAN_SDK is set permanently at system or user level
$systemVulkan = [System.Environment]::GetEnvironmentVariable('VULKAN_SDK', 'Machine')
$userVulkan = [System.Environment]::GetEnvironmentVariable('VULKAN_SDK', 'User')
if ($systemVulkan -eq $vulkanBasePath -or $userVulkan -eq $vulkanBasePath) {
Write-Status " [OK] Vulkan SDK found and permanently configured" $Green
$env:VULKAN_CONFIGURED = "true"
} else {
Write-Status " [OK] Vulkan SDK found (setting for user level)" $Yellow
# Set at user level (doesn't require admin)
[System.Environment]::SetEnvironmentVariable('VULKAN_SDK', $vulkanBasePath, 'User')
Write-Status " [OK] VULKAN_SDK set at user level - restart PowerShell for system-wide effect" $Green
$env:VULKAN_CONFIGURED = "true"
}
} else {
Write-Status " [WARN] Vulkan SDK not found - Vulkan builds will not work" $Yellow
$env:VULKAN_CONFIGURED = "false"
}
# Check OpenCL (optional - for universal GPU builds)
Write-Status " Checking OpenCL..."
$openclAvailable = $false
$openclIncludePath = $null
# OpenCL headers can come from multiple sources
# 1. NVIDIA CUDA Toolkit (includes OpenCL)
# 2. Intel SDK
# 3. AMD APP SDK
# Check CUDA toolkit for OpenCL headers (most common on Windows)
if ($env:CUDA_HOME) {
$cudaOpenCLPath = "$env:CUDA_HOME\include\CL\cl.h"
if (Test-Path $cudaOpenCLPath) {
$openclIncludePath = "$env:CUDA_HOME\include"
$openclAvailable = $true
Write-Status " [OK] OpenCL headers found in CUDA toolkit" $Green
}
}
# Check alternative OpenCL locations (Windows SDK, Intel drivers, AMD drivers)
# Note: CUDA installation above is the most common source of OpenCL headers
# Check Windows SDK (sometimes has OpenCL)
if (-not $openclAvailable) {
$windowsSDKPath = "C:\Program Files (x86)\Windows Kits\10\Include"
if (Test-Path $windowsSDKPath) {
$sdkVersions = Get-ChildItem $windowsSDKPath -Directory | Where-Object { $_.Name -match '^\d' } | Sort-Object Name -Descending
foreach ($sdkVer in $sdkVersions) {
$sdkOpenCLPath = "$($sdkVer.FullName)\um\CL\cl.h"
if (Test-Path $sdkOpenCLPath) {
$openclIncludePath = "$($sdkVer.FullName)\um"
$openclAvailable = $true
Write-Status " [OK] OpenCL headers found in Windows SDK $($sdkVer.Name)" $Green
break
}
}
}
}
if ($openclAvailable) {
$env:OPENCL_INCLUDE_PATH = $openclIncludePath
$env:OPENCL_AVAILABLE = "true"
Write-Status " [OK] OpenCL builds will be enabled" $Green
} else {
Write-Status " [SKIP] OpenCL headers not found - OpenCL builds will be skipped" $Yellow
Write-Status " [TIP] OpenCL headers come with NVIDIA CUDA, Intel SDK, or AMD drivers" $Cyan
$env:OPENCL_AVAILABLE = "false"
}
# Check Git
Write-Status " Checking Git..."
if (Test-CommandExists "git") {
$gitVersion = & git --version 2>$null
Write-Status " [OK] Git found: $gitVersion" $Green
} else {
Write-Status " [FAIL] Git not found in PATH" $Red
$criticalToolsMissing += "Git"
$allToolsFound = $false
}
# Check Python
Write-Status " Checking Python..."
if (Test-CommandExists "py") {
$pythonVersion = & py --version 2>$null
Write-Status " [OK] Python found: $pythonVersion" $Green
} elseif (Test-CommandExists "python") {
$pythonVersion = & python --version 2>$null
Write-Status " [OK] Python found: $pythonVersion" $Green
} else {
Write-Status " [FAIL] Python not found in PATH" $Red
$criticalToolsMissing += "Python"
$allToolsFound = $false
}
Write-Status ""
# FAIL FAST if critical tools are missing
if (-not $allToolsFound) {
Write-Status "========================================" $Red
Write-Status "CRITICAL TOOLS MISSING!" $Red
Write-Status "========================================" $Red
Write-Status ""
Write-Status "The following required tools were not found:" $Red
foreach ($tool in $criticalToolsMissing) {
Write-Status " - $tool" $Red
}
Write-Status ""
Write-Status "Please install missing tools before running this script." $Red
Write-Status "See comments at top of script for installation instructions." $Red
Write-Status ""
exit 1
}
Write-Status "========================================" $Green
Write-Status "ALL REQUIRED TOOLS VERIFIED!" $Green
Write-Status "========================================" $Green
Write-Status ""
# 2. Initialize git submodules
Write-Status "2. Initializing git submodules..."
# This step ensures all required submodules are properly initialized:
# - 3rdparty/llama.cpp (main llama.cpp framework)
# - 3rdparty/llama.cpp/ggml (core compute library)
# - 3rdparty/llama.cpp/ggml/src/kompute (Kompute backend for GPU acceleration)
try {
& git submodule update --init --recursive
if ($LASTEXITCODE -ne 0) {
throw "Git submodule initialization failed"
}
Write-Status " Git submodules initialized successfully"
} catch {
Write-ErrorAndExit "Failed to initialize git submodules: $_"
}
# 3. Verify 3rdparty directory structure
Write-Status "3. Verifying 3rdparty directory structure..."
# Verify that git submodules were properly initialized and key directories exist:
# - 3rdparty/llama.cpp (main framework)
# - 3rdparty/llama.cpp/ggml (compute library)
# - 3rdparty/llama.cpp/ggml/src (source files)
# - 3rdparty/llama.cpp/ggml/include (header files)
if (!(Test-Path "3rdparty\llama.cpp")) {
Write-ErrorAndExit "llama.cpp submodule not found in 3rdparty directory. Please check git submodule initialization."
}
if (!(Test-Path "3rdparty\llama.cpp\ggml")) {
Write-ErrorAndExit "ggml submodule not found in llama.cpp directory. Please check git submodule initialization."
}
Write-Status " 3rdparty directory structure verified"
# 4. Verify required header files are available
Write-Status "4. Verifying required header files..."
# Check for critical header files that are required for successful compilation:
# - llama.h: Main llama.cpp header
# - ggml.h: Core GGML compute library header
# - ggml-vulkan.h: Vulkan backend header
# - ggml-cuda.h: CUDA backend header
$headerFiles = @(
"3rdparty\llama.cpp\include\llama.h",
"3rdparty\llama.cpp\ggml\include\ggml.h",
"3rdparty\llama.cpp\ggml\include\ggml-vulkan.h",
"3rdparty\llama.cpp\ggml\include\ggml-cuda.h"
)
$missingHeaders = @()
foreach ($header in $headerFiles) {
if (!(Test-Path $header)) {
$missingHeaders += $header
}
}
if ($missingHeaders.Count -gt 0) {
Write-Status " Missing header files detected:" $Yellow
foreach ($header in $missingHeaders) {
Write-Host " - $header"
}
Write-ErrorAndExit "Required header files are missing. Please check submodule initialization and ensure all submodules are properly checked out."
}
Write-Status " All required header files are available"
# 6. Set up Python environment (create if doesn't exist)
Write-Status "6. Setting up Python environment..."
# CRITICAL: Check Python version BEFORE creating venv
Write-Status " Checking Python version compatibility..."
$pythonVersionCheck = $null
$pythonVersions = @("3.11", "3.10", "3.9")
foreach ($ver in $pythonVersions) {
if (Test-CommandExists "py") {
$testResult = & py -$ver --version 2>$null
if ($LASTEXITCODE -eq 0) {
# Extract version number (e.g., "Python 3.11.9" -> "3.11.9")
if ($testResult -match "Python (\d+\.\d+\.\d+)") {
$detectedVersion = $matches[1]
$majorMinor = $detectedVersion.Split('.')[0..1] -join '.'
# Check if version is >= 3.13 (NOT supported)
if ([version]$detectedVersion -ge [version]"3.13.0") {
Write-Status " [FAIL] Python $detectedVersion detected - NOT SUPPORTED!" $Red
continue
}
$pythonVersionCheck = "py -$ver"
Write-Status " [OK] Python $detectedVersion detected - COMPATIBLE" $Green
break
}
}
}
}
if (-not $pythonVersionCheck) {
Write-Status "" $Red
Write-Status "========================================" $Red
Write-Status "PYTHON VERSION REQUIREMENT NOT MET!" $Red
Write-Status "========================================" $Red
Write-Status "" $Red
Write-Status "This project requires Python 3.9, 3.10, or 3.11 (Python < 3.13)" $Yellow
Write-Status "" $Red
Write-Status "WHY:" $Yellow
Write-Status " - PyTorch 2.3.1 does not support Python 3.13+" $Cyan
Write-Status " - xformers 0.0.27 requires PyTorch 2.3.1 exactly" $Cyan
Write-Status " - BitNet CUDA kernels depend on xformers" $Cyan
Write-Status "" $Red
Write-Status "SOLUTION:" $Yellow
Write-Status " 1. Install Python 3.11 (recommended):" $Cyan
Write-Status " https://www.python.org/downloads/release/python-3119/" $Cyan
Write-Status " 2. Or install Python 3.10 or 3.9" $Cyan
Write-Status "" $Red
Write-Status "Current Python versions found:" $Yellow
& py -0 2>$null
Write-Status "" $Red
exit 1
}
# Create or use existing Python virtual environment:
# - Environment name: bitnet-gpu-env-windows
# - Location: .\bitnet-gpu-env-windows\ (relative to script location)
# - Python executable: .\bitnet-gpu-env-windows\Scripts\python.exe
# This ensures isolated dependencies and prevents conflicts with system Python packages
$envPath = "bitnet-gpu-env-windows"
$pythonCmd = "$envPath\Scripts\python.exe"
if (!(Test-Path $envPath)) {
Write-Status " Creating Python virtual environment with $pythonVersionCheck..."
# Create virtual environment
Invoke-Expression "$pythonVersionCheck -m venv $envPath"
if ($LASTEXITCODE -ne 0) {
Write-ErrorAndExit "Failed to create virtual environment. Please ensure Python 3.9+ is installed."
}
# Verify the Python version in the venv
$venvPythonVersion = & $pythonCmd --version 2>$null
Write-Status " Virtual environment created with: $venvPythonVersion"
}
# Verify Python environment
if (!(Test-Path $pythonCmd)) {
Write-ErrorAndExit "Python environment not found at $pythonCmd. Please check virtual environment creation."
}
Write-Status " Python environment ready"
# 7. Install required Python packages with exact versions
Write-Status "7. Installing required Python packages..."
& $pythonCmd -m pip install --upgrade pip
if ($LASTEXITCODE -ne 0) {
Write-ErrorAndExit "Failed to upgrade pip"
}
# Core ML/CUDA packages
$packages = @(
"torch==2.3.1+cu121",
"torchvision==0.18.1+cu121",
"torchaudio==2.3.1+cu121"
)
Write-Status " Installing PyTorch stack (CUDA 12.1)..."
foreach ($package in $packages) {
& $pythonCmd -m pip install $package --extra-index-url https://download.pytorch.org/whl/cu121
if ($LASTEXITCODE -ne 0) {
Write-ErrorAndExit "Failed to install $package"
}
}
Write-Status " Installing xformers 0.0.27..."
& $pythonCmd -m pip install xformers==0.0.27 --extra-index-url https://download.pytorch.org/whl/cu121
if ($LASTEXITCODE -ne 0) {
Write-ErrorAndExit "Failed to install xformers"
}
# Other required packages
$otherPackages = @(
"transformers==4.57.1",
"sentencepiece==0.2.1",
"tiktoken==0.12.0",
"tokenizers==0.22.1",
"numpy==2.3.3",
"safetensors==0.6.2",
"einops==0.8.1",
"huggingface_hub==0.35.3",
"intel-openmp==2021.4.0",
"mkl==2021.4.0",
"tbb==2021.13.1",
"fire==0.7.1",
"flask==3.1.2",
"blobfile==3.1.0"
)
Write-Status " Installing other required packages..."
foreach ($package in $otherPackages) {
& $pythonCmd -m pip install $package
if ($LASTEXITCODE -ne 0) {
Write-Status " Warning: Failed to install $package, continuing..." $Yellow
}
}
# Install GGUF package directly (avoid requirements.txt conflicts)
Write-Status " Installing GGUF package from llama.cpp..."
& $pythonCmd -m pip install 3rdparty/llama.cpp/gguf-py
if ($LASTEXITCODE -ne 0) {
Write-Status " Warning: Failed to install GGUF package, continuing..." $Yellow
}
# Install GPU requirements individually (SKIP torch/xformers - already installed with CUDA!)
Write-Status " Installing GPU requirements (skipping torch/xformers to preserve CUDA version)..."
$gpuPackagesOnly = @(
"fire",
"sentencepiece",
"tiktoken",
"blobfile",
"flask",
"einops",
"transformers"
)
foreach ($package in $gpuPackagesOnly) {
& $pythonCmd -m pip install $package
if ($LASTEXITCODE -ne 0) {
Write-Status " Warning: Failed to install $package, continuing..." $Yellow
}
}
# Verify torch version is still CUDA
Write-Status " Verifying PyTorch CUDA version preserved..."
$torchVersion = & $pythonCmd -c "import torch; print(torch.__version__)" 2>$null
if ($torchVersion -like "*cu121*") {
Write-Status " [OK] PyTorch CUDA 12.1 preserved: $torchVersion" $Green
} else {
Write-Status " [WARN] PyTorch version is $torchVersion (expected cu121)" $Yellow
}
Write-Status " All Python packages installed successfully"
# 12. Generate required kernel files if they don't exist
Write-Status "12. Generating required kernel files..."
# Create include directory if it doesn't exist:
# - Location: .\include\
# - Required files: bitnet-lut-kernels.h, kernel_config.ini
# These files are critical for BitNet kernel compilation and must be generated properly
if (!(Test-Path "include")) {
New-Item -ItemType Directory -Path "include" | Out-Null
}
# Run the full BitNet setup process to generate proper kernel files:
# This replicates the gen_code() function from setup_env.py:
# 1. Installs GGUF package from 3rdparty/llama.cpp/gguf-py
# 2. Runs codegen_tl2.py to generate optimized kernels for x86_64 architecture
# 3. Creates bitnet-lut-kernels.h and kernel_config.ini with proper parameters
Write-Status " Running full BitNet setup process..."
Invoke-FullBitNetSetup -PythonCmd $pythonCmd
# Verify that kernel files were generated
$kernelFiles = @(
"include\bitnet-lut-kernels.h",
"include\kernel_config.ini"
)
$missingKernelFiles = @()
foreach ($file in $kernelFiles) {
if (!(Test-Path $file)) {
$missingKernelFiles += $file
}
}
if ($missingKernelFiles.Count -gt 0) {
Write-Status " Some kernel files are missing, using preset kernels..." $Yellow
# Use preset kernels as fallback (like Linux workflow does)
$presetKernelPath = "preset_kernels\bitnet_b1_58-3B\bitnet-lut-kernels-tl2.h"
if (Test-Path $presetKernelPath) {
Copy-Item $presetKernelPath "include\bitnet-lut-kernels.h" -Force
Write-Status " [OK] Copied preset TL2 kernel header"
} else {
Write-Status " Warning: Preset kernel not found, creating minimal fallback..." $Yellow
'#ifndef BITNET_LUT_KERNELS_H
#define BITNET_LUT_KERNELS_H
#include <cstring>
#include <immintrin.h>
// Minimal header for build process
#endif // BITNET_LUT_KERNELS_H' | Out-File -FilePath "include\bitnet-lut-kernels.h" -Encoding UTF8
}
if (!(Test-Path "include\kernel_config.ini")) {
Write-Status " Creating kernel_config.ini..." $Yellow
'[kernel]
BM=256,128,256
BK=96,96,96
bm=32,32,32' | Out-File -FilePath "include\kernel_config.ini" -Encoding UTF8
}
} else {
Write-Status " Required kernel files are available"
}
# Apply critical patches to kernel header (like Linux workflow lines 222-225)
Write-Status " Applying kernel header patches..."
if (Test-Path "include\bitnet-lut-kernels.h") {
$kernelContent = Get-Content "include\bitnet-lut-kernels.h" -Raw
# Check if it's a preset kernel (starts with #if defined) - DON'T PATCH IT!
if ($kernelContent -match "^#if defined\(GGML_BITNET") {
Write-Status " [OK] Kernel header is preset kernel - no patching needed"
}
# Check if it's a generated kernel that needs includes added
elseif ($kernelContent -notmatch "#include <cstring>") {
# Only patch if file is long enough (more than 10 lines) - avoid corrupting minimal headers
$lineCount = (Get-Content "include\bitnet-lut-kernels.h" | Measure-Object -Line).Lines
if ($lineCount -gt 10) {
# Insert includes at the top after header guards
$lines = Get-Content "include\bitnet-lut-kernels.h"
$newContent = @()
$headerGuardFound = $false
foreach ($line in $lines) {
$newContent += $line
# After the #define BITNET_LUT_KERNELS_H line, add includes
if ($line -match "^#define BITNET_LUT_KERNELS_H" -and -not $headerGuardFound) {
$newContent += "#include <cstring>"
$newContent += "#include <immintrin.h>"
$newContent += ""
$headerGuardFound = $true
}
}
$newContent | Out-File -FilePath "include\bitnet-lut-kernels.h" -Encoding UTF8
Write-Status " [OK] Added missing includes to generated kernel header"
} else {
Write-Status " [WARN] Kernel header too short to patch safely - skipping"
}
} else {
Write-Status " [OK] Kernel header already has required includes"
}
}
# 13. Build BitNet CUDA kernels (Python GPU DLL)
Write-Status "13. Building BitNet CUDA kernels (Python GPU DLL)..."
if (Test-Path "gpu\bitnet_kernels\bitnet_kernels.cu") {
try {
# Use the VS installation path detected at the beginning
if (-not $vsInstallPath) {
throw "Visual Studio not detected at initialization"
}
# Find latest MSVC version
$msvcBasePath = "$vsInstallPath\VC\Tools\MSVC"
$msvcVersions = Get-ChildItem $msvcBasePath -Directory -ErrorAction SilentlyContinue | Sort-Object Name -Descending
if (-not $msvcVersions) {
throw "MSVC compiler not found in $msvcBasePath"
}
$msvcPath = $msvcVersions[0].FullName
# Configure VS environment for CUDA compilation
$env:DISTUTILS_USE_SDK = "1"
$env:MSSdk = "1"
$env:VS160COMNTOOLS = "$vsInstallPath\Common7\Tools\"
$env:VSINSTALLDIR = "$vsInstallPath\"
$env:PATH = "$msvcPath\bin\Hostx64\x64;$env:PATH"
# Set INCLUDE paths (critical for NVCC to find Windows SDK headers)
$env:INCLUDE = @(
"$msvcPath\include",
"C:\Program Files (x86)\Windows Kits\10\Include\10.0.26100.0\ucrt",
"C:\Program Files (x86)\Windows Kits\10\Include\10.0.26100.0\shared",
"C:\Program Files (x86)\Windows Kits\10\Include\10.0.26100.0\um"
) -join ";"
# Set LIB paths (critical for NVCC to find Windows SDK libraries)
$env:LIB = @(
"$msvcPath\lib\x64",
"C:\Program Files (x86)\Windows Kits\10\Lib\10.0.26100.0\ucrt\x64",
"C:\Program Files (x86)\Windows Kits\10\Lib\10.0.26100.0\um\x64"
) -join ";"
# Set compiler paths
$env:CC = "$msvcPath\bin\Hostx64\x64\cl.exe"
$env:CXX = "$msvcPath\bin\Hostx64\x64\cl.exe"
# Dynamically find latest CUDA version (not hardcoded!)
$cudaBasePath = "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA"
if (Test-Path $cudaBasePath) {
$cudaVersions = Get-ChildItem $cudaBasePath -Directory | Where-Object { $_.Name -match "^v\d" } | Sort-Object Name -Descending
if ($cudaVersions) {
$cudaDir = $cudaVersions[0].FullName
$env:CUDA_HOME = $cudaDir
$env:CUDA_PATH = $cudaDir
$env:PATH = "$cudaDir\bin;$env:PATH"
Write-Status " Using CUDA: $($cudaVersions[0].Name)"
# Build using nvcc directly (more reliable than Python distutils)
$originalLocation = Get-Location
try {
Set-Location "gpu\bitnet_kernels"
$nvcc = "$env:CUDA_HOME\bin\nvcc.exe"
& $nvcc bitnet_kernels.cu `
-o libbitnet.dll `
--shared `
-O3 `
-use_fast_math `
-std=c++17 `
"-gencode=arch=compute_75,code=sm_75" `
-Xcompiler "/MD" `
-allow-unsupported-compiler
if ($LASTEXITCODE -eq 0) {
Write-Status " [OK] BitNet CUDA kernel DLL built successfully" $Green
# IMMEDIATELY copy to Release folder (we're already in gpu\bitnet_kernels\)
if (Test-Path "libbitnet.dll") {
Copy-Item "libbitnet.dll" "$BuildDir\gpu\windows\bitnet-python-cuda\" -Force
Copy-Item "libbitnet.lib" "$BuildDir\gpu\windows\bitnet-python-cuda\" -Force -ErrorAction SilentlyContinue
Copy-Item "libbitnet.exp" "$BuildDir\gpu\windows\bitnet-python-cuda\" -Force -ErrorAction SilentlyContinue
# Copy CUDA runtime DLLs alongside libbitnet.dll for standalone operation
if ($env:CUDA_HOME) {
$cudaBinPath = "$env:CUDA_HOME\bin"
$cudaDlls = @("cudart64_*.dll", "cublas64_*.dll", "cublasLt64_*.dll", "nvrtc64_*.dll")
foreach ($pattern in $cudaDlls) {
$files = Get-ChildItem "$cudaBinPath\$pattern" -ErrorAction SilentlyContinue
foreach ($file in $files) {
Copy-Item $file.FullName "$BuildDir\gpu\windows\bitnet-python-cuda\" -Force -ErrorAction SilentlyContinue
}
}
Write-Status " [COPIED] libbitnet.dll + CUDA runtime DLLs → Release/gpu/windows/bitnet-python-cuda/" $Green
}
}
$env:BITNET_CUDA_SUCCESS = "true"
} else {
throw "NVCC compilation failed with exit code $LASTEXITCODE"
}
} finally {
# ALWAYS return to original location, even if error occurs
Set-Location $originalLocation
}
} else {
Write-Status " [WARN] CUDA versions not found - skipping Python GPU kernel" $Yellow
$env:BITNET_CUDA_SUCCESS = "false"
}
} else {
Write-Status " [WARN] CUDA not found - skipping Python GPU kernel" $Yellow
$env:BITNET_CUDA_SUCCESS = "false"
}
} catch {
Write-Status " [WARN] Failed to build BitNet CUDA kernels: $_" $Yellow
$env:BITNET_CUDA_SUCCESS = "false"
}
} else {
Write-Status " [SKIP] BitNet CUDA kernel source not found" $Yellow
$env:BITNET_CUDA_SUCCESS = "false"
}
# 14. Clean CMake caches and create build directories
Write-Status "14. Cleaning CMake caches and creating build directories..."
# Clean old CMake caches to avoid toolset conflicts
# Platform-specific build directory names (windows/linux) to avoid conflicts
$buildDirs = @(
"build-windows-standard",
"build-windows-gpu-cuda-vulkan",
"build-windows-gpu-opencl",
"build-windows-bitnet-portable",
# AMD Ryzen (all generations)
"build-windows-bitnet-amd-zen1",
"build-windows-bitnet-amd-zen2",
"build-windows-bitnet-amd-zen3",
"build-windows-bitnet-amd-zen4",
"build-windows-bitnet-amd-zen5",
# Intel Core (all generations)
"build-windows-bitnet-intel-haswell",
"build-windows-bitnet-intel-broadwell",
"build-windows-bitnet-intel-skylake",
"build-windows-bitnet-intel-icelake",
"build-windows-bitnet-intel-rocketlake",
"build-windows-bitnet-intel-alderlake"
)
foreach ($dir in $buildDirs) {
if (Test-Path $dir) {
Write-Status " Cleaning CMake cache in $dir..." $Yellow
Remove-Item "$dir\CMakeCache.txt" -Force -ErrorAction SilentlyContinue
Remove-Item "$dir\CMakeFiles" -Recurse -Force -ErrorAction SilentlyContinue
}
}
if ($CleanBuild) {
Write-Status " Cleaning previous WINDOWS build output only (preserving Linux/macOS)..." $Yellow
# Clean EVERYTHING in Windows directories (but preserve Linux/macOS)
if (Test-Path "$BuildDir\cpu\windows") {
Write-Status " Cleaning Release/cpu/windows/* ..." $Yellow
Get-ChildItem "$BuildDir\cpu\windows\*" | Remove-Item -Recurse -Force
}