machine-learning.scm (19291B)
1 (define-module (epistemia packages machine-learning) 2 #:use-module (guix packages) 3 #:use-module (guix build-system cmake) 4 #:use-module (guix build-system go) 5 #:use-module (guix download) 6 #:use-module (guix utils) 7 #:use-module (guix git-download) 8 #:use-module (guix gexp) 9 #:use-module ((guix licenses) #:prefix license:) 10 #:use-module (gnu packages base) 11 #:use-module (gnu packages bash) 12 #:use-module (gnu packages golang-check) 13 #:use-module (gnu packages golang-web) 14 #:use-module (gnu packages golang-xyz) 15 #:use-module (gnu packages llvm) 16 #:use-module (gnu packages machine-learning) 17 #:use-module (gnu packages rocm) 18 #:use-module (gnu packages rocm-libs) 19 #:use-module (gnu packages python) 20 #:use-module (gnu packages python-crypto) 21 #:use-module (gnu packages python-web) 22 #:use-module (gnu packages python-xyz)) 23 24 (define-public ggml-rocm 25 (package 26 (inherit ggml) 27 (name "ggml-rocm") 28 (version "1.0.0") 29 (source 30 (origin 31 (method git-fetch) 32 (uri (git-reference 33 (url "https://github.com/ggml-org/ggml") 34 (commit (string-append "v" version)))) 35 (file-name (git-file-name name version)) 36 (sha256 37 (base32 "08g9vy934dawskkjw3cbgznz191lwy49hzpphyy9yg39adbm48ai")))) 38 (arguments 39 (substitute-keyword-arguments (package-arguments (@@ (gnu packages machine-learning) ggml)) 40 ((#:configure-flags flags #~'()) 41 #~(append #$flags (list (string-append "-DCMAKE_HIP_COMPILER_ROCM_ROOT=" #$rocm-hip-runtime) 42 (string-append "-DCMAKE_HIP_FLAGS=--rocm-path=" #$rocm-hip-runtime 43 " --rocm-device-lib-path=" #$rocm-device-libs "/amdgcn/bitcode" 44 ;; CMAKE_HIP_FLAGS is to workaround regression in ROCm 7.2 45 " -mllvm --amdgpu-unroll-threshold-local=600") 46 #$(string-append "-DGPU_TARGETS=" (current-amd-gpu-targets-string)) 47 "-DGGML_CPU=ON" 48 "-DGGML_OPENCL=OFF" 49 "-DGGML_VULKAN=ON" 50 "-DGGML_HIP=ON" 51 "-DGGML_HIP_ROCWMMA_FATTN=ON" 52 "-DGGML_HIP_GRAPHS=ON" 53 "-DGGML_HIP_RCCL=ON" 54 "-DGGML_CUDA_FA_ALL_QUANTS=ON" 55 ;; for stable-diffusion.cpp 56 "-DGGML_CPU_ALL_VARIANTS=ON"))) 57 ((#:phases phases #~%standard-phases) 58 #~(modify-phases #$phases 59 ;; for stable-diffusion.cpp 60 (add-before 'configure 'set-ggml-max-name 61 (lambda _ 62 (setenv "CFLAGS" "-DGGML_MAX_NAME=160") 63 (setenv "CXXFLAGS" "-DGGML_MAX_NAME=160"))) 64 ;; for stable-diffusion.cpp's upstream-ggml compatibility layer, which needs this private function 65 (add-before 'configure 'export-ggml-graph-view 66 (lambda _ 67 (substitute* "src/ggml-impl.h" 68 (("^struct ggml_cgraph ggml_graph_view" all) 69 (string-append "GGML_API " all))))))))) 70 (inputs 71 (modify-inputs (package-inputs ggml) 72 (append clang-rocm 73 lld-rocm 74 rocm-cmake 75 rocm-device-libs 76 rocm-hipcc 77 rocm-hip-runtime 78 rocr-runtime 79 hipblas 80 hipblas-common 81 hipblaslt 82 rocblas 83 rccl))) 84 (properties `((amd-gpu-targets . ,%default-amd-gpu-targets))))) 85 86 (define-public llama-cpp-rocm 87 (let ((tag "b12632") 88 (ui-build "12631")) 89 (package 90 (inherit llama-cpp) 91 (name "llama-cpp-rocm") 92 (version (string-append "0.0.0-" tag)) 93 (source 94 (origin 95 (method git-fetch) 96 (uri (git-reference 97 (url "https://github.com/ggml-org/llama.cpp") 98 (commit tag))) 99 (file-name (git-file-name name tag)) 100 (sha256 101 (base32 "1zannb5b2d1hrifzcr2s13sy9i9r4g39paxwhywamp0facjnkv7h")) 102 (patches (list (plain-file "pulpie-eurobert.patch" "\ 103 diff --git a/src/models/eurobert.cpp b/src/models/eurobert.cpp 104 index 7a42f0dbf..9047f1b97 100644 105 --- a/src/models/eurobert.cpp 106 +++ b/src/models/eurobert.cpp 107 @@ -15,6 +15,18 @@ void llama_model_eurobert::load_arch_tensors(llama_model_loader &) { 108 109 output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, \"weight\"), {n_embd}, 0); 110 111 + // optional token-classification head (e.g. main-content extraction models). 112 + // applied per position in the graph below, so it stays independent of the 113 + // sequence pooling type. 114 + cls_out = create_tensor(tn(LLM_TENSOR_CLS_OUT, \"weight\"), {n_embd, hparams.n_cls_out}, TENSOR_NOT_REQUIRED); 115 + cls_out_b = create_tensor(tn(LLM_TENSOR_CLS_OUT, \"bias\"), {hparams.n_cls_out}, TENSOR_NOT_REQUIRED); 116 + 117 + if (cls_out) { 118 + // the graph below emits n_cls_out values per token, so the embedding 119 + // output is no longer n_embd wide. covers GGUFs that omit embedding_length_out. 120 + hparams.n_embd_out_impl = hparams.n_cls_out; 121 + } 122 + 123 for (int i = 0; i < n_layer; ++i) { 124 auto & layer = layers[i]; 125 126 @@ -110,4 +122,16 @@ llama_model_eurobert::graph::graph(const llm_graph_params & params) : llm_graph_ 127 128 cb(cur, \"result_embd\", -1); 129 res->t_embd = cur; 130 + 131 + if (model.cls_out) { 132 + // classify every position, not just the pooled sequence: the caller reads 133 + // one n_cls_out-sized row per token. 134 + ggml_tensor * embd = build_lora_mm(model.cls_out, cur); 135 + if (model.cls_out_b) { 136 + embd = ggml_add(ctx0, embd, model.cls_out_b); 137 + } 138 + cb(embd, \"result_embd_proj\", -1); 139 + res->t_embd = embd; 140 + ggml_build_forward_expand(gf, embd); 141 + } 142 }\n"))))) 143 (arguments 144 (substitute-keyword-arguments (package-arguments llama-cpp) 145 ((#:configure-flags flags #~'()) 146 #~(append #$flags 147 '("-DLLAMA_BUILD_TESTS=OFF" 148 "-DLLAMA_USE_PREBUILT_UI=OFF"))) 149 ((#:phases phases) 150 #~(modify-phases #$phases 151 (delete 'fix-python-shebang) 152 ;; upstream moved webui from tools/ui to ui/apps/chat 153 (delete 'get-ui) 154 (add-after 'unpack 'get-ui 155 (lambda _ 156 (let ((dist "ui/apps/chat/dist")) 157 (mkdir-p dist) 158 (invoke "tar" "xf" 159 #$(this-package-input "ui.tar.gz") 160 "-C" dist "--strip-components=1")))))))) 161 (inputs 162 (modify-inputs (package-inputs llama-cpp) 163 (replace "ggml" ggml-rocm) 164 (replace "ui.tar.gz" 165 (origin 166 (method url-fetch) 167 (uri (string-append 168 "https://github.com/ggml-org/llama.cpp/releases/download/b" 169 ui-build "/llama-b" ui-build "-ui.tar.gz")) 170 (file-name "ui.tar.gz") 171 (sha256 172 (base32 "0iwpb2595q0w2859paph0jmf29n3sz283yl6xhzfh9a37wygi63y"))))))))) 173 174 (define-public stable-diffusion-cpp-rocm 175 (package 176 (inherit stable-diffusion-cpp) 177 (name "stable-diffusion-cpp-rocm") 178 (arguments 179 (substitute-keyword-arguments (package-arguments stable-diffusion-cpp) 180 ((#:configure-flags flags #~'()) 181 #~(append #$flags (list "-DHIP_PLATFORM=amd" 182 "-DSD_HIPBLAS=ON" 183 "-DSD_SERVER_BUILD_FRONTEND=OFF" 184 "-DSD_USE_SYSTEM_GGML=ON" 185 "-DSD_USE_UPSTREAM_GGML=ON" 186 "-DSD_VULKAN=ON" 187 "-DSD_WEBP=OFF" 188 "-DSD_WEBM=OFF" 189 ;; use matching ggml source tree 190 (string-append "-DSD_GGML_SOURCE_DIR=" 191 #$(package-source (this-package-input "ggml-rocm")))))) 192 193 ((#:phases phases #~%standard-phases) 194 #~(modify-phases #$phases 195 ;; upstream dropped its own 'set-CXXFLAGS phase and passes 196 ;; -DGGML_MAX_NAME=160 as a configure flag instead, which 197 ;; does not reach the external ggml-rocm headers 198 (add-before 'configure 'set-CXXFLAGS 199 (lambda _ 200 (setenv "CFLAGS" "-DGGML_MAX_NAME=160") 201 (setenv "CXXFLAGS" "-DGGML_MAX_NAME=160"))))))) 202 (inputs 203 (modify-inputs (package-inputs stable-diffusion-cpp) 204 (append ggml-rocm 205 rocm-hip-runtime 206 rocm-device-libs 207 rocr-runtime 208 hipblas 209 hipblaslt))))) 210 211 (define-public strata-rdna3 212 (let* ((commit "f557b544") 213 ;; strata is pinned to an older llama.cpp's ggml; 214 ;; using package-source llama-cpp-rocm instead has "incorrect number of function argument" errors 215 (llama-cpp-commit "3cf03257f219afbe7334045ff7c6a06ac68c627d") 216 (llama-cpp-source 217 (origin 218 (method git-fetch) 219 (uri (git-reference 220 (url "https://github.com/ggml-org/llama.cpp") 221 (commit llama-cpp-commit))) 222 (file-name (git-file-name "llama-cpp-strata" llama-cpp-commit)) 223 (sha256 224 (base32 "10hr8pkszphsylrg3j055pb0s4v2qpaip6kp0x12005qmxfsh4a9"))))) 225 (package 226 (name "strata-rdna3") 227 (version (string-append "0.0.0-" commit)) ;; arbitrary, the project, or at least fork, doensn't do versioning 228 (source 229 (origin 230 (method git-fetch) 231 (uri (git-reference 232 (url "https://github.com/nicejunjie/strata-rdna3") 233 (commit commit) 234 (recursive? #t))) 235 (file-name (git-file-name name version)) 236 (sha256 237 (base32 "15vr8prmmjx5ci7mw1p25z0pghp1x3nqgazfbd690a84668kfii1")) 238 ;; patches required for fixing compiler errors and incoherent inference and failed tests 239 (patches (list (plain-file "strata-rdna3-shared_expert.patch" "\ 240 diff --git a/src/kernels/cuda/shared_expert.cu b/src/kernels/cuda/shared_expert.cu 241 index f8b58963..dee881af 100644 242 --- a/src/kernels/cuda/shared_expert.cu 243 +++ b/src/kernels/cuda/shared_expert.cu 244 @@ -421,8 +421,8 @@ void shared_expert(const uint8_t* x_q8_0, const uint8_t* x_q8k, const uint16_t* 245 // gate and up projections, then silu(gate) * up in place in `gate` 246 // [claude] native->x_q8_1: the caller's q8_1 image of x (STRATA_MTP_QFUSE: the hyper-connection read wrote it, the same bytes 247 // native_quantize_q8_1 writes) - read as is; the quantize launch is skipped 248 - const void* x_q8 = native->x_q8_1 != nullptr ? native->x_q8_1 : native->q8_1; 249 - if ((native_gate || native_up) && native->x_q8_1 == nullptr) 250 + const void* x_q8 = native == nullptr ? nullptr : (native->x_q8_1 != nullptr ? native->x_q8_1 : native->q8_1); 251 + if ((native_gate || native_up) && native != nullptr && native->x_q8_1 == nullptr) 252 native_quantize_q8_1(x_f32, native->q8_1, (int) n_embd, 1, stream); 253 if (native_gate) 254 native_mmvq(native->gate_type, native->gate_data, x_q8, gate, (int) n_embd, (int) n_ff, 1, stream);") 255 (plain-file "strata-rdna3-alignas.patch" "\ 256 diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cu 257 index c8f60b61..ec17bb20 100644 258 --- a/src/kernels/cuda/iq_kernels.cu 259 +++ b/src/kernels/cuda/iq_kernels.cu 260 @@ -1776,8 +1776,10 @@ struct IqGridWords { 261 // with MSVC as host does not take it. Same layout either way. 262 #if defined(__HIPCC__) 263 #define STRATA_SHARED_ALIGN16_U32(name, ...) __shared__ uint32_t name[__VA_ARGS__] __attribute__((aligned(16))) 264 +#define STRATA_SHARED_ALIGN16_INT4(name, ...) __shared__ int4 name[__VA_ARGS__] __attribute__((aligned(16))) 265 #else 266 #define STRATA_SHARED_ALIGN16_U32(name, ...) __shared__ alignas(16) uint32_t name[__VA_ARGS__] 267 +#define STRATA_SHARED_ALIGN16_INT4(name, ...) __shared__ alignas(16) int4 name[__VA_ARGS__] 268 #endif 269 template<int TY, int NC, bool STAGE_GRID = kStageIqGrid<TY>, bool EXACT_N = false> 270 __global__ void __launch_bounds__(128) mmvq_multi_kernel(const uint8_t* __restrict__ w, size_t row_bytes, 271 @@ -2474,7 +2476,7 @@ __global__ void __launch_bounds__(256, MINB) expdec_gu_kernel(const unsigned lon 272 float* __restrict__ gate, float* __restrict__ up, int rb) { 273 const int ng = *n_groups; 274 if (blockIdx.y >= ng) return; 275 - __shared__ alignas(16) int4 s_u[ED_NC * 2 * ED_XB]; 276 + STRATA_SHARED_ALIGN16_INT4(s_u, ED_NC * 2 * ED_XB); 277 __shared__ float s_ds[ED_NC * ED_XB]; 278 STRATA_SHARED_ALIGN16_U32(s_grid_buf, EdGrid<TG>::words); 279 const int tid = threadIdx.x; 280 @@ -2661,7 +2663,7 @@ __global__ void __launch_bounds__(256, STRATA_EXPDEC_MINB) expdec_down_kernel(co 281 if (blockIdx.y >= ng) return; 282 constexpr int LANES = TD == 20 ? 8 : 16; 283 constexpr int RPP = (256 / LANES) * R; // rows per pass 284 - __shared__ alignas(16) int4 s_u[ED_NC * 2 * ED_HB]; 285 + STRATA_SHARED_ALIGN16_INT4(s_u, ED_NC * 2 * ED_HB); 286 __shared__ float s_ds[ED_NC * ED_HB]; 287 const int tid = threadIdx.x; 288 const int sw = tid / LANES, t = tid % LANES;") 289 (plain-file "strata-rdna3-default_reasoning_effort.patch" "\ 290 diff --git a/serve/server.py b/serve/server.py 291 index 0ded16f8..6a7bee00 100644 292 --- a/serve/server.py 293 +++ b/serve/server.py 294 @@ -8168,6 +8168,9 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in 295 help=\"the mock engine's answer (default: a short greeting); given more than once, requests get \" 296 \"them in turn and the last one repeats\") 297 ap.add_argument(\"--port\", type=int, default=8095) 298 + ap.add_argument(\"--reasoning-effort\", metavar=\"LEVEL\", choices=[\"none\", \"low\", \"medium\", \"high\", \"xhigh\"], 299 + help=\"default thinking level (none, low, medium, high, xhigh); overrides the config, \" 300 + \"while requests and shared Chat settings can override it\") 301 ap.add_argument(\"--ready-file\", help=\"write a JSON instance record once the API is bound and model state is known\") 302 ap.add_argument(\"--owner-fd\", type=int, help=argparse.SUPPRESS) 303 ap.add_argument(\"--shutdown-timeout\", type=float, default=None, 304 @@ -8295,6 +8298,8 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in 305 ap.error(\"--batch-groups conflicts with the saved engine args\") 306 cfg[\"args\"] = [*cfg[\"args\"], \"--batch-groups\", a.batch_groups] 307 lift_reasoning_effort_arg(cfg) 308 + if a.reasoning_effort is not None: 309 + cfg[\"reasoning_effort\"] = \"high\" if a.reasoning_effort == \"xhigh\" else a.reasoning_effort 310 if a.replicas is not None: 311 cfg[\"replicas\"] = a.replicas 312 if a.gpu is not None: 313 @@ -8499,7 +8504,8 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in 314 except ValueError as e: 315 raise SystemExit(f\"[strata] config {e}\") 316 if svc.config_effort: 317 - print(f\"[strata] thinking level: {svc.config_effort} (reasoning_effort in the config; a request, or the \" 318 + effort_source = \"--reasoning-effort\" if a.reasoning_effort is not None else \"reasoning_effort in the config\" 319 + print(f\"[strata] thinking level: {svc.config_effort} ({effort_source}; a request, or the \" 320 \"Chat settings shared with other apps, can set its own)\", flush=True) 321 svc.codex_thread_titles = cfg.get(\"codex_thread_titles\") is True # #923: opt-in, off by default 322 svc.codex_compaction_cache = cfg.get(\"codex_compaction_cache\") is True # #924: opt-in, off by default"))))) 323 (build-system cmake-build-system) 324 (arguments 325 (list #:tests? #f ;; failing tests require rocm-capable gpu, which I don't see a way to fix without changing guix-daemon chroot 326 #:patch-shebangs? #f ;; when true, rewrites bin/strata-server to the bare input python instead of wrapped python 327 #:configure-flags 328 #~(list "-DHIP_PLATFORM=amd" 329 "-DSTRATA_ENABLE_HIP=ON" 330 "-DSTRATA_PREFILL_MMQ=ON" 331 "-DSTRATA_MMQ_KQUANTS=ON" 332 "-DCMAKE_HIP_ARCHITECTURES=gfx1100" ;; this is a rdna3-focused fork 333 "-DSTRATA_BUILD_TESTS=OFF" 334 (string-append "-DSTRATA_GGML_DIR=" #$llama-cpp-source) ;; there isn't a submodule 335 (string-append "-DCMAKE_HIP_COMPILER=" #$clang-22 "/bin/clang++") ;; incoherent with default clang-20 336 (string-append "-DCMAKE_HIP_COMPILER_ROCM_ROOT=" #$rocm-hip-runtime) 337 (string-append "-DCMAKE_HIP_FLAGS=--rocm-path=" #$rocm-hip-runtime 338 " --rocm-device-lib-path=" #$rocm-device-libs "/amdgcn/bitcode")) 339 #:phases 340 #~(modify-phases %standard-phases 341 (add-after 'install 'actually-install-bin 342 ;; strata doesn't do any installation, so it needs to be done manually 343 ;; below is llm'd a bit (dsv4.1-flash-1017 with pi) with clean-up; too tedious otherwise 344 (lambda* (#:key inputs outputs #:allow-other-keys) 345 (let* ((out (assoc-ref outputs "out")) 346 (build (getcwd)) 347 (source (string-append (dirname build) "/source")) 348 (share (string-append out "/share/strata")) 349 (libexec (string-append out "/libexec/strata")) 350 (python (assoc-ref inputs "python")) 351 (bash (assoc-ref inputs "bash-minimal")) 352 (python-dir (string-append 353 "python" 354 #$(version-major+minor (package-version python)))) 355 (site-packages 356 (lambda (input) 357 (string-append (assoc-ref inputs input) 358 "/lib/" python-dir "/site-packages"))) 359 (pythonpath 360 (string-join 361 (map site-packages 362 '("python-numpy" "python-jinja2" "python-regex" 363 "python-pyyaml" "python-tqdm" "python-requests" 364 "python-pillow" "python-psutil" "python-markupsafe" 365 "python-certifi" "python-truststore" 366 "python-charset-normalizer" "python-idna" 367 "python-urllib3")) 368 ":"))) 369 ;; copy engine 370 (mkdir-p libexec) 371 (install-file (string-append build "/strata") 372 libexec) 373 ;; copy python tree 374 (for-each (lambda (dir) 375 (copy-recursively 376 (string-append source "/" dir) 377 (string-append share "/" dir))) 378 '("serve" "tools" "data" "include" "rdna3" "src" "third_party" 379 "strata_control" "strata_cli")) 380 ;; create python wrapper that sets PYTHONPATH 381 (symlink (string-append python "/bin/python3") 382 (string-append libexec "/python3")) 383 (wrap-program (string-append libexec "/python3") 384 #:sh (string-append bash "/bin/bash") 385 `("GUIX_PYTHONPATH" ":" prefix (,pythonpath)) 386 `("PYTHONPATH" ":" prefix (,share))) 387 ;; use wrapped python to run the api server 388 (mkdir-p (string-append out "/bin")) 389 (let ((server (string-append out "/bin/strata-server"))) 390 (call-with-output-file server 391 (lambda (port) 392 (format port 393 "#!~a/python3~%from serve.server import main~%raise SystemExit(main())~%" 394 libexec))) 395 (chmod server #o555)))))))) 396 (inputs 397 (list clang-22 ;; clang 23 needs rocm newer than 7.1.1 398 lld-rocm 399 rocm-cmake 400 rocm-device-libs 401 rocm-hipcc 402 rocm-hip-runtime 403 rocr-runtime 404 hipblas 405 hipblas-common 406 hipblaslt 407 rocblas 408 rccl 409 bash-minimal 410 python 411 python-numpy 412 python-jinja2 413 python-regex 414 python-pyyaml 415 python-tqdm 416 python-requests 417 python-pillow 418 python-psutil 419 python-markupsafe 420 python-certifi 421 python-truststore 422 python-charset-normalizer 423 python-idna 424 python-urllib3)) 425 (properties '((tunable? . #t))) 426 (home-page "https://github.com/nicejunjie/strata-rdna3") 427 (synopsis "Fork of the Strata LLM inference engine, tuned for RDNA3 (gfx1100/RX 7900 XTX).") 428 (description "Fork of the Strata LLM inference engine, tuned for RDNA3 (gfx1100/RX 7900 XTX). 429 430 Includes optimized kernels, added tensor parallelism, etc. 431 432 notes: setup.py generates the config in regular strata, but there's 433 already presets in the share/rdna3/configs/ directory that can be used 434 if you have the same setup. the generated config has quite a few paths 435 referring to the store directory, it would be more convenient to have 436 this package installed in a persistent profile and refer to those 437 paths instead of /gnu/store.") 438 (license license:expat))))