#!/bin/bash
# desktop-w0-stage: build llama.cpp 3cf03257 NATIVELY on the desktop (lane desktop-w0-stage, D-098's stage step (a)), v2.
# v1 used the desktop's system nvcc (/usr/local/cuda -> cuda-13.1) and its configure FAILED: CUDA 13.1's crt/math_functions.h
# declares rsqrt/rsqrtf without the noexcept that glibc 2.43's mathcalls.h carries ("exception specification is
# incompatible"); CUDA 13.4 adds _NV_RSQRT_SPECIFIER for exactly this. v2 uses CUDA 13.4, the same toolkit (V13.4.92)
# that built the laptop's L-arm engine, staged by this lane in user space under ~/bench-flashnext/cuda-13.4 (a subset of
# the laptop's /usr/local/cuda-13.4: bin, nvvm, include, and the cudart/cublas/cublasLt/stub libraries). No sudo.
# Run inside: systemd-run --user --unit=desktop-w0-build -p CPUQuota=1600% ... /usr/bin/nice -n 19 bash build-w0-v2.sh
# Flags are the brief's: -G Ninja -DGGML_CUDA=ON -DCMAKE_CUDA_ARCHITECTURES=120 -DLLAMA_USE_PREBUILT_UI=OFF, plus
# CMAKE_CUDA_COMPILER naming the staged nvcc. GGML_NATIVE stays at its default (ON): a native build on the desktop targets
# the desktop's own EPYC 7532 (AVX2, no AVX-512, no AVX-VNNI), which is the point of building here (RECON N-2).
set -u
B=/workshop/bench-flashnext
SRC=$B/llama.cpp-3cf03257
CUDA=$B/cuda-13.4
LOGD=$B/build-logs
mkdir -p "$LOGD"
export PATH=$CUDA/bin:$PATH
say() { echo "$(date -u +%FT%TZ) build-w0-v2 $*"; }
say "START host=$(hostname) commit=$(git -C "$SRC" rev-parse HEAD) dirty_files=$(git -C "$SRC" status --porcelain | wc -l)"
say "nvcc=$(command -v nvcc) $(nvcc --version | tail -1)"
say "gcc=$(gcc --version | head -1) cmake=$(cmake --version | head -1) ninja=$(ninja --version)"
cd "$SRC" || exit 90
test ! -e build || { say "REFUSED: $SRC/build already exists (launch once)"; exit 91; }
cmake -S . -B build -G Ninja -DGGML_CUDA=ON -DCMAKE_CUDA_ARCHITECTURES=120 -DLLAMA_USE_PREBUILT_UI=OFF \
  -DCMAKE_CUDA_COMPILER="$CUDA/bin/nvcc" > "$LOGD/configure-v2.log" 2>&1
rc=$?; say "CONFIGURE rc=$rc"; [ $rc = 0 ] || exit $rc
t0=$(date +%s)
cmake --build build -j 16 > "$LOGD/build-v2.log" 2>&1
rc=$?; say "BUILD rc=$rc seconds=$(( $(date +%s) - t0 ))"
exit $rc
