Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,13 @@ Use `just build cpu` for a portable CPU runtime. macOS defaults to Metal;
Linux and Windows default to CPU unless a backend is supplied. CUDA builds
require the matching pinned toolkit and architecture list.

On Windows, `just build cpu` defaults to the machine's architecture. To build
the Windows ARM64 CPU runtime and CLI from x64, run
`scripts/build-windows.ps1 -Backend cpu -TargetArch arm64`. Install the Rust
`aarch64-pc-windows-msvc` target and the Visual Studio ARM64 MSVC and LLVM
Clang components. The runtime is placed alongside the ARM64 executable in
Cargo's target directory. This target currently uses the source build path.

Default tests are offline. Model-backed and accelerator qualification use
explicit certification commands and immutable fixtures. Do not make default
tests depend on a network, writable home directory, or undeclared system tools.
Expand Down
2 changes: 1 addition & 1 deletion Justfile
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ release-runtime-build backend="" target="":
scripts/package-native-runtime.sh "${args[@]}"

[windows]
release-runtime-build backend="cpu" target="x86_64-pc-windows-msvc":
release-runtime-build backend="cpu" target="":
@powershell -NoProfile -ExecutionPolicy Bypass -File scripts/build-windows.ps1 -Backend "{{ backend }}" -Target "{{ target }}" -BuildProfile release -RuntimeOnly

release-build backend="" target="":
Expand Down
60 changes: 57 additions & 3 deletions scripts/build-llama.sh
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,33 @@ case "$LLAMA_LINK_MODE" in
;;
esac

# Rust target triple of the runtime when the build does not simply follow the
# machine's own compiler. Only Windows ARM64 is handled: clang compiles it for
# the MSVC ABI, natively or across from x64, inside an MSVC environment that
# targets ARM64 (vcvarsall amd64_arm64 or arm64).
LLAMA_STAGE_TARGET="${LLAMA_STAGE_TARGET:-}"
case "$LLAMA_STAGE_TARGET" in
"") ;;
aarch64-pc-windows-msvc)
case "$(uname -s)" in
MINGW*|MSYS*|CYGWIN*) ;;
*)
echo "LLAMA_STAGE_TARGET=$LLAMA_STAGE_TARGET builds only on Windows" >&2
exit 1
;;
esac
if [[ "$LLAMA_BACKEND" != "cpu" ]]; then
echo "LLAMA_STAGE_TARGET=$LLAMA_STAGE_TARGET supports the cpu backend only, not $LLAMA_BACKEND" >&2
exit 1
fi
;;
*)
echo "unsupported LLAMA_STAGE_TARGET: $LLAMA_STAGE_TARGET" >&2
echo "expected aarch64-pc-windows-msvc or empty" >&2
exit 1
;;
esac

sanitize_build_component() {
printf '%s' "$1" | tr ';, /:' '_____' | tr -cd 'A-Za-z0-9_.-'
}
Expand All @@ -118,6 +145,9 @@ default_build_dir_for_backend() {
suffix="rocm-$(sanitize_build_component "$amdgpu_targets")"
;;
esac
if [[ -n "$LLAMA_STAGE_TARGET" ]]; then
suffix="$suffix-$(sanitize_build_component "$LLAMA_STAGE_TARGET")"
fi
# Key the build directory by the patched llama sha. The directory is otherwise
# keyed only by link mode and backend, so two different pins built on one machine
# share it -- and package-native-runtime.sh globs every *.dylib under it, shipping
Expand Down Expand Up @@ -360,9 +390,33 @@ fi
# nothing on make-based toolchains.
CMAKE_ARGS=(-G "$SELECTED_CMAKE_GENERATOR" "${CMAKE_ARGS[@]}")

case "$(uname -s)" in
MINGW*|MSYS*|CYGWIN*) CMAKE_ARGS+=(-DCMAKE_OBJECT_PATH_MAX=180) ;;
esac
if [[ "$LLAMA_STAGE_TARGET" == aarch64-pc-windows-msvc ]]; then
# ggml's CPU backend refuses MSVC on ARM unless GGML_NATIVE=ON, so clang
# compiles for the MSVC ABI and the DLLs import the same host runtime as the
# x64 build. armv8.2-a is the floor of Windows on ARM laptops. OpenMP is off,
# so ggml uses its own thread pool and no OpenMP runtime ships with the DLLs.
if ! command -v clang >/dev/null 2>&1; then
echo "clang is required for $LLAMA_STAGE_TARGET: add the Visual Studio component Microsoft.VisualStudio.Component.VC.Llvm.Clang to PATH" >&2
exit 1
fi
if [[ "${VSCMD_ARG_TGT_ARCH:-}" != arm64 ]]; then
echo "$LLAMA_STAGE_TARGET needs an MSVC environment that targets ARM64 (vcvarsall amd64_arm64 or arm64); VSCMD_ARG_TGT_ARCH is '${VSCMD_ARG_TGT_ARCH:-}'" >&2
exit 1
fi
CMAKE_ARGS+=(
-DCMAKE_SYSTEM_NAME=Windows
-DCMAKE_SYSTEM_PROCESSOR=ARM64
-DCMAKE_C_COMPILER=clang
-DCMAKE_CXX_COMPILER=clang++
-DCMAKE_C_COMPILER_TARGET=arm64-pc-windows-msvc
-DCMAKE_CXX_COMPILER_TARGET=arm64-pc-windows-msvc
-DCMAKE_ASM_COMPILER_TARGET=arm64-pc-windows-msvc
-DCMAKE_CXX_FLAGS_INIT=-DPATH_MAX=4096
-DGGML_NATIVE=OFF
-DGGML_OPENMP=OFF
-DGGML_CPU_ARM_ARCH=armv8.2-a
)
fi

case "$LLAMA_BACKEND" in
cuda)
Expand Down
115 changes: 82 additions & 33 deletions scripts/build-windows.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ param(
[string]$CudaArch = "",
[string]$RocmArch = "",
[ValidateSet("debug", "dev", "release")][string]$BuildProfile = "debug",
[ValidateSet("x86_64-pc-windows-msvc")][string]$Target = "x86_64-pc-windows-msvc",
[ValidateSet("", "x86_64-pc-windows-msvc", "aarch64-pc-windows-msvc")][string]$Target = "",
[ValidateSet("", "x64", "arm64")][string]$TargetArch = "",
[switch]$RuntimeOnly
)
$ErrorActionPreference = "Stop"
Expand Down Expand Up @@ -64,15 +65,8 @@ function Get-MissingCommands {
return $missing
}

function Ensure-MsvcToolchain {
$requiredTools = @("cl", "link", "lib", "rc", "mt")
$missingTools = @(Get-MissingCommands -Commands $requiredTools)
if ($missingTools.Count -eq 0) {
return
}

Write-Host "MSVC/Windows SDK tools missing before vcvars64 import: $($missingTools -join ', ')"

function Resolve-Vcvars {
param([string]$Component)
$programFilesX86 = ${env:ProgramFiles(x86)}
$vswhereCandidates = @()
if ($programFilesX86) {
Expand All @@ -86,41 +80,51 @@ function Ensure-MsvcToolchain {
$vswhereCandidates += $vswhereFromPath
}

$vcvars64 = $null
$vswhere = $vswhereCandidates | Where-Object { $_ -and (Test-Path $_) } | Select-Object -Unique -First 1
if ($vswhere) {
$installationPathOutput = & $vswhere -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath | Select-Object -First 1
$installationPathOutput = & $vswhere -latest -products * -requires $Component -property installationPath | Select-Object -First 1
$installationPath = if ($installationPathOutput) { $installationPathOutput.Trim() } else { "" }
if ($installationPath) {
$candidate = Join-Path $installationPath "VC\Auxiliary\Build\vcvars64.bat"
$candidate = Join-Path $installationPath "VC\Auxiliary\Build\vcvarsall.bat"
if (Test-Path $candidate) {
$vcvars64 = $candidate
return $candidate
}
}
}

if (-not $vcvars64) {
$searchRoots = @($programFilesX86, $env:ProgramFiles) | Where-Object { $_ } | Select-Object -Unique
foreach ($searchRoot in $searchRoots) {
$candidate = Get-ChildItem -Path $searchRoot -Filter vcvars64.bat -Recurse -ErrorAction SilentlyContinue |
Where-Object { $_.FullName -like '*Microsoft Visual Studio*VC\Auxiliary\Build\vcvars64.bat' } |
Select-Object -First 1
if ($candidate) {
$vcvars64 = $candidate.FullName
break
}
$searchRoots = @($programFilesX86, $env:ProgramFiles) | Where-Object { $_ } | Select-Object -Unique
foreach ($searchRoot in $searchRoots) {
$candidate = Get-ChildItem -Path $searchRoot -Filter vcvarsall.bat -Recurse -ErrorAction SilentlyContinue |
Where-Object { $_.FullName -like '*Microsoft Visual Studio*VC\Auxiliary\Build\vcvarsall.bat' } |
Select-Object -First 1
if ($candidate) {
return $candidate.FullName
}
}
throw "Visual Studio Build Tools with $Component and vcvarsall.bat are required."
}

function Ensure-MsvcToolchain {
param([string]$Architecture, [bool]$ArmHost)

if (-not (Test-Path $vcvars64)) {
throw "Visual Studio Build Tools with vcvars64.bat were not found on this Windows runner."
$requiredTools = @("cl", "link", "lib", "rc", "mt")
$missingTools = @(Get-MissingCommands -Commands $requiredTools)
if ($missingTools.Count -eq 0 -and $env:VSCMD_ARG_TGT_ARCH -eq $Architecture) {
return
}

Import-CmdEnvironment "`"$vcvars64`" >nul"
$component = if ($Architecture -eq "arm64") { "Microsoft.VisualStudio.Component.VC.Tools.ARM64" } else { "Microsoft.VisualStudio.Component.VC.Tools.x86.x64" }
$vcvars = Resolve-Vcvars $component
$argument = if ($Architecture -eq "arm64") {
if ($ArmHost) { "arm64" } else { "amd64_arm64" }
} else {
"amd64"
}
Import-CmdEnvironment "`"$vcvars`" $argument >nul"

$missingTools = @(Get-MissingCommands -Commands $requiredTools)
if ($missingTools.Count -gt 0) {
throw "MSVC toolchain initialization completed, but required Visual Studio/Windows SDK tools are still unavailable in PATH: $($missingTools -join ', '). Install the Windows SDK and Visual Studio Build Tools on this runner."
if ($missingTools.Count -gt 0 -or $env:VSCMD_ARG_TGT_ARCH -ne $Architecture) {
throw "MSVC must target $Architecture. Active target: '$env:VSCMD_ARG_TGT_ARCH'. Missing tools: $($missingTools -join ', ')."
}
}

Expand Down Expand Up @@ -181,10 +185,33 @@ function Invoke-NativeCommand {
throw "Command failed with exit code ${LASTEXITCODE}: $Command$argString"
}
}
$machineIsArm64 = [System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture -eq "Arm64"
if ($TargetArch) {
$archTarget = if ($TargetArch -eq "arm64") { "aarch64-pc-windows-msvc" } else { "x86_64-pc-windows-msvc" }
if ($Target -and $Target -ne $archTarget) { throw "-Target and -TargetArch must select the same architecture." }
$Target = $archTarget
}
if (-not $Target) {
$Target = if ($machineIsArm64) { "aarch64-pc-windows-msvc" } else { "x86_64-pc-windows-msvc" }
}
$architecture = if ($Target -eq "aarch64-pc-windows-msvc") { "arm64" } else { "x64" }
if (-not $Backend) { $Backend = "cpu" }
if ($architecture -eq "arm64" -and $Backend -ne "cpu") { throw "Windows ARM64 supports the CPU runtime only." }

$savedEnvironment = @{}
Get-ChildItem Env: | ForEach-Object { $savedEnvironment[$_.Name] = $_.Value }
Push-Location $repoRoot
try {
Ensure-MsvcToolchain
if (-not $Backend) { $Backend = "cpu" }
Ensure-MsvcToolchain $architecture $machineIsArm64
if ($architecture -eq "arm64" -and -not (Resolve-CommandPath "clang")) {
if ($env:VCINSTALLDIR) {
Add-ToPath (Join-Path $env:VCINSTALLDIR "Tools\Llvm\ARM64\bin")
Add-ToPath (Join-Path $env:VCINSTALLDIR "Tools\Llvm\x64\bin")
}
if (-not (Resolve-CommandPath "clang")) {
throw "Install Microsoft.VisualStudio.Component.VC.Llvm.Clang and add clang to PATH."
}
}
if ($Backend -eq "cuda") { Ensure-CudaToolchain }
$bash = Resolve-PackagingBash
if (-not $env:CC) { $env:CC = "cl" }
Expand All @@ -193,13 +220,35 @@ try {
if ($CudaArch) { $env:LLAMA_STAGE_CUDA_ARCHITECTURES = $CudaArch }
if ($RocmArch) { $env:LLAMA_STAGE_AMDGPU_TARGETS = $RocmArch }
$profile = if ($BuildProfile -eq "release") { "release" } else { "debug" }
$runtimeOut = if ($RuntimeOnly) { "dist/native-runtimes" } else { "target/$profile/native-runtimes" }
$runtimeOut = "dist/native-runtimes"
if (-not $RuntimeOnly) {
$cargoMetadata = & cargo metadata --locked --no-deps --format-version 1
if ($LASTEXITCODE -ne 0) { throw "cargo metadata failed with exit code $LASTEXITCODE" }
$targetDir = ($cargoMetadata | ConvertFrom-Json).target_directory
# Pass an explicit triple when crossing architectures. A native build
# keeps Cargo's ordinary layout unless the caller already selected a target.
if ($architecture -eq "arm64" -or $machineIsArm64 -or $env:CARGO_BUILD_TARGET) {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Resolve Cargo and native packaging to the same target. On an x64 host with CARGO_BUILD_TARGET=aarch64-pc-windows-msvc, omitting -Target selects x64 from the OS and this block overwrites the caller's ARM64 target. A target set via Cargo's build.target config can also escape this block, letting Cargo build for that target while the wrapper packages x64 and prints an unqualified output path. Resolve one effective triple before initializing MSVC, honor or explicitly reject conflicting caller settings, and use that triple for both builds and the output directory.

$env:CARGO_BUILD_TARGET = $Target
$targetDir = Join-Path $targetDir $Target
}
$productDir = Join-Path $targetDir $profile
$nativePath = Join-Path $productDir "native-runtimes"
$runtimeOut = (& $bash -c 'cygpath -au "$1"' bash $nativePath | Out-String).Trim()
if ($LASTEXITCODE -ne 0 -or -not $runtimeOut) { throw "Cannot convert $nativePath for the packaging shell." }
}
Invoke-NativeCommand $bash @("scripts/package-native-runtime.sh", "--build", "--backend", $Backend, "--target", $Target, "--out", $runtimeOut)
if (-not $RuntimeOnly) {
$recipe = if ($BuildProfile -eq "release") { "skippy-cli-release-build" } else { "skippy-cli-build" }
Invoke-NativeCommand "just" @($recipe)
Write-Host "Built Skippy: target/$profile/skippy.exe"
Write-Host "Built Skippy: $(Join-Path $productDir 'skippy.exe')"
}
} finally {
Pop-Location
Get-ChildItem Env: | Where-Object { -not $savedEnvironment.ContainsKey($_.Name) } |
ForEach-Object { Remove-Item -LiteralPath "env:$($_.Name)" }
foreach ($name in $savedEnvironment.Keys) {
if ([Environment]::GetEnvironmentVariable($name) -cne $savedEnvironment[$name]) {
Set-Item -LiteralPath "env:$name" -Value $savedEnvironment[$name]
}
}
}
1 change: 1 addition & 0 deletions scripts/lib/native_policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@
"armv7-unknown-linux-gnueabihf": ("linux", "arm"),
"armv7-linux-androideabi": ("linux", "arm"),
"x86_64-pc-windows-msvc": ("windows", "x86_64"),
"aarch64-pc-windows-msvc": ("windows", "aarch64"),
}

HOST_TARGETS = {
Expand Down
12 changes: 10 additions & 2 deletions scripts/native-inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,11 +113,19 @@ def verify_directory(root, resolve_rocm):
if (not isinstance(libraries, list) or primary not in libraries or primary not in files
or files[primary] != build["library_sha256"]):
raise ValueError("invalid native primary library")
for name in [*libraries, *tools]:
binaries = dict.fromkeys([*libraries, *tools])
if platform["os"] == "windows":
binaries.update(dict.fromkeys(name for name in files if Path(name).suffix.lower() in {".dll", ".exe"}))
for folder in ("lib", "tools"):
binaries.update(dict.fromkeys(
path.relative_to(root).as_posix() for path in (root / folder).rglob("*")
if path.is_file() and path.suffix.lower() in {".dll", ".exe"}
))
for name in binaries:
if name not in files and name not in tools:
raise ValueError(f"unhashed runtime library: {name}")
image = inspect(contained_file(root, name))
if image.arch != platform["arch"]:
if image.arch != platform["arch"] or (platform["os"] == "windows" and image.kind != "pe"):
raise ValueError(f"runtime architecture mismatch: {name}")
external_rocm = False
for imported in image.imports:
Expand Down
17 changes: 16 additions & 1 deletion scripts/package-native-runtime.sh
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ default_target_triple() {
linux/x86_64) printf 'x86_64-unknown-linux-gnu\n' ;;
linux/aarch64) printf 'aarch64-unknown-linux-gnu\n' ;;
windows/x86_64) printf 'x86_64-pc-windows-msvc\n' ;;
windows/aarch64) printf 'aarch64-pc-windows-msvc\n' ;;
*) printf '\n' ;;
esac
}
Expand All @@ -164,6 +165,7 @@ target_platform() {
x86_64-unknown-linux-gnu) printf 'linux-x86_64\n' ;;
aarch64-unknown-linux-gnu) printf 'linux-aarch64\n' ;;
x86_64-pc-windows-msvc) printf 'windows-x86_64\n' ;;
aarch64-pc-windows-msvc) printf 'windows-aarch64\n' ;;
*) printf '%s\n' "$1" | tr '_' '-' ;;
esac
}
Expand Down Expand Up @@ -730,6 +732,15 @@ if [[ -z "$TARGET_TRIPLE" ]]; then
exit 1
fi

llama_stage_target=""
if [[ "$TARGET_TRIPLE" == aarch64-pc-windows-msvc ]]; then
llama_stage_target="$TARGET_TRIPLE"
if [[ "$BACKEND" != cpu ]]; then
echo "Windows ARM64 supports only the CPU runtime" >&2
exit 1
fi
fi

# The build directory is keyed by the checkout's pin stamp, so it can only be
# resolved after the pin is prepared. Resolving first would key the new pin's
# build to the previous stamp -- or to no stamp at all on a fresh checkout --
Expand All @@ -739,13 +750,14 @@ if [[ "$BUILD" == "1" ]]; then
fi

if [[ -z "${LLAMA_STAGE_BUILD_DIR:-}" ]]; then
LLAMA_STAGE_BUILD_DIR="$(LLAMA_STAGE_LINK_MODE=dynamic LLAMA_STAGE_BACKEND="$(build_backend)" "$SCRIPT_DIR/build-llama.sh" --print-build-dir)"
LLAMA_STAGE_BUILD_DIR="$(LLAMA_STAGE_LINK_MODE=dynamic LLAMA_STAGE_BACKEND="$(build_backend)" LLAMA_STAGE_TARGET="$llama_stage_target" "$SCRIPT_DIR/build-llama.sh" --print-build-dir)"
fi

if [[ "$BUILD" == "1" ]]; then
env \
LLAMA_STAGE_LINK_MODE=dynamic \
LLAMA_STAGE_BACKEND="$(build_backend)" \
LLAMA_STAGE_TARGET="$llama_stage_target" \
LLAMA_BUILD_DIR="$LLAMA_STAGE_BUILD_DIR" \
LLAMA_STAGE_BUILD_DIR="$LLAMA_STAGE_BUILD_DIR" \
"$SCRIPT_DIR/build-llama.sh"
Expand Down Expand Up @@ -922,6 +934,9 @@ fi
manifest_args+=(-- "${linux_relocatable_library_paths[@]}")

"${SKIPPY_PYTHON:-python3}" "$SCRIPT_DIR/native-manifest.py" --schema-v2 "${manifest_args[@]}"
if [[ -n "$llama_stage_target" ]]; then
"${SKIPPY_PYTHON:-python3}" "$SCRIPT_DIR/native-inspect.py" verify-runtime-package "$stage_dir"
fi

cat > "$stage_dir/README.md" <<EOF
# $artifact_id
Expand Down
Loading
Loading