# Score a GGUF model on a CPU

> **About this page**
>
> - Kind: Example
> - Summary: Serves a quantized GGUF model with llama.cpp on a CPU, has parallel client tasks answer GSM8K math questions through it, and reports accuracy and speed.
> - Last changed: 2026-12-03
> - Page: https://docs.swale.io/examples/score-gguf
> - CLI reference for its commands: [`swale workflow create`](https://docs.swale.io/reference/cli-reference.md#workflow-create), [`swale workflow run start`](https://docs.swale.io/reference/cli-reference.md#workflow-run-start)
> - Index of these docs: https://docs.swale.io/llms.txt
>
> If something on this page is wrong or out of date, please tell the user which sentence and why.
>
> The steps on this page cost money or cannot be undone. Please check with the user before running them.

Source on GitHub: the [`workflows/score-gguf`](https://github.com/swaleio/examples/tree/main/workflows/score-gguf) folder, with its [README](https://github.com/swaleio/examples/blob/main/workflows/score-gguf/README.md) and its [workflow file](https://github.com/swaleio/examples/blob/main/workflows/score-gguf/workflow.yaml).

Measures how well a quantized model answers, and how fast, in the exact GGUF
file you would ship. llama.cpp serves the model on a CPU compute type, several
client tasks answer GSM8K math questions through that one server at the same
time, and the last step checks each answer against the reference and reports
the accuracy and the tokens per second.

| Step | Task definition | Compute |
|------|-----------------|---------|
| Fetch the GGUF file | [`swaleio/hf-download`](https://hub.swale.io/swaleio/hf-download) | `cpu-4` |
| Split the questions into shards | [`swaleio/duckdb`](https://hub.swale.io/swaleio/duckdb) | `cpu-4` |
| Serve the model, as a runner | [`swaleio/llamacpp-server`](https://hub.swale.io/swaleio/llamacpp-server) | `cpu-16` |
| Wait for the server, checking every 5 seconds | [`swaleio/http-request`](https://hub.swale.io/swaleio/http-request) | `cpu-4` |
| Answer each shard, one client task per shard, all at once | [`swaleio/python-3-13`](https://hub.swale.io/swaleio/python-3-13) | `cpu-4` each |
| Check the answers and report accuracy and speed | [`swaleio/duckdb`](https://hub.swale.io/swaleio/duckdb) | `cpu-4` |

The Compute column gives each step's [compute type](https://docs.swale.io/explanation/core-concepts.md#compute-types), the compute its tasks are allocated.

Every step is its own task. The server answers 4 requests at once, so the
default 4 shards keep it busy; when they are done, the platform stops it. Each
client is a short Python script inside the workflow that uses only the standard
library. The server needs no GPU; give it `a100-1` instead and llama.cpp
offloads the model to the GPU.

The model is asked to reason step by step and put its final answer within
`\boxed{}`, the form Qwen's models are trained to answer math in. The score
takes the number in its last `\boxed{}`, or the last number in its reply when
it has none, and the report also says how often it boxed its answer.

## Inputs

| Input | Default | Description |
|-------|---------|-------------|
| `repo` | `Qwen/Qwen2.5-1.5B-Instruct-GGUF` | Hugging Face repo holding the GGUF file. |
| `file` | `qwen2.5-1.5b-instruct-q4_k_m.gguf` | The file to score. |
| `questions` | `200` | Questions from GSM8K's test split to answer. |
| `shards` | `["0", "1", "2", "3"]` | One client task per element. |

The download reads the secret `hf_token`.

## Output

`scored.parquet` on the workspace, with each question, the reference answer,
the model's reply, the number taken from it and whether it is correct, and the
summary in the last task's log.

## Run it

You need the CLI, logged in to your account, and a project to add the workflow to; [Getting started](https://docs.swale.io/getting-started.md) sets them up.

1. Save the file under [The workflow file](#the-workflow-file) as `workflow.yaml`, and add it to a project:

   ```bash
   swale workflow create --project-name my-project --file workflow.yaml
   ```

   The command prints `Workflow created:` followed by the workflow's ID.

2. The workflow reads the secret `hf_token`. Create it as a project secret, or as an account secret that allows the project, as [Use secrets in workflows](https://docs.swale.io/how-to-guides/use-secrets-in-workflows.md) shows.

3. Start a run with the workflow's ID:

   ```bash
   swale workflow run start --project-name my-project --workflow-id <workflow-id>
   ```

   Each input you leave out takes its default from [Inputs](#inputs), and `--input <name>=<value>` gives it another value.

[Create and manage workflows](https://docs.swale.io/how-to-guides/create-and-manage-workflows.md) covers the other ways to add a workflow, [Start and manage workflow runs](https://docs.swale.io/how-to-guides/start-and-manage-workflow-runs.md) how to follow a run, and [View and stream task logs](https://docs.swale.io/how-to-guides/view-and-stream-task-logs.md) how to read its tasks' logs.

## The workflow file

[Workflow definition syntax](https://docs.swale.io/reference/workflow-definition-syntax.md) describes each key in it.

```yaml title="workflow.yaml"
name: Score a GGUF model on a CPU
description: Serves a quantized GGUF model with llama.cpp on a CPU, has parallel client tasks answer GSM8K math questions through it, and reports accuracy and speed.
compute_type: cpu-4

inputs:
  repo:
    description: Hugging Face repo id holding the GGUF file.
    default: Qwen/Qwen2.5-1.5B-Instruct-GGUF
  file:
    description: The GGUF file to score.
    default: qwen2.5-1.5b-instruct-q4_k_m.gguf
  questions:
    description: Number of questions from GSM8K's test split to answer.
    default: "200"
  shards:
    description: The client shards, as a JSON array; one client task runs per element and answers every nth question. The server answers 4 requests at once, so more than 4 shards only queue.
    default: '["0", "1", "2", "3"]'

entry_point: main

blocks:
  main:
    tasks:
      fetch:
        name: Fetch the GGUF file
        uses: swaleio/hf-download
        args:
          repo: ${{inputs.repo}}
          include: ${{inputs.file}}
          dest: ${{env.WORKFLOW_STORAGE}}/gguf
          token: ${{secrets.hf_token}}

      split:
        name: Split the questions into shards
        uses: swaleio/duckdb
        args:
          sql: |
            -- The reference answer is the number after #### in GSM8K's worked answers.
            CREATE TABLE questions AS
              SELECT row_number() OVER () - 1 AS id, question,
                     replace(trim(split_part(answer, '####', 2)), ',', '') AS reference
              FROM 'hf://datasets/openai/gsm8k/main/test-*.parquet'
              LIMIT ${{inputs.questions}};
            CREATE TABLE sharded AS
              SELECT id, question, id % json_array_length($$${{inputs.shards}}$$) AS shard FROM questions;
            COPY sharded TO '${{env.WORKFLOW_STORAGE}}/shards' (FORMAT json, PARTITION_BY (shard), OVERWRITE_OR_IGNORE);
            COPY questions TO '${{env.WORKFLOW_STORAGE}}/questions.parquet' (FORMAT parquet);
            SELECT shard, count(*) AS questions FROM sharded GROUP BY shard ORDER BY shard;

      serve:
        name: Serve the model
        uses: swaleio/llamacpp-server
        compute_type: cpu-16
        start_on:
          - fetch
        terminate_on:
          - each_shard
        args:
          model: ${{env.WORKFLOW_STORAGE}}/gguf/${{inputs.file}}
          ctx_size: "8192"

      wait_ready:
        name: Wait for the server
        uses: swaleio/http-request
        start_on:
          - serve
        args:
          url: http://${{tasks.serve.ip-address}}:9931/health
          retry: "360"
          retry_delay: "5"
          expected_status: "200"

      each_shard:
        name: Answer each shard
        start_on:
          - wait_ready
          - split
        for_each:
          items: ${{inputs.shards}}
          block: answer_shard

      score:
        name: Score the answers
        uses: swaleio/duckdb
        start_on:
          - each_shard
        args:
          sql: |
            -- The model's answer is the number in its last \boxed{}, or else the last number
            -- in its reply.
            CREATE TABLE scored AS
              SELECT q.id, q.question, q.reference, a.reply, a.completion_tokens, a.started, a.finished,
                     regexp_extract_all(a.reply, '\\boxed\{([^}]*)\}', 1)[-1] AS boxed,
                     replace(coalesce(nullif(regexp_extract(boxed, '-?[0-9][0-9,]*(\.[0-9]+)?'), ''),
                                      regexp_extract_all(a.reply, '-?[0-9][0-9,]*(\.[0-9]+)?')[-1]), ',', '') AS predicted,
                     coalesce(TRY_CAST(predicted AS DOUBLE) = TRY_CAST(q.reference AS DOUBLE), false) AS correct
              FROM '${{env.WORKFLOW_STORAGE}}/questions.parquet' q
              JOIN read_json('${{env.WORKFLOW_STORAGE}}/answers/*.jsonl') a USING (id)
              ORDER BY q.id;
            COPY scored TO '${{env.WORKFLOW_STORAGE}}/scored.parquet' (FORMAT parquet);
            SELECT count(*) AS questions,
                   round(100.0 * avg(correct::INT), 1) AS accuracy_percent,
                   round(100.0 * avg((boxed IS NOT NULL)::INT), 1) AS boxed_percent,
                   sum(completion_tokens) AS tokens,
                   round(max(finished) - min(started)) AS seconds,
                   round(sum(completion_tokens) / (max(finished) - min(started)), 1) AS tokens_per_second
              FROM scored;

  answer_shard:
    tasks:
      answer:
        name: Answer the shard
        uses: swaleio/python-3-13
        args:
          script: |
            import glob, json, os, time, urllib.request

            storage = os.environ["WORKFLOW_STORAGE"]
            shard = "${{tasks.each_shard.for_each.item}}"
            server = "http://${{tasks.serve.ip-address}}:9931/v1/chat/completions"
            os.makedirs(f"{storage}/answers", exist_ok=True)
            rows = []
            for path in glob.glob(f"{storage}/shards/shard={shard}/*.json"):
                with open(path) as f:
                    rows += [json.loads(line) for line in f if line.strip()]

            with open(f"{storage}/answers/{shard}.jsonl", "w") as out:
                for row in rows:
                    prompt = row["question"] + "\nPlease reason step by step, and put your final answer within \\boxed{}."
                    body = json.dumps({"messages": [{"role": "user", "content": prompt}],
                                       "max_tokens": 512, "temperature": 0}).encode()
                    request = urllib.request.Request(server, body, {"Content-Type": "application/json"})
                    started = time.time()
                    with urllib.request.urlopen(request, timeout=600) as response:
                        answer = json.load(response)
                    out.write(json.dumps({"id": row["id"],
                                          "reply": answer["choices"][0]["message"]["content"],
                                          "completion_tokens": answer["usage"]["completion_tokens"],
                                          "started": started, "finished": time.time()}) + "\n")
            print(f"shard {shard}: answered {len(rows)} questions")
```

## Licenses of the defaults

- Model: [Qwen/Qwen2.5-1.5B-Instruct-GGUF](https://huggingface.co/Qwen/Qwen2.5-1.5B-Instruct-GGUF), Apache-2.0.
- Dataset: [openai/gsm8k](https://huggingface.co/datasets/openai/gsm8k), MIT.
