### run_sampled_generation session setup and prefill Source: https://github.com/antirez/ds4/blob/main/gguf-tools/imatrix/dataset/rendered_prompts_think.txt Creates a session, installs the progress callback, runs the synchronous prefill, and measures prefill time. On failure it clears the callback, prints the error, frees the session, and returns 1. ```c static int run_sampled_generation(ds4_engine *engine, const cli_config *cfg, const ds4_tokens *prompt) { ds4_session *session = NULL; if (ds4_session_create(&session, engine, cfg->gen.ctx_size) != 0) { fprintf(stderr, "ds4: sampled CLI generation requires a session backend\n"); return 1; } char err[160]; ds4_think_mode think_mode = cli_effective_think_mode(&cfg->gen); token_printer printer = { .engine = engine, .fp = stdout, .format_thinking = ds4_think_mode_enabled(think_mode), .in_think = ds4_think_mode_enabled(think_mode), .use_color = isatty(fileno(stdout)) != 0, .last_output_newline = true, }; cli_prefill_progress progress = { .base_tokens = 0, .input_tokens = prompt->len, .use_color = ds4_log_is_tty(stderr), }; const double t_prefill0 = cli_now_sec(); ds4_session_set_progress(session, cli_prefill_progress_cb, &progress); if (ds4_session_sync(session, prompt, err, sizeof(err)) != 0) { ds4_session_set_progress(session, NULL, NULL); fprintf(stderr, "ds4: prompt processing failed: %s\n", err); ds4_session_free(session); return 1; } ds4_session_set_progress(session, NULL, NULL); const double t_prefill1 = cli_now_sec(); ``` -------------------------------- ### Setup for copy examples: import copy and create nested list Source: https://github.com/antirez/ds4/blob/main/gguf-tools/quality-testing/deepseek-v4.1-flash-20260919-router/continuations/case_009.txt Imports the copy module and creates a nested list 'original' containing two inner lists. This is the starting point for demonstrating shallow and deep copy behavior. ```python import copy original = [[1, 2, 3], [4, 5, 6]] ``` -------------------------------- ### Server - Start server Source: https://github.com/antirez/ds4/blob/main/gguf-tools/imatrix/dataset/rendered_prompts.txt Starts a local OpenAI/Anthropic-compatible server with configurable context and disk-backed KV cache. ```APIDOC ## Server - Start server ### Description Starts a local OpenAI/Anthropic-compatible server. The server keeps one mutable backend/KV checkpoint in memory, so stateless clients that resend a longer version of the same prompt can reuse the shared prefix instead of pre-filling from token zero. ### Usage ```sh ./ds4-server --ctx 100000 --kv-disk-dir /tmp/ds4-kv --kv-disk-space-mb 8192 ``` ### Parameters #### Command-Line Arguments - **--ctx** (integer) - Required - The context window size in tokens. - **--kv-disk-dir** (string) - Required - Directory for the disk-backed KV cache. - **--kv-disk-space-mb** (integer) - Required - Maximum disk space for the KV cache in megabytes. ### Notes - Request parsing and sockets run in client threads, but inference is serialized through one graph worker. - The server does not batch multiple independent requests; concurrent requests wait their turn on the single live graph/session. ``` -------------------------------- ### Initialize ds4-server engine and install signal handlers in main() Source: https://github.com/antirez/ds4/blob/main/gguf-tools/imatrix/dataset/rendered_prompts.txt Installs SIGINT/SIGTERM handlers, parses options, opens the engine, and logs context memory. Exits with status 1 if ds4_engine_open fails. ```c #ifndef DS4_SERVER_TEST int main(int argc, char **argv) { signal(SIGPIPE, SIG_IGN); struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = stop_signal_handler; sigemptyset(&sa.sa_mask); sigaction(SIGINT, &sa, NULL); sigaction(SIGTERM, &sa, NULL); server_config cfg = parse_options(argc, argv); ds4_engine *engine = NULL; if (ds4_engine_open(&engine, &cfg.engine) != 0) return 1; log_context_memory(cfg.engine.backend, cfg.ctx_size); ``` -------------------------------- ### Server - Start server Source: https://github.com/antirez/ds4/blob/main/gguf-tools/imatrix/dataset/rendered_prompts_think.txt Starts the local OpenAI/Anthropic-compatible server. ```APIDOC ## Server - Start server ### Description Starts the local OpenAI/Anthropic-compatible server with a mutable backend/KV checkpoint. ### Usage ```sh ./ds4-server --ctx 100000 --kv-disk-dir /tmp/ds4-kv --kv-disk-space-mb 8192 ``` ### Parameters - `--ctx` (integer) - Required - Context length in tokens. - `--kv-disk-dir` (string) - Required - Directory for disk-backed KV cache. - `--kv-disk-space-mb` (integer) - Required - Maximum disk space for KV cache in MB. ### Notes - The server keeps one mutable backend/KV checkpoint in memory, allowing stateless clients to reuse shared prefixes. - Inference is serialized through one graph worker; concurrent requests wait their turn. ``` -------------------------------- ### Start server with disk KV cache Source: https://github.com/antirez/ds4/blob/main/QA_BEFORE_RELEASES.md Start the server with a 100K context and disk KV cache directory. Use this command to test disk KV cache behavior, including cache hits, eviction, and checkpoint rejection. ```bash ./ds4-server --ctx 100000 --kv-disk-dir /tmp/ds4-kv --kv-disk-space-mb 8192 ``` -------------------------------- ### Server - Start server Source: https://github.com/antirez/ds4/blob/main/gguf-tools/imatrix/dataset/rendered_prompts.txt Starts the ds4-server with configurable context length and disk-backed KV cache. ```APIDOC ## Server - Start server ### Description Starts the ds4-server with configurable context length and disk-backed KV cache. ### Usage ```sh ./ds4-server --ctx --kv-disk-dir --kv-disk-space-mb ``` ### Parameters - `--ctx` (integer) - Required - Context length in tokens. - `--kv-disk-dir` (string) - Required - Directory for disk-backed KV cache. - `--kv-disk-space-mb` (integer) - Required - Maximum disk space for KV cache in megabytes. ### Example ```sh ./ds4-server --ctx 100000 --kv-disk-dir /tmp/ds4-kv --kv-disk-space-mb 8192 ``` ### Behavior - Keeps one mutable backend/KV checkpoint in memory. - Stateless clients can resend a longer version of the same prompt to reuse the shared prefix. - Inference is serialized through one graph worker; concurrent requests wait their turn. ``` -------------------------------- ### trace_begin: start trace section Source: https://github.com/antirez/ds4/blob/main/gguf-tools/imatrix/dataset/rendered_prompts_nothink.txt Returns 0 immediately if the trace file is not set. This function is a stub that currently does nothing else; the actual trace start logic is not shown. ```c static uint64_t trace_begin( server *s, const job *j, int cached, int effective_prompt_tokens, const trace_cache_diag *cache_diag, const char *cache_source, int disk_cached, const char *disk_path) { if (!s->trace) return 0; ``` -------------------------------- ### Prefill start with live continuation and cold-store logic Source: https://github.com/antirez/ds4/blob/main/gguf-tools/imatrix/dataset/rendered_prompts_think.txt This block runs at the start of prefill. It logs live continuation matches, sets up progress reporting, and decides whether to store a cold checkpoint based on cache state and token thresholds. ```c } else if (thinking_live_continuation) { server_log(DS4_LOG_PREFILL, "ds4-server: thinking live continuation match=visible-prefix cached=%d prompt=%d", cached, prompt_tokens); } if (responses_visible_replay_without_reasoning) { /* The request replays a prior tool-call turn but omits the hidden * reasoning that originally led to it. A live Responses checkpoint, or * a responses-visible disk checkpoint, would preserve that hidden KV. * If neither is available, continue from the visible transcript instead * of surfacing a hard error to the user. This is lower fidelity, but it * lets old / restarted agent sessions recover and is exactly what the * client asked us to prefill. */ server_log(DS4_LOG_WARNING, "ds4-server: responses replay RESPPROTO missing reasoning state; continuing from visible history source=%s cached=%d prompt=%d", cache_source, cached, prompt_tokens); trace_event(s, trace_id, "responses replay missing reasoning state; continuing from visible history source=%s cached=%d", cache_source, cached); } server_log(DS4_LOG_PREFILL, "ds4-server: %s ctx=%s%s%s prompt start", j->req.kind == REQ_CHAT ? "chat" : "completion", ctx_span, req_flags[0] ? " " : "", req_flags); ds4_session_set_progress(s->session, server_progress_cb, &progress); int cold_store_len = 0; if (cached == 0 && s->kv.enabled && prompt_for_sync->len >= s->kv.opt.min_tokens && s->kv.opt.cold_max_tokens > 0 && prompt_for_sync->len <= s->kv.opt.cold_max_tokens) { const int anchor = kv_cache_chat_anchor_pos(&s->kv, prompt_for_sync, ds4_token_user(s->engine), ds4_token_assistant(s->engine)); cold_store_len = anchor >= s->kv.opt.min_tokens ? anchor : kv_cache_store_len(&s->kv, prompt_for_sync->len); } int suppressed_continued_last = -1; if (cold_store_len >= s->kv.opt.min_tokens) { /* A cold checkpoint can land exactly on the continued-checkpoint * frontier. The prefill progress callback would then write the same * prefix as "continued" while we are intentionally stopping there to ``` -------------------------------- ### Start ds4 server with context and disk cache Source: https://github.com/antirez/ds4/blob/main/docs/CLIENTS.md Starts the ds4 server with a 100k context window and disk-backed key-value storage. The client's context limit must not exceed the server's; output tokens also consume context. ```sh ./ds4-server --ctx 100000 --kv-disk-dir /tmp/ds4-kv --kv-disk-space-mb 8192 ``` -------------------------------- ### POSIX threads shared counter example (truncated) Source: https://github.com/antirez/ds4/blob/main/gguf-tools/quality-testing/data/pro-0813/continuations/case_063.txt The code block is truncated at the include directive, so the full example is not visible. It appears to be the start of a POSIX threads example where two threads increment a shared counter without synchronization. ```c #include < ``` -------------------------------- ### build_prompt and run_sampled_generation session setup Source: https://github.com/antirez/ds4/blob/main/gguf-tools/imatrix/dataset/rendered_prompts_nothink.txt Builds the prompt by either tokenizing a rendered chat prompt or encoding a chat prompt. Sets up a session, progress callback, and performs synchronous prefill. Measures prefill time. ```c static void build_prompt(ds4_engine *engine, const cli_generation_options *gen, ds4_tokens *out) { if (is_rendered_chat_prompt(gen->prompt)) { ds4_tokenize_rendered_chat(engine, gen->prompt, out); } else { ds4_encode_chat_prompt(engine, gen->system, gen->prompt, cli_effective_think_mode(gen), out); } } static int run_sampled_generation(ds4_engine *engine, const cli_config *cfg, const ds4_tokens *prompt) { ds4_session *session = NULL; if (ds4_session_create(&session, engine, cfg->gen.ctx_size) != 0) { fprintf(stderr, "ds4: sampled CLI generation requires a session backend\n"); return 1; } char err[160]; ds4_think_mode think_mode = cli_effective_think_mode(&cfg->gen); token_printer printer = { .engine = engine, .fp = stdout, .format_thinking = ds4_think_mode_enabled(think_mode), .in_think = ds4_think_mode_enabled(think_mode), .use_color = isatty(fileno(stdout)) != 0, .last_output_newline = true, }; cli_prefill_progress progress = { .base_tokens = 0, .input_tokens = prompt->len, .use_color = ds4_log_is_tty(stderr), }; const double t_prefill0 = cli_now_sec(); ds4_session_set_progress(session, cli_prefill_progress_cb, &progress); if (ds4_session_sync(session, prompt, err, sizeof(err)) != 0) { ds4_session_set_progress(session, NULL, NULL); fprintf(stderr, "ds4: prompt processing failed: %s\n", err); ds4_session_free(session); return 1; } ds4_session_set_progress(session, NULL, NULL); const double t_prefill1 = cli_now_sec(); ``` -------------------------------- ### Setup: Build tool schema and render chat prompt for testing Source: https://github.com/antirez/ds4/blob/main/gguf-tools/imatrix/dataset/rendered_prompts_nothink.txt This excerpt sets up a tool schema for a bash command and creates a user message to test prompt rendering. It initializes a chat message list, pushes a user message, and calls render_chat_prompt_text with the tool schemas and high thinking mode. ```c static void test_tool_checkpoint_suffix_is_future_prompt_canonical(void) { tool_schema_orders orders = make_bash_order(); const char *tool_schemas = "{\"name\":\"bash\",\"parameters\":{\"type\":\"object\",\"properties\":{" "\"command\":{},\"description\":{},\"timeout\":{}}}}"; chat_msgs prefix_msgs = {0}; chat_msg user = {0}; user.role = xstrdup("user"); user.content = xstrdup("inspect"); chat_msgs_push(&prefix_msgs, user); char *prompt_text = render_chat_prompt_text(&prefix_msgs, tool_schemas, &orders, DS4_THINK_HIGH); ``` -------------------------------- ### ds4_gpu_encode_router_select function signature and buffer setup Source: https://github.com/antirez/ds4/blob/main/gguf-tools/imatrix/dataset/rendered_prompts_think.txt Starts the ds4_gpu_encode_router_select function, declaring its parameters and retrieving Metal buffers and offsets for selected, weights, and probs tensors. The excerpt ends mid-function before any encoder is created or dispatched, so the remainder of the kernel setup is not shown. ```objective-c static int ds4_gpu_encode_router_select( id cb, ds4_gpu_tensor *selected, ds4_gpu_tensor *weights, ds4_gpu_tensor *probs, id logitsbuf, NSUInteger logits_off, id biasbuf, NSUInteger bias_off, id hashbuf, NSUInteger hash_off, id tokensbuf, NSUInteger tokens_off, const int32_t *single_token, uint32_t hash_rows, uint32_t n_tokens, bool has_bias, bool hash_mode) { id selectedbuf = ds4_gpu_tensor_buffer(selected); id weightsbuf = ds4_gpu_tensor_buffer(weights); id probsbuf = ds4_gpu_tensor_buffer(probs); const NSUInteger selected_off = ds4_gpu_tensor_offset(selected); const NSUInteger weights_off = ds4_gpu_tensor_offset(weights); const NSUInteger probs_off = ds4_gpu_tensor_offset(probs); ``` -------------------------------- ### ds4_flash_attn KV buffer offset calculation Source: https://github.com/antirez/ds4/blob/main/gguf-tools/imatrix/dataset/rendered_prompts.txt Computes the offset for the key/value buffer, handling ring buffer start offset. Part of the flash attention buffer setup. ```c id kvbuf = rawbuf; NSUInteger kvoff = ds4_gpu_tensor_offset(raw_kv); if (raw_start != 0) { const NSUInteger ring_bytes = (NSUInteger)n_raw * row_bytes; ``` -------------------------------- ### Flash attention pipeline setup and ring buffer copy (ds4_metal.m) Source: https://github.com/antirez/ds4/blob/main/gguf-tools/imatrix/dataset/rendered_prompts_think.txt Sets up the flash attention scratch buffers and pipelines, then copies raw KV data into a ring buffer when raw_start is non-zero. Handles tail and head row copies with wrap-around logic. Returns 0 on failure. ```c "ds4_flash_attn_pad") || !ds4_gpu_ensure_scratch_buffer(&g_flash_attn_tmp_buffer, &g_flash_attn_tmp_bytes, tmp_bytes, "ds4_flash_attn_tmp")) { return 0; } id pad_pipeline = nil; if ((n_keys % ncpsg) != 0) { pad_pipeline = ds4_gpu_get_flash_attn_pad_pipeline(true, (int32_t)ncpsg); if (!pad_pipeline) return 0; } id vec_pipeline = ds4_gpu_get_flash_attn_vec_pipeline("kernel_flash_attn_ext_vec_f16_dk512_dv512", true, true, false, false, (n_keys % ncpsg) != 0, (int32_t)head_dim, (int32_t)head_dim, (int32_t)nsg, (int32_t)nwg); id reduce_pipeline = ds4_gpu_get_flash_attn_reduce_pipeline((int32_t)head_dim, (int32_t)nwg); if (!vec_pipeline || !reduce_pipeline) return 0; id raw_linear_buf = rawbuf; NSUInteger raw_linear_offset = ds4_gpu_tensor_offset(raw_kv); if (raw_start != 0) { const NSUInteger ring_bytes = (NSUInteger)n_raw * row_bytes; const uint32_t tail_rows = raw_cap - raw_start < n_raw ? raw_cap - raw_start : n_raw; const uint32_t head_rows = n_raw - tail_rows; if (!ds4_gpu_ensure_scratch_buffer(&g_flash_attn_ring_buffer, &g_flash_attn_ring_bytes, ring_bytes, "ds4_flash_attn_ring")) { return 0; } if ((tail_rows && !ds4_gpu_encode_cpy_f32_f32_1d(cb, rawbuf, ds4_gpu_tensor_offset(raw_kv) + (NSUInteger)raw_start * row_bytes, g_flash_attn_ring_buffer, 0, tail_rows * head_dim)) || (head_rows && !ds4_gpu_encode_cpy_f32_f32_1d(cb, rawbuf, ds4_gpu_tensor_offset(raw_kv), g_flash_attn_ring_buffer, ``` -------------------------------- ### Main entry point with tokenization dump and execution dispatch Source: https://github.com/antirez/ds4/blob/main/gguf-tools/imatrix/dataset/rendered_prompts_nothink.txt Parses CLI options, handles --dump-tokens mode, initializes the engine, and dispatches to REPL, generation, or imatrix collection. Returns exit codes 1 for engine open failure and 2 for invalid arguments. ```c int main(int argc, char **argv) { cli_config cfg = parse_options(argc, argv); if (cfg.gen.dump_tokens) { if (cfg.gen.prompt == NULL) { fprintf(stderr, "ds4: --dump-tokens requires -p or --prompt-file\n"); free(cfg.prompt_owned); return 2; } int rc = ds4_dump_text_tokenization(cfg.engine.model_path, cfg.gen.prompt, stdout); free(cfg.prompt_owned); return rc; } if (!cfg.inspect) { log_context_memory(cfg.engine.backend, cfg.gen.ctx_size); cli_warn_think_max_downgraded(&cfg.gen, "--think-max"); } ds4_engine *engine = NULL; if (ds4_engine_open(&engine, &cfg.engine) != 0) { free(cfg.prompt_owned); return 1; } int rc = 0; if (cfg.inspect) { ds4_engine_summary(engine); } else if (cfg.gen.imatrix_output_path) { rc = ds4_engine_collect_imatrix(engine, cfg.gen.imatrix_dataset_path, cfg.gen.imatrix_output_path, cfg.gen.ctx_size, cfg.gen.imatrix_max_prompts, cfg.gen.imatrix_max_tokens); } else if (cfg.gen.prompt == NULL) { rc = run_repl(engine, &cfg); } else { rc = run_generation(engine, &cfg); } ds4_engine_close(engine); free(cfg.prompt_owned); return rc; } ``` -------------------------------- ### Install ROCm development packages on Ubuntu Source: https://github.com/antirez/ds4/blob/main/docs/STRIX_HALO.md Installs HIP, hipBLAS, hipBLASLt, rocBLAS, rocWMMA, and hipCUB development files for a native Ubuntu build. Adds the user to the render and video groups; log out and back in after changing groups. rocminfo must report gfx1151 and be able to open /dev/kfd before DwarfStar can run. ```sh sudo apt-get update sudo apt-get install -y hipcc rocminfo rocm-smi \ libamdhip64-dev libhipblas-dev libhipblaslt-dev librocblas-dev \ librocwmma-dev libhipcub-dev sudo usermod -aG render,video "$USER" ``` -------------------------------- ### Stream setup and SSE header sending in ds4_server.c Source: https://github.com/antirez/ds4/blob/main/gguf-tools/imatrix/dataset/rendered_prompts.txt Initializes stream state variables and sends SSE headers for streaming requests. Handles API-specific stream starts for Anthropic and OpenAI, with error logging and cleanup on failure. ```c bool structured_stream = request_uses_structured_stream(&j->req); anthropic_stream anthropic_live = {0}; openai_stream openai_live = {0}; responses_stream responses_live = {0}; const bool openai_live_chat = request_uses_openai_live_stream(&j->req); const bool responses_live_chat = request_uses_responses_live_stream(&j->req); long responses_created_at = (long)time(NULL); if (j->req.stream) { if (!sse_headers(j->fd, s->enable_cors)) { server_log(DS4_LOG_GENERATION, "ds4-server: %s ctx=%s%s%s sse headers failed", j->req.kind == REQ_CHAT ? "chat" : "completion", ctx_span, req_flags[0] ? " " : "", req_flags); ds4_tokens_free(&effective_prompt); return; } if (j->req.api == API_ANTHROPIC && !anthropic_sse_start_live(j->fd, &j->req, id, prompt_tokens, &anthropic_live)) { server_log(DS4_LOG_GENERATION, "ds4-server: chat ctx=%s anthropic stream start failed", ctx_span); ds4_tokens_free(&effective_prompt); return; } if (j->req.api == API_OPENAI && j->req.kind == REQ_CHAT && !sse_chunk(j->fd, &j->req, id, NULL, NULL)) { server_log(DS4_LOG_GENERATION, "ds4-server: chat ctx=%s openai role chunk failed", ctx_span); ds4_tokens_free(&effective_prompt); } } } ``` -------------------------------- ### Initialize server state and start accept loop Source: https://github.com/antirez/ds4/blob/main/gguf-tools/imatrix/dataset/rendered_prompts.txt Initializes synchronization primitives, optionally opens a trace file, starts a worker thread, and runs the main accept loop. Handles listen failure by stopping the worker and returning 1. Accepts client connections, configures sockets, and spawns detached threads for each client. ```c fg.kv_disk_space_mb, cfg.kv_cache_reject_different_quant, cfg.kv_cache); } if (s.disable_exact_dsml_tool_replay) { server_log(DS4_LOG_DEFAULT, "ds4-server: exact DSML tool replay disabled; tool history uses canonical JSON rendering"); } pthread_mutex_init(&s.mu, NULL); pthread_cond_init(&s.cv, NULL); pthread_cond_init(&s.clients_cv, NULL); pthread_mutex_init(&s.tool_mu, NULL); pthread_mutex_init(&s.trace_mu, NULL); if (cfg.trace_path) { s.trace = fopen(cfg.trace_path, "w"); if (!s.trace) { server_log(DS4_LOG_DEFAULT, "ds4-server: failed to open trace file %s: %s", cfg.trace_path, strerror(errno)); server_close_resources(&s); return 1; } setvbuf(s.trace, NULL, _IONBF, 0); server_log(DS4_LOG_DEFAULT, "ds4-server: tracing session to %s", cfg.trace_path); } pthread_t worker; if (pthread_create(&worker, NULL, worker_main, &s) != 0) die("failed to start worker"); int lfd = listen_on(cfg.host, cfg.port); if (lfd < 0) { server_log(DS4_LOG_DEFAULT, "ds4-server: failed to listen on %s:%d: %s", cfg.host, cfg.port, strerror(errno)); pthread_mutex_lock(&s.mu); s.stopping = true; pthread_cond_broadcast(&s.cv); pthread_mutex_unlock(&s.mu); pthread_join(worker, NULL); server_close_resources(&s); return 1; } g_listen_fd = lfd; server_log(DS4_LOG_DEFAULT, "ds4-server: listening on http://%s:%d", cfg.host, cfg.port); while (!g_stop_requested) { int fd = accept(lfd, NULL, NULL); if (fd < 0) { if (g_stop_requested) break; if (errno == EINTR) continue; server_log(DS4_LOG_DEFAULT, "ds4-server: accept failed: %s", strerror(errno)); continue; } if (g_stop_requested) { close(fd); break; } configure_client_socket(fd); client_arg *ca = xmalloc(sizeof(*ca)); ca->srv = &s; ca->fd = fd; pthread_mutex_lock(&s.mu); s.clients++; pthread_mutex_unlock(&s.mu); pthread_t th; if (pthread_create(&th, NULL, client_main, ca) != 0) { pthread_mutex_lock(&s.mu); s.clients--; pthread_cond_broadcast(&s.clients_cv); pthread_mutex_unlock(&s.mu); free(ca); close(fd); continue; } pthread_detach(th); } if (g_listen_fd >= 0) { ``` -------------------------------- ### GPU-visible memory kernel parameters Source: https://github.com/antirez/ds4/blob/main/docs/STRIX_HALO.md Kernel boot parameters used in the native reference setup to control GPU-visible memory. These are a system-specific starting point, not an allocation budget for DwarfStar. Preserve existing boot options and keep RAM available for the OS; do not disable the IOMMU merely to copy another host's configuration. ```text amdgpu.gttsize=126976 ttm.pages_limit=32505856 ttm.page_pool_size=32505856 ``` -------------------------------- ### Start coordinator and worker for Flash Q4 Source: https://github.com/antirez/ds4/blob/main/docs/DISTRIBUTED.md Run on two machines with ds4f-q4 downloaded. Replace the example address with your coordinator's reachable address. The coordinator listens on 10.99.0.2:9911 and the worker connects to it. ```sh # Machine A. ./ds4 --role coordinator --layers 0:19 --listen 10.99.0.2 9911 ``` ```sh # Machine B. ./ds4 --role worker --layers 20:output --coordinator 10.99.0.2 9911 ``` -------------------------------- ### C race condition thread example (incomplete code block) Source: https://github.com/antirez/ds4/blob/main/gguf-tools/quality-testing/data/flash/continuations/case_063.txt Starts a C program that would exhibit a race condition, beginning with standard include directives for stdio.h and possibly pthread.h. The code block is truncated in the source after the second include, so only the opening lines are provided. ```c #include #include < ``` -------------------------------- ### Parse command-line options and initialize server Source: https://github.com/antirez/ds4/blob/main/gguf-tools/imatrix/dataset/rendered_prompts_nothink.txt Parses options like --warm-weights, --metal, --cuda, --backend, --cpu, and --kv-cache-cold-max-tokens. Validates that cold_max_tokens is 0 or >= min_tokens, and defaults directional_steering_ffn to 1.0 if a steering file is set without an explicit scale. Sets up signal handlers for SIGINT/SIGTERM, opens the engine and session, initializes mutexes/condition variables, optionally opens a trace file, creates a worker thread, and listens on the configured host/port. On listen failure, it cleans up resources and returns 1. ```c attn = parse_float_arg(need_arg(&i, argc, argv, arg), arg, -100.0f, 100.0f); directional_steering_scale_set = true; } else if (!strcmp(arg, "--warm-weights")) { c.engine.warm_weights = true; } else if (!strcmp(arg, "--metal")) { c.engine.backend = DS4_BACKEND_METAL; } else if (!strcmp(arg, "--cuda")) { c.engine.backend = DS4_BACKEND_CUDA; } else if (!strcmp(arg, "--backend")) { c.engine.backend = parse_backend_arg(need_arg(&i, argc, argv, arg), arg); } else if (!strcmp(arg, "--cpu")) { c.engine.backend = DS4_BACKEND_CPU; } else { server_log(DS4_LOG_DEFAULT, "ds4-server: unknown option: %s", arg); usage(stderr); exit(2); } } if (c.kv_cache.cold_max_tokens > 0 && c.kv_cache.cold_max_tokens < c.kv_cache.min_tokens) { server_log(DS4_LOG_DEFAULT, "ds4-server: --kv-cache-cold-max-tokens must be 0 or >= --kv-cache-min-tokens"); exit(2); } if (c.engine.directional_steering_file && !directional_steering_scale_set) { c.engine.directional_steering_ffn = 1.0f; } return c; } #ifndef DS4_SERVER_TEST int main(int argc, char **argv) { signal(SIGPIPE, SIG_IGN); struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = stop_signal_handler; sigemptyset(&sa.sa_mask); sigaction(SIGINT, &sa, NULL); sigaction(SIGTERM, &sa, NULL); server_config cfg = parse_options(argc, argv); ds4_engine *engine = NULL; if (ds4_engine_open(&engine, &cfg.engine) != 0) return 1; log_context_memory(cfg.engine.backend, cfg.ctx_size); ds4_session *session = NULL; if (ds4_session_create(&session, engine, cfg.ctx_size) != 0) { server_log(DS4_LOG_DEFAULT, "ds4-server: failed to create %s session", ds4_backend_name(cfg.engine.backend)); ds4_engine_close(engine); return 1; } server s; memset(&s, 0, sizeof(s)); s.engine = engine; s.session = session; s.default_tokens = cfg.default_tokens; s.disable_exact_dsml_tool_replay = cfg.disable_exact_dsml_tool_replay; s.tool_mem.max_entries = cfg.tool_memory_max_ids; s.enable_cors = cfg.enable_cors; if (cfg.kv_disk_dir) { kv_cache_open(&s.kv, cfg.kv_disk_dir, cfg.kv_disk_space_mb, cfg.kv_cache_reject_different_quant, cfg.kv_cache); } if (s.disable_exact_dsml_tool_replay) { server_log(DS4_LOG_DEFAULT, "ds4-server: exact DSML tool replay disabled; tool history uses canonical JSON rendering"); } pthread_mutex_init(&s.mu, NULL); pthread_cond_init(&s.cv, NULL); pthread_cond_init(&s.clients_cv, NULL); pthread_mutex_init(&s.tool_mu, NULL); pthread_mutex_init(&s.trace_mu, NULL); if (cfg.trace_path) { s.trace = fopen(cfg.trace_path, "w"); if (!s.trace) { server_log(DS4_LOG_DEFAULT, "ds4-server: failed to open trace file %s: %s", cfg.trace_path, strerror(errno)); server_close_resources(&s); return 1; } setvbuf(s.trace, NULL, _IONBF, 0); server_log(DS4_LOG_DEFAULT, "ds4-server: tracing session to %s", cfg.trace_path); } pthread_t worker; if (pthread_create(&worker, NULL, worker_main, &s) != 0) die("failed to start worker"); int lfd = listen_on(cfg.host, cfg.port); if (lfd < 0) { server_log(DS4_LOG_DEFAULT, "ds4-server: failed to listen on %s:%d: %s", cfg.host, cfg.port, strerror(errno)); pthread_mutex_lock(&s.mu); s.stopping = true; pthread_cond_broadcast(&s.cv); pthread_mutex_unlock(&s.mu); pthread_join(worker, NULL); server_close_resources(&s); return 1; } g_listen_fd = lfd; server_log(DS4_LOG_DEFAULT, "ds4-server: listening on http://%s:%d", cfg.host, cfg.port); while (!g_stop_requested) { int fd = accept(lfd, NULL, NULL); if (fd < 0) { if (g_stop_requested) break; if (errno == EINTR) continue; server_log(DS4_LOG_DEFAULT, "ds4-server: accept failed: %s", strerror(errno)); continue; } if (g_stop_requested) { close(fd); break; } ``` -------------------------------- ### FlashAttention kernel comparison and reduction setup Source: https://github.com/antirez/ds4/blob/main/gguf-tools/imatrix/dataset/rendered_prompts_nothink.txt This snippet shows the tail of a FlashAttention kernel where the result is determined by comparing mask values, and the start of a reduction kernel that combines partial results. It includes the kernel's final block calculation and the constant declarations for the reduction kernel's specialization. ```metal if ((C > NW || Q > 1) && res == 0) { half mmin = MAXHALF; half mmax = -MAXHALF; FOR_UNROLL (short j = 0; j < Q; ++j) { FOR_UNROLL (short ii = 0; ii < C/NW; ++ii) { mmin = min(mmin, mask_src[ii*NW]); mmax = max(mmax, mask_src[ii*NW]); } mask_src += args.nb31/2; } mmin = simd_min(mmin); mmax = simd_max(mmax); if (mmax > -MAXHALF) { if (mmin == 0.0 && mmax == 0.0) { res = 2; } else { res = 1; } } } const int32_t nblk1 = ((args.ne01 + Q - 1)/Q); ``` ```metal dst1[rid*(2*NWG) + 2*iwg + 0] = ss[0]; dst1[rid*(2*NWG) + 2*iwg + 1] = ss[1]; } } } #undef NWG #undef NSG #undef NS10 #undef NS20 } ``` ```metal #define FA_TYPES \ half4, \ half4, \ half4, \ float, \ float, float4, \ float4 #define FA_TYPES_F32 \ half4, \ float4, \ float4, \ float, \ float, float4, \ float4 typedef decltype(kernel_flash_attn_ext_vec) flash_attn_ext_vec_t; // Host-visible decode FlashAttention variant for DS4's 512-wide F16 K/V rows. template [[host_name("kernel_flash_attn_ext_vec_f16_dk512_dv512")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; #undef FA_TYPES #undef FA_TYPES_F32 ``` ```metal constant int32_t FC_flash_attn_ext_vec_reduce_DV [[function_constant(FC_FLASH_ATTN_EXT_VEC_REDUCE + 0)]]; constant int32_t FC_flash_attn_ext_vec_reduce_NWG [[function_constant(FC_FLASH_ATTN_EXT_VEC_REDUCE + 1)]]; // Reduces split-K decode FlashAttention partials. It combines each workgroup's // output vector and softmax (sum,max) pair into the final attention result. kernel void kernel_flash_attn_ext_vec_reduce( constant ds4_metal_args_flash_attn_ext_vec_reduce & args, device const char * htmp, device char * dst, uint tgpig[[threadgroup_position_in_grid]], ushort tiisg[[thread_index_in_simdgroup]], ushort sgitg[[simdgroup_index_in_threadgroup]]) { #define NWG (FC_flash_attn_ext_vec_reduce_NWG) #define DV (FC_flash_attn_ext_vec_reduce_DV) const uint64_t rid = tgpig; const short iwg = tiisg; device const float * ss = (device const float *) htmp + (uint64_t)args.nrows*DV*NWG; float S = ss[rid*(2*NWG) + 2*iwg + 0]; float M = ss[rid*(2*NWG) + 2*iwg + 1]; const float m = simd_max(M); const float ms = exp(M - m); S = simd_sum(S*ms); S = S == 0.0f ? 0.0f : 1.0f/S; const short DV4 = DV/4; device const float4 * htmp4 = (device const float4 *) htmp + rid*DV4*NWG; device float4 * dst4 = (device float4 *) dst + rid*DV4; for (short i = sgitg; i < DV4; i += NWG) { const float4 v = simd_sum(htmp4[i*NWG + iwg]*ms); if (iwg == 0) { dst4[i] = v*S; } } #undef NWG #undef DV } ``` -------------------------------- ### Funzione kv_cache_store_live_prefix_text in C Source: https://github.com/antirez/ds4/blob/main/gguf-tools/imatrix/dataset/rendered_prompts.txt Funzione che salva su disco il prefisso live dei token se le condizioni sono soddisfatte. Verifica che la cache sia abilitata, che i token siano sufficienti, che la quantizzazione sia a 2 o 4 bit, che il checkpoint live corrisponda esattamente al prefisso da salvare e che i payload non siano vuoti. In caso di mancata corrispondenza, registra un log e restituisce false. Il commento sottolinea che la persistenza deve osservare il grafo esattamente come รจ, e che i chiamanti devono precompilare il prefisso prima di chiamare questa funzione per evitare inferenze nascoste. ```c static bool kv_cache_store_live_prefix_text(server *s, const ds4_tokens *tokens, int store_len, const char *reason, const char *cache_text_override, uint8_t cache_text_ext, const char *cache_text_key) { kv_disk_cache *kc = &s->kv; if (!kc->enabled) return false; if (!tokens || store_len < kc->opt.min_tokens) return false; const int original_len = tokens->len; ds4_tokens store_tokens = {0}; tokens_copy_prefix(&store_tokens, tokens, store_len); const int quant_bits = ds4_engine_routed_quant_bits(s->engine); if (quant_bits != 2 && quant_bits != 4) { ds4_tokens_free(&store_tokens); return false; } char err[160] = {0}; /* Disk cache persistence must observe the graph exactly as-is. If callers * want a shorter prefix, they first prefill to that prefix and only then call * this function. This keeps cache population from doing hidden inference. */ const ds4_tokens *live_tokens = ds4_session_tokens(s->session); if (!live_tokens || live_tokens->len != store_tokens.len || !ds4_tokens_starts_with(live_tokens, &store_tokens)) { server_log(DS4_LOG_KVCACHE, "ds4-server: kv cache skipped tokens=%d reason=%s because live checkpoint is at %d", store_tokens.len, reason, live_tokens ? live_tokens->len : -1); ds4_tokens_free(&store_tokens); return false; } uint64_t payload_bytes = ds4_session_payload_bytes(s->session); if (payload_bytes == 0) { ds4_tokens_free(&store_tokens); return false; } size_t text_len = 0; char *text = NULL; const bool text_override = cache_text_override && cache_text_override[0]; if (text_override) { text = xstrdup(cache_text_override); text_len = strlen(text); } else { text = render_tokens_text(s->engine, &store_tokens, &text_len); } if (text_len > UINT32_MAX) { server_log(DS4_LOG_KVCACHE, "ds4-server: kv cache skipped tokens=%d because rendered text is too large", store_tokens.len); free(text); ds4_tokens_free(&store_tokens); return false; } uint64_t tool_map_est_bytes = 0; if (!kv_tool_map_serialized_size(s, text, &tool_map_est_bytes)) { server_log(DS4_LOG_KVCACHE, ``` -------------------------------- ### DS4 Metal kernel_mul_mv_q8_0_f32_impl kernel signature and setup Source: https://github.com/antirez/ds4/blob/main/gguf-tools/imatrix/dataset/rendered_prompts.txt Starts the kernel_mul_mv_q8_0_f32_impl function for 8-bit quantized matrix-vector multiplication. It declares the NSG constant, NW and NQ compile-time constants, computes the number of blocks (nb), derives row/column indices from the threadgroup position, and begins loading the quantized weight blocks (ax) and the float vector (y) into registers. ```metal template void kernel_mul_mv_q8_0_f32_impl( args_t args, device const char * src0, device const char * src1, device char * dst, threadgroup char * shmem, uint3 tgpig, ushort tiisg, ushort sgitg) { const short NSG = FC_mul_mv_nsg; constexpr short NW = N_SIMDWIDTH; constexpr short NQ = 8; const int nb = args.ne00/QK8_0; const int r0 = tgpig.x*NR0; const int r1 = tgpig.y; const int im = tgpig.z; const uint i12 = im%args.ne12; const uint i13 = im/args.ne12; const uint64_t offset1 = r1*args.nb11 + (i12)*args.nb12 + (i13)*args.nb13; device const float * y = (device const float *) (src1 + offset1); device const block_q8_0 * ax[NR0]; FOR_UNQUOTED (short row = 0; row < NR0; ++row) { const uint64_t offset0 = (r0 + row)*args.nb01 + (i12/args.r2)*args.nb02 + (i13/args.r3)*args.nb03; ax[row] = (device const block_q8_0 *) ((device char *) src0 + offset0); } float sumf[NR0] = { 0.f }; const short ix = tiisg/(NW/NQ); const short il = tiisg%(NW/NQ); const int ib0 = sgitg*NQ + ix; float yl[NQ]; ``` -------------------------------- ### Install Apple command-line developer tools Source: https://github.com/antirez/ds4/blob/main/docs/METAL.md Installs the necessary command-line tools for building on macOS. ```sh xcode-select --install ``` -------------------------------- ### trace_begin: Write rendered prompt and generated text header Source: https://github.com/antirez/ds4/blob/main/gguf-tools/imatrix/dataset/rendered_prompts_nothink.txt Continues trace_begin by writing the rendered prompt if present, then writes a header for generated text and flushes the trace file. Unlocks the mutex and returns the trace ID. ```c if (j->req.prompt_text) { fputs("\n--- rendered prompt ---\n", s->trace); fputs(j->req.prompt_text, s->trace); if (!j->req.prompt_text[0] || j->req.prompt_text[strlen(j->req.prompt_text) - 1] != '\n') { fputc('\n', s->trace); } } fputs("\n--- generated text ---\n", s->trace); fflush(s->trace); pthread_mutex_unlock(&s->trace_mu); return id; } ``` -------------------------------- ### JSON checkpoint header example Source: https://github.com/antirez/ds4/blob/main/gguf-tools/quality-testing/data/pro-0813/continuations/case_024.txt A JSON example for a model checkpoint header. The page recommends this format for safe storage, citing JSON with schema validation. ```json { ```