Running a model yourself

Running a model yourself: the llama mod

mods/llama.luma runs a model file itself: a GGUF file, as llama.cpp, Ollama and LM Studio use, read into memory and worked out in Luma, with nothing else installed and nothing leaving the computer. It is an llm.model, so a program written for the claude and openai mods works with it. Copy it next to your program with mods/gguf.luma and mods/llm.luma, which it uses, and import it.

import "llama"
import "llm"

ai: llama.model = llama.open(file("SmolLM2-135M-Instruct-Q8_0.gguf"))
print(ai.ask("What is the capital of France?"))

ai.stream("Tell me a story.", fn(part: str) {
    write(part)
})

c: llm.talk = ai.chat()
print(c.say("My name is Ann."))
print(c.say("What is my name?"))

Output (the first line):

The capital of France is Paris.

Which models

ArchitectureModels
llamaSmolLM and SmolLM2, TinyLlama, Llama 2 and 3 (3.1, 3.2: their RoPE factors), Mistral 7B, CodeLlama
qwen2Qwen 2 and 2.5
qwen3Qwen 3 (dense)

The weights must be of the types qmat takes: F32, F16, BF16, Q8_0, Q4_0, Q5_0, Q4_K and Q6_K. Files quantized to Q8_0 and Q4_K_M are; Q4_K_M files of models whose rows aren’t a multiple of 256 numbers use Q5_0 for those, which is why it’s there. Another type or architecture is an error that names it.

The weights aren’t read in: the file is mapped, so a model opens at once, the system keeps what it reads of it in memory as part of the file, and programs that run the same model share it. What the program takes for itself is the rest: about 100 MB for Qwen2.5-0.5B, 50 MB for CodeLlama-7B (as a cache of the conversation grows, more). It runs on the processor; the large products share its cores (LUMA_THREADS sets how many). A built program multiplies with AVX2 (SSE2 on processors without it): on a laptop’s 12-core i7, SmolLM2-135M writes about 40 tokens a second, Qwen2.5-0.5B (Q4_K_M) about 16 (12 on one thread), CodeLlama-7B (Q4_0) about 2 (1.4); luma run is about 10 times slower. A model as small as SmolLM2 is as fast on one thread (LUMA_THREADS=1), and a large one is held back by how fast memory gives the weights.

Asking

MethodWhat it does
llama.open(file)reads a model file
ai.ask(text), ai.ask(text, files)asks one question and gives the answer; files: text files (txt, md, csv, json, html, xml, log, luma), added to the question
ai.stream(text, part)asks, and gives each piece of the answer to part as it comes; the whole answer at the end
ai.extract(text, schema)the answer as a json that fits the schema, ready to convert
ai.tool(name, about, schema, run)adds a tool the model may call; ai.approve(check) asks before each call
ai.chat()starts a conversation, an llm.talk: c.say(text), c.flow(text, part); the model keeps what it has read, so each turn reads only what is new
ai.begin()the same conversation as a llama.chat, which also has c.text(): all the model has read in it, prompts in its template and answers, as the model reads it
ai.raw(text)runs the model on the text as it is, without a chat template, and gives what it writes after it: for models that aren’t made to chat
ai.logits(tokens)the model’s scores for the token after each of the tokens, a [vec]: one number for each token of the vocabulary
ai.tokenizer()the model’s tokenizer (a gguf.tokenizer): encode(text), decode(tokens), count(text)

Settings

MethodSetsIf not set
ai.system(text)the system promptthe one the model’s template gives, if any
ai.sample(temp, topk, topp)how the next token is picked, below0.8, 40, 0.95
ai.seed(n)where the chances start: the same n gives the same answersa random start
ai.tokens(n)the most tokens of an answerthe context’s room
ai.turns(n)the most rounds of tool calls in one question20
ai.context(n)the most tokens of a conversation, questions and answersthe model’s own length

How a question is put

A model made to chat was trained on conversations written in its own way, its chat template, which its file holds. The mod knows the three that most models use, by their text, and writes the question the same way:

TemplateModelsA question is in
ChatMLSmolLM, Qwen<|im_start|>user … <|im_end|>
Llama 3Llama 3, 3.1, 3.2user<|end_header_id|> … <|eot_id|>
MistralMistral, Mixtral[INST] … [/INST]

A template that gives a system prompt when there is none, as SmolLM’s and Qwen 2.5’s do (“You are Qwen, created by Alibaba Cloud. …”), gives it here too. Special tokens written in a question are read as text, so a question can’t end the turn early. Another template is error llama.FAILED; raw(text) still runs the model.

Picking the next token

The model gives a score to each token of its vocabulary; the answer is made one token at a time. With sample(temp, topk, topp):

  • the topk likeliest tokens are kept (all of them if topk is 0);
  • their scores are divided by the temperature temp and made chances: below 1 the likeliest gets likelier, above 1 the others do;
  • of those, the fewest whose chances add up to topp are kept, and one is picked by chance.

sample(0.0, 1, 1.0) always takes the likeliest token: the answer is the same every time. With a temperature above 0, seed(n) makes the chances come out the same every time for the same n. A built program and luma run give the same answers, to the bit.

Answers in JSON

extract(text, schema) gives an answer that is JSON fitting a schema, as the claude and openai mods’ extract does, with any model the mod runs:

obj City {
    name: str
    country: str
    people: int
}

j: json = ai.extract("Tell me about Paris.", schema(City))
city: City = convert(j)

The model can’t write anything else: before each token, the mod checks that the JSON can go on with it, and takes the likeliest one that fits (or, sampling, one of those that fit). So the answer is always JSON of the schema’s shape, even from a small model, though what it says is only as good as the model.

  • What can only be written one way, the mod writes itself: an object’s keys, in the schema’s order, with their quotes and colons, and a date’s dashes. Every key of an object is written, so a field with a default gets a value too.
  • The schema goes with the question, so the model knows the fields, and a date is asked for as YYYY-MM-DD (a time HH:MM:SS, a date and time YYYY-MM-DDTHH:MM:SS).
  • More schemas than the APIs’ strict mode takes: maps ({str: T}), types that contain themselves, {} (any JSON), enum and const, anyOf, a list of types.
  • Strings are well-formed UTF-8; numbers fit an int or a float (18 digits, 2 in an exponent). Date-times with a zone are put on the local clock, as the other mods do.
  • A model that strays (a question the schema doesn’t fit, sampling at a high temperature) can write a string or a list that doesn’t end: tokens(n) stops it with CUT. Qwen 3 answers without thinking first.

Tools

A model trained to call tools can call yours, as with the claude and openai mods:

// Where to look up the weather.
obj Place {
    city: str        // the city's name, e.g. Tartu
}

ai.tool("get_weather", "Gives the weather in a city now.", schema(Place), fn(input: json): str {
    p: Place = convert(input)
    return "{\"temperature\": 12, \"sky\": \"rain\"}"
})
print(ai.ask("What is the weather in Tartu now?"))

Output:

The current weather in Tartu is 12 degrees Celsius with a rain sky.

The tools are described to the model as its template does, and it calls them as it was trained to. When it starts a call, the call is written as extract writes JSON: the name is one of the tools’, the input fits that tool’s schema. The mod runs the tool (approve is asked first), gives the model the result (or error: ... if the tool raised an error or the call was declined), and the model goes on, until it answers without a call: at most turns(n) rounds.

TemplateModelsToolsA callIts result
Hermes (ChatML)Qwen 2.5, Qwen 3in the system prompt<tool_call> JSON </tool_call>, one or more<tool_response> in a user turn
Llama 3.1Llama 3.1, 3.2, 3.3in the first questionan answer that is JSON alone, one a turnan ipython turn

Tools are added before the first question of a conversation, which describes them. A model whose template has no tools (SmolLM2, Llama 2 and 3.0, CodeLlama, Mistral for now) can’t take one: tool is llama.FAILED. extract doesn’t use tools.

Scores of the next token

logits(tokens) gives what the model thinks of each next token, without picking one: for scoring texts, choosing between answers, or a model’s perplexity.

t: gguf.tokenizer = ai.tokenizer()
tokens: [int] = t.encode("The capital of France is")
scores: [vec] = ai.logits(tokens)
last: vec = scores[len(scores) - 1]
print(t.piece(last.index(last.max())))

Output:

 Paris

Errors

The codes of the claude and openai mods:

CodeWhen
llama.CUT (103)the answer reached tokens(n), or the conversation the context’s end
llama.FAILED (104)a file that isn’t there or isn’t a model this mod runs (its architecture, a weight’s type), a template it doesn’t know, a prompt longer than the context, a schema extract or tool can’t read, a tool for a model without tools, more rounds of tool calls than turns(n)

How it was checked

  • Small models of each architecture, with random weights of every type (and Qwen 2’s biases, Qwen 3’s normalized heads, Llama 3.1’s RoPE factors), against the same steps in numpy: the scores after each token agree within a float32’s last bit, and are the same bits in every mode.
  • SmolLM2-135M (Q8_0), Qwen2.5-0.5B (Q4_K_M) and CodeLlama-7B (Q4_0, SentencePiece’s tokenizer) against llama.cpp (b12864): the token the mod finds likeliest is llama.cpp’s greedy choice at 377 of 384 steps; at the other 7 the two were nearly tied (llama.cpp makes x 8-bit with a 16-bit scale, and adds in another order). The prompts are the same tokens as llama.cpp’s.
  • SmolLM2 answering, streaming, conversations and sampling with a seed, the same in every mode; its prompts are the tokens llama.cpp makes of its template.
  • extract: a model of random weights writes answers for schemas of every kind, and every answer fits its schema, keys in order, the same in every mode; Qwen2.5 and SmolLM2 read invoices, dates and family trees into objects.
  • Tools: what the model reads in a conversation with tools (c.text()) is, to the character, what the model file’s own template writes for it, as Hugging Face renders it: Qwen2.5 asked the weather (its call the one llama.cpp’s server makes, get_weather with {"city": "Tartu"}), and Llama 3.1’s template on a small model with Llama 3’s vocabulary.
  • The Llama 3 and Mistral templates are written as those models’ templates say; they haven’t been run with those models yet (Llama 3.1’s tools only on that small model).