跳至主要内容

Inkling 2 Mini Tutorial: Building an Autonomous Python Performance Optimizer

Learn how to run Inkling 2 Mini locally with Ollama and build an agent that profiles, rewrites, and verifies slow NumPy code on its own.
· 15分钟 阅读

使用 AI 探索

Inkling 2 Mini is a small open-weight model from Thinking Machines Lab. It is a looped Mixture of Experts (MOE) model with 26.4B total parameters, 3.4B active, and 5.4B weight activations per token and middle layers that run three times for every token. It is small enough to run on an Apple Silicon Mac with 32 GB of memory.

In this tutorial, we'll build a small agent that makes slow Python code fast without help. It profiles a NumPy pipeline, asks the model for one targeted fix, runs equivalence tests, benchmarks the result, and keeps the rewrite only if it is both correct and faster. 

By the end, you'll know how to:

  • Call Inkling 2 Mini through Ollama's /api/chat endpoint with thinking enabled.

  • Separate a reasoning model's thinking stream from its answer stream.

  • Build a profile, hypothesize, rewrite, and verify a loop with a correctness gate.

  • Measure prefill and decode speed, time to first token, and model memory.

You can find the complete code in the repository.

What Is Inkling 2 Mini?

Inkling 2 Mini is a multimodal model that accepts text and images, returns text, and supports a 1M-token context window.

It has two interesting design choices that set it apart from other small models:

Looped transformer 

The model has 24 layers, split into four blocks of six. The first and last blocks run once, while the two middle blocks run three times for every token. That gives 48-layer applications per token from 24 stored layers. The engineers reason that the middle layers carry the more abstract reasoning, so repeating them lets the model think more per token without storing more weights.

The Thinking Machines team also tested which layers are worth looping and found that the middle 12 layers gave larger accuracy gains than looping the last 12 on 27 of 28 evaluations. At training step 2,000, a model without looping was estimated to need 1.51x to 1.91x as much compute to match the middle-loop model's loss, against 1.24x to 1.36x for the last-loop model, with both looped runs using three passes and equal training compute.

Figure: Compute-equivalent gain by loop position (Source)

Mixture-of-Experts

Each layer routes a token to 8 of 128 experts. Most of the weights were trained and are deployed natively in NVFP4, with the last four layers in MXFP8. There is no separate quantization step after training, and the full model takes about 20 GB. This makes Inkling 2 Mini lead the open-weights models under 100B total parameters on benchmarks such as DeepSWE v1.1 (48.2%) and Vals Index v2.2 (46.5%).

However, the authors also point out two limitations that will matter in this tutorial:

  • The model can get stuck in long reasoning loops, especially when debugging code, so Thinking Machines recommends limits on output tokens and agent turns.
  • Setting the reasoning effort to its minimum does not fully disable reasoning.

For this tutorial, we’ll run the inkling-2-mini:26b-a5b-nvfp4 version via ollama. Here are some key parameters of the model:

Property

Value

Architecture

inkling2_loop

Parameters

26.4B

Quantization

nvfp4

Context length

1,048,576 tokens

Embedding length

2,304

Capabilities

completion, vision, tools, thinking

Thinking levels

false, true, none, minimal, low, medium, high (default), xhigh, max

Note that the default level is high, but it is not the top of the scale. xhigh and max sit above it. Passing think: true most likely gives you that default high.

How Does the Agent Loop Work?

The agent has no plan and no built-in knowledge of how to optimize NumPy. In each iteration, it does four things:

  1. Profile: Run cProfile over the current best version and extract the table, sorted by own time.

  2. Hypothesize and rewrite: Send the profile, the current code, and the history of earlier attempts to the model. Ask for one focused change and the completely rewritten file.

  3. Verify: Run equivalence tests against the original pipeline's output at four data sizes.

  4. Benchmark: If the tests pass, time the rewrite. Keep it only if it is at least 3% faster than the current best.

A rejected rewrite is not dropped silently. When the tests fail, the pytest output goes into the next prompt, so the model sees its own mistake.

Every model call is measured via prompt tokens, generated tokens, the split between thinking and answer, prompt-reading and generation speed, time to first token, and model load time.

Demo: A Self-Optimizing NumPy Pipeline

Before the code, let's separate the model settings from the task.

Setting

Value used

Why it matters

Temperature

0.2

Held fixed so sampling never changes while we compare thinking levels

think

false, low, true

The variable under test

num_predict

8,192, then 12,288

Caps thinking and answer

num_ctx

16,384

Prompt and generation must fit here

Minimum gain

3%

A rewrite must beat the current best by this much to be kept

Iterations

6

Five planted bottlenecks, and one to see what the model does next

Runs

3 at true, 1 each at low and false

Run-to-run variation instead of relying on one run

Note: These are working settings for this experiment, not tuned settings for Inkling 2 Mini. All measurements below come from an Apple M3 Pro (Apple Silicon) with 36 GB of unified memory, running Ollama 0.40.17, Python 3.13.1, and NumPy 2.5.5.

Step 1: Prerequisites

Inkling 2 Mini ships as a single checkpoint of about 20 GB in mixed NVFP4 and MXFP8 precision, so it fits on local hardware. Thinking Machines Lab supports one NVIDIA DGX Spark or an Apple silicon Mac with 32 GB or more of memory, and recommends 32 GB or more of VRAM on other GPUs. For inference, it works with Hugging Face, SGLang, vLLM, TokenSpeed, NVIDIA Dynamo, Unsloth, llama.cpp, and the Llama App, and on Apple silicon with Ollama and Exo Labs.

This tutorial uses Ollama on a Mac. You need an Apple Silicon Mac with at least 32 GB of memory, Ollama 0.40.17 or newer, and Python 3 with numpy, pytest, matplotlib, requests, and rich.

pip install numpy pytest matplotlib requests rich

NumPy runs the pipeline the agent optimizes, and pytest checks that each rewrite still returns the right answer. The requests library sends prompts to Ollama's local API, matplotlib draws the dashboard charts, and rich (optional) colors the streamed model output in the terminal.

Before moving forward, check your Ollama version first. The older versions can't pull this model. Run the following command:

ollama -v

Then pull the model by its explicit tag, so your results stay reproducible even if latest moves:

ollama pull inkling-2-mini:26b-a5b-nvfp4

This pulls the Inkling 2 Mini model’s MLX version. The tag has three parts: 

  • 26b is the total parameter count (26.4B)

  • a5b is the active parameters per token (5.4B effective)

  • nvfp4 is the weight format.

Step 2: The pipeline 

The target is a synthetic sales analytics pipeline with five deliberately slow functions. The idea is that the build_report() function must return the same keys, shapes, dtypes, and values as the original.

The slowest function compares every pair of transactions in a Python loop:

def repeat_purchase_pairs(customer, day):
    # Compares every pair of transactions: O(n^2) Python loop
    count = 0
    n = len(customer)
    for i in range(n):
        for j in range(i + 1, n):
            if customer[i] == customer[j] and abs(day[i] - day[j]) <= 7:
                count += 1
    return np.array([count])

The other four are slow in different ways:

  • customer_totals() grows arrays with np.append inside a loop.

  • zscores() recomputes the mean and standard deviation for every element.

  • rolling_mean() re-sums the whole window at each position.

  • daily_revenue() scans all rows once per day of the year.

With 8,000 rows, build_report() takes about 2.9 seconds.

Step 3: Build the profile, test, and benchmark tools

The agent has three tools: profile(), run_tests(), and benchmark(). Each one runs the candidate file in a separate process with a timeout, so a broken or very slow rewrite can't hang the loop.

def profile(path, top=12, timeout=120):
    """cProfile report of build_report(), top functions by own time."""
    code, out = _run([sys.executable, "-c", PROFILE_SCRIPT, str(path), str(top)], timeout)
    lines = [l for l in out.splitlines() if l.strip()]
    start = next((i for i, l in enumerate(lines) if "ncalls" in l), 0)
    return "\n".join(lines[max(0, start - 1):])

run_tests() points pytest at the candidate file through a PIPELINE_FILE environment variable and compares its output with cached output from the original. Then the benchmark() tool returns the median of three timings.

Here is a profile of the original pipeline, captured separately from the runs. Note that the agent doesn't save the profile it sees each iteration:

In the above table, ncalls is how many times a function ran, tottime is the time spent inside the function itself, and cumtime also counts the functions it calls. repeat_purchase_pairs runs once but takes about 2.6 s, and daily_revenue comes next at about 0.17 s. The last two lines show that the original pipeline passes its tests and takes a median of 2.90s, which also acts as the baseline every rewrite is compared against.

Step 4: Streaming model's thinking and answer from Ollama

Ollama streams thinking and answer in two separate fields, message.thinking and message.content. We record when the first token of each arrives:

def call_ollama(messages, model, host, think, max_tokens, live=True, num_ctx=16384):
    body = {
        "model": model, "messages": messages, "stream": True, "think": think,
        "options": {"temperature": 0.2, "num_ctx": num_ctx, "num_predict": max_tokens},
    }
    t0 = time.perf_counter()
    t_first_think = t_first_answer = None
    thinking, content = [], []
    with requests.post(f"{host}/api/chat", json=body, stream=True, timeout=3600) as r:
        for line in r.iter_lines(chunk_size=None):
            if not line:
                continue
            chunk = json.loads(line)
            msg = chunk.get("message", {})
            if msg.get("thinking"):
                if t_first_think is None:
                    t_first_think = time.perf_counter() - t0
                thinking.append(msg["thinking"])
            if msg.get("content"):
                if t_first_answer is None:
                    t_first_answer = time.perf_counter() - t0
                content.append(msg["content"])
            if chunk.get("done"):
                final = chunk

With the default setting (chunk_size=None), the requests lib collects the stream into larger blocks, so thinking and answering appear to arrive at the same moment.

However, the final chunk carries prompt_eval_count, prompt_eval_duration, eval_count, eval_duration, and load_duration. So, these give prompt-reading and generation speed directly. Each streamed chunk is usually one token, so counting thinking chunks and answer chunks splits eval_count into thinking and answer. Any tokens Ollama counted but never streamed show up as the difference:

unstreamed = max(0, gen_tok - (n_think + n_ans))
hidden_s = max(0.0, (ttft or 0.0) - pre_s - load_s)

This difference will turn out to be important in Step 11.

Step 5: The accept/reject gate

Each rewrite of the model returns is only a candidate. The agent keeps it only if it passes the equivalence tests and runs at least 3% faster than the current best version (the --min-gain default). Otherwise, it is rejected, and the reason is passed back to the model on the next turn:

if passed:
    runtime, row["bench_s"] = tl.run(it, "benchmark", tools.benchmark, cand)

if not passed:
    row.update(accepted=False, outcome=f"rejected: tests failed ({reason[:200]})")
    last_failure = test_out

elif runtime is None or runtime > best_s * (1 - args.min_gain):
    row.update(accepted=False, outcome=f"rejected: not faster ({runtime:.3f} s)")

else:
    shutil.copy(cand, best_path)
    row.update(accepted=True, outcome=f"accepted: {best_s:.3f} s -> {runtime:.3f} s")
    best_s = runtime

Correctness is checked before speed, so a faster but wrong rewrite never reaches the benchmark. Every candidate is written to its own file in the run folder, and the original pipeline is never touched. This matters particularly because the model card warns that the model may delete or overwrite files without asking when it acts as an agent.

Step 6: Run the agent

With the tools, the model call, and the gate in place, start the agent. The following command runs six iterations with the default settings, i.e., thinking ON, an 8,192-token cap per call (--max-tokens) and a 16,384-token context window (--num-ctx).

python agent.py --model inkling-2-mini:26b-a5b-nvfp4 --iters 6

While it runs, the terminal streams the model's thinking live, followed by its hypothesis and code. When it finishes, dashboard.py turns the run's log into the charts.

python dashboard.py --power power.log

Step 7: Results

Our best run (run 120936, think: true) accepted all six rewrites:

Iteration

Target

Runtime after

Thinking tokens

Answer tokens

Model time

0

Baseline

2.910 s

  •  
  •  

-

1

repeat_purchase_pairs

0.313 s

1,708

1,308

166 s

2

daily_revenue

0.142 s

468

1,250

87 s

3

zscores

0.044 s

905

1,203

107 s

4

rolling_mean

0.009 s

674

1,216

104 s

5

customer_totals

0.0016 s

1,212

1,218

132 s

6

repeat_purchase_pairs again

0.0007 s

6,589

1,245

463 s

Re-benchmarking the final file 15 times gave a speedup of 3,870x to 4,609x, so about 4,000x overall. At sub-millisecond runtimes, a single timing is too noisy to quote, so we use the range.

Runtime by agent iteration on a log scale, run 120936

Figure: Runtime by iteration on a log scale, run 120936

The model attacked the bottlenecks in order of cost. Each answer named the slow function, explained why it was slow, and described the fix before writing any code.

Thinking and answer tokens per iteration, run 120936

Figure: Thinking and answer tokens per iteration, run 120936.

The z-score iteration shows the model reading the profile carefully. Look back at the profile in Step 3. It is sorted by own time, where zscores sits eighth at 0.007s, below four NumPy internals. The cost is in the cumulative column 0.123s (third highest). The model's iteration 3 hypothesis in this run reads:

Note: zscores() is the bottleneck (0.133s cumulative) because it recomputes np.mean and np.std inside a Python loop over all 8000 elements

It ignored the sort order, read the cumulative column, and traced the scattered _mean and _std rows back to the function that calls them. Our tool presented the information poorly, and the model worked around it.

Step 8: Compare model time with tool time

The agent logs how long every phase of each iteration takes. The dashboard turns that log into the chart below, which splits each iteration into model time (loading, reading the prompt, thinking, and answering) and tool time (profiling, testing and benchmarking).

Time breakdown per iteration with thinking on, run 120936

Figure: Where each iteration's time went at the default thinking level, run 120936

Model calls took about 98% of the wall time in this run, and between 96.8% and 98.7% in every run. Profiling, testing, and benchmarking together never took more than 3.2%. If you build something like this, speeding up your tools is not where the gains are.

After the first call, the model read prompts at 184 to 191 tokens per second and generated at 17 to 23 tokens per second. The first call was slower (164 tokens per second) and also took 9.9 seconds to load the model.

Step 9: The token-budget failure

With all five planted bottlenecks fixed, every run went back to repeat_purchase_pairs for iteration 6. One run, with num_predict raised to 12,288, ended iteration 6 like this:

generated:   12288 of 12288 cap
thinking:    12218
answer:      70
done_reason: length
outcome:     rejected: no Python code block (hit max tokens)

The model spent almost the whole budget reasoning, wrote 70 tokens of answer, and was cut off before it opened a code block. 

This happened because num_predict is one budget for thinking and the answer together. Thinking and answering draw from the same pool, and a reasoning model can spend all of it thinking. The fix for this failure is a turn limit and a check on done_reason, not a bigger budget.

There is also a second ceiling to keep in mind. The num_ctx bounds the prompt and the generation together. Our largest prompt was 2,452 tokens, so a 16,384-token context leaves about 13,900 tokens to generate. If you raise num_predict well past that, raise num_ctx too. 

Step 10: Iteration 6 across every run

All five runs found the same five bottlenecks in the same order, including the run with thinking off. The first three fixes landed within 5% of each other in every run. The last two varied more, because the model wrote different implementations each time:

Iteration

Runtime range across 5 runs

Spread

1

0.310 to 0.315 s

1.4%

2

0.139 to 0.145 s

4.7%

3

0.043 to 0.044 s

2.6%

4

0.0083 to 0.0098 s

17.8%

5

0.0015 to 0.0030 s

102.5%

However, iteration 6 is the hardest step that needed a new algorithm for repeat_purchase_pairs, and this is where the runs split apart:

Run

think

Iteration 6 thinking tokens

Outcome

131033

low

673

Tests failed

130150

false

0 shown (see Step 11)

Tests failed

113051

true

1,773

Tests failed

120936

true

6,589

Accepted

123904

true

12,218

Hit the cap, no code

Four of five runs produced unusable output on iteration 6, and the test gate caught all four. The correct pair count is 4,391. The three rewrites that failed the tests returned counts that were far off, and two of them were negative, which is impossible for a count. In our environment, they returned -16,675,713, -5,014,914, and 19,628.

All three ran one np.searchsorted over the whole sorted array, but the data is only sorted within each customer:

right = np.searchsorted(d, d + 7, side="right")   # d is not sorted across customers
count = int(np.sum(np.minimum(right, group_end) - np.arange(n) - 1))

The np.searchsorted assumes a sorted array, so on unsorted data its result is undefined. The exact wrong values even change between NumPy versions. The correct answer, 4,391, does not.

Step 11: What does think: false  mean?

Ollama's eval_count counts every token the model generated. If we subtract the chunks we actually received in message.thinking and message.content, we get the tokens the model generated. With thinking on or low, the gap is a small, constant 6 to 14 tokens per call, which means our thinking and answer counts are close to exact in those runs. With thinking off, more than a quarter of the generated tokens never reached us.

In the thinking-off run, the wait before the first answer token is much longer than the time spent reading the prompt. If we divide the hidden tokens by that extra wait, we get the model's normal generation speed:

Iteration

Hidden tokens

Extra wait before the answer

Implied speed

1

580

32.9 s

17.6 tokens/s

2

63

3.3 s

19.1 tokens/s

3

247

14.9 s

16.6 tokens/s

4

291

15.5 s

18.8 tokens/s

5

292

17.8 s

16.4 tokens/s

6

1,004

58.6 s

17.1 tokens/s

Every row lands at 16 to 19 tokens per second, the same rate the model generates normally. So those tokens were really generated, one by one, before any visible output, and they added 143 seconds to the run.

Time breakdown per iteration with thinking off, run 130150

Figure: The same time breakdown with think: false, run 130150.

The most likely explanation is that the model keeps reasoning, and Ollama just doesn't show it. That matches the model card, which says setting reasoning effort to its minimum does not fully disable reasoning. The logs prove the tokens were generated, but not what they contained.

So on this model, think: false reduces reasoning but doesn't remove it. The run generated 2,477 hidden tokens, against 6,344 to 16,279 visible thinking tokens in the full-thinking runs. This also means that the time to first token isn't comparable across thinking settings. 

Note that with thinking on, it measures the wait for the first thinking token. With thinking off, it measures the wait for the first answer token, which includes all the hidden reasoning.

Step 12: Track CPU and GPU power during a run

We ran powermetrics in a second terminal, sampling once a second during run 120936:

sudo powermetrics --samplers cpu_power,gpu_power -i 1000 -o power.log

The agent logs the start and end of every phase, so dashboard.py can line the samples up with model calls and tool runs. The two phases separate cleanly:

Phase

CPU

GPU

Model calls

2.20 W

13.14 W

Tests and benchmarks

6.08 W

0.29 W

CPU and GPU power across run 120936 with phases shaded

Figure: CPU and GPU power across run 120936, with phases shaded

The GPU does the model work, and the CPU does the testing. The above chart shows one GPU spike per iteration, peaking at 25.3 W, each at the start of a model call. Total energy for the 17.9-minute run was about 4.5 Wh, counting CPU and GPU power only.

Final Thoughts

Three practical behaviors came out of this experiment.

  1. The token budget is shared:  num_predict covers thinking and answering together, and a reasoning model can spend all of it thinking and return no code because the model used the extra room to keep thinking.

  2. think: false doesn't stop the reasoning: With think: false, 27% of the generated tokens were never shown, yet they were generated at the normal speed and added 143 seconds to the run. If you track reasoning cost, compare eval_count with the tokens you actually received.

  3. The correctness gate does the heavy lifting: The model fixed five planted bottlenecks at every thinking level. On the harder sixth step, four of five attempts produced wrong or truncated code, and the equivalence tests caught every one.

Note: These results come from five runs against one synthetic pipeline on one machine, so treat them as observations from this demo rather than general claims about Inkling 2 Mini.

Aashi Dutt

作者

Aashi Dutt

I am a Google Developers Expert in ML(Gen AI), a Kaggle 3x Expert, and a Women Techmakers Ambassador with 3+ years of experience in tech. I co-founded a health-tech startup in 2020 and am pursuing a master's in computer science at Georgia Tech, specializing in machine learning.

Inkling 2 Mini FAQs

What makes Inkling 2 Mini different from other small models?

It is a looped Mixture-of-Experts model. Its two middle blocks of layers run three times for every token, so it does more computation per token without storing more weights. It has 26.4B total parameters and 3.4B active per token, or 5.4B counting the loops.

Does a higher thinking level produce better code?

Not on the easy steps. All five runs fixed the same five bottlenecks in the same order, including the run with thinking off. On the hardest step, the setting wasn't decisive either: two runs with identical settings thought for 1,773 and 6,589 tokens and reached opposite outcomes.

Why did an iteration return no code at all?

It hit num_predict while still reasoning. A done_reason of length means the answer was cut off.

Does think: false make the model stop reasoning?

Not fully. In our thinking-off run, 2,477 generated tokens (27%) were never shown, and they added 143 seconds to the run. In every run with thinking on, the gap was only 39 to 45 tokens.

Why is reading the prompt so much faster than generating?

Reading a prompt processes all its tokens in parallel, while generation produces one token at a time. On our Mac, the model read prompts at about 188 tokens per second and generated at about 21.

主题

相关