LLM Text Generation

Run autoregressive LLM text generation in Go using GoMLX's generate package with go-huggingface models and tokenizers.

LLM Text Generation with GoMLX and go-huggingface

GoMLX provides a high-level autoregressive text generation engine in github.com/gomlx/gomlx/ml/zoo/transformer/generate. Paired with go-huggingface, you can download pre-trained SafeTensors or quantized GGUF language models from HuggingFace Hub, tokenize prompts with their native chat templates, and generate text with KV-caching across any GoMLX backend (go, cuda, xla, mlx, mps, or onnx) — entirely in Go.

This tutorial walks through the full pipeline, based on the patterns used in go-huggingface/examples/dolly/benchmark_generate.


Prerequisites & Packages

You will use three main packages:

  • github.com/gomlx/go-huggingface/hub: Resolves and downloads model repositories (<owner>/<repo>[@<revision>][:<variant>]), automatically picking up HF_TOKEN from the environment for gated models (such as Gemma 4).
  • github.com/gomlx/go-huggingface/models/transformer: Parses HuggingFace SafeTensors or GGUF configurations and weights, loads them into a GoMLX model.Store, provides the matching tokenizer, and exposes Forward and KVCacheConfig.
  • github.com/gomlx/gomlx/ml/zoo/transformer/generate: Manages KV-cache initialization and growth, prompt prefill, incremental single-token decoding, sampling strategies (greedy, temperature, top-k, top-p, beam search), early stopping, and token streaming.
Choosing a Model: Any generative model in the Tested Models list works out of the box, including SafeTensors models (Qwen/Qwen3.5-4B, google/gemma-4-E2B-it, google/gemma-4-E4B-it) and quantized GGUF repositories (unsloth/Qwen3.5-4B-GGUF:Q4_0, unsloth/Qwen3.5-4B-GGUF:Q4_K_M).

Step 1: Initialize Backend and Load the Model

Start by initializing a GoMLX compute backend (controlled via GOMLX_BACKEND, e.g. go, cuda, xla:cuda, mlx) and loading the HuggingFace model repository and configuration:

backend, err := compute.New()
if err != nil {
	return err
}
defer backend.Finalize()

// Accepts SafeTensors repos (e.g. "Qwen/Qwen3.5-4B") or GGUF variants
// (e.g. "unsloth/Qwen3.5-4B-GGUF:Q4_0"). Reads HF_TOKEN automatically if set.
repo := hub.New(modelSpec)
if err := repo.DownloadInfo(false); err != nil {
	return err
}

hfModel, err := transformer.LoadModel(repo)
if err != nil {
	return err
}

// Configure the transformer for autoregressive text generation.
hfModel.WithCausalMask(true).
	WithOnlyLastTokenLogits(true).
	WithMMap(useMMap).
	WithForceFloat32(forceF32)

Key configuration options on hfModel:

  • WithCausalMask(true): Enables causal (autoregressive) attention masking so each token only attends to itself and earlier tokens.
  • WithOnlyLastTokenLogits(true): Slices the final hidden states to only the last sequence position before projecting through lm_head. During prompt prefill this skips computing unused vocabulary logits for all earlier prompt tokens, significantly reducing prefill latency and memory.
  • WithMMap(false): Uses standard file I/O instead of mmap when reading SafeTensors weights, avoiding counting the weight file size toward process Resident Set Size (MaxRSS).
  • WithForceFloat32(true): Converts Float16/BFloat16 weights to Float32 on load (useful for backends without native half-precision kernels).

Next, create a GoMLX model.Store, enable fused quantized matrix multiplications (important for GGUF models), and load the weights:

store := model.NewStore()
defer store.Finalize()

store.SetParams(map[string]any{
	layers.ParamQuantizedMatmul: true,
})

if err := hfModel.LoadStore(backend, store); err != nil {
	return err
}

Step 2: Tokenizer, Chat Templates, and Stop Tokens

Retrieve the tokenizer associated with the model (either from tokenizer.json / SentencePiece files or embedded directly inside a GGUF file):

tokenizer, err := hfModel.GetTokenizer()
if err != nil {
	return err
}

Instruction-tuned models expect prompts wrapped in their chat template and terminate turns with a model-specific stop token in addition to the standard EOS token. Following benchmark_generate, you can auto-detect common chat templates directly from the tokenizer’s vocabulary:

type chatTemplate struct {
	prefix    string
	suffix    string
	stopToken string
}

func detectChatTemplate(tok tokenizers.Tokenizer) chatTemplate {
	ttid, ok := tok.(interface {
		TokenToID(token string) (int, bool)
	})
	if !ok {
		return chatTemplate{}
	}
	if _, hasStart := ttid.TokenToID("<|turn>"); hasStart {
		if _, hasEnd := ttid.TokenToID("<turn|>"); hasEnd {
			return chatTemplate{
				prefix:    "<bos><|turn>user\n",
				suffix:    "<turn|>\n<|turn>model\n",
				stopToken: "<turn|>",
			}
		}
	}
	if _, hasStart := ttid.TokenToID("<start_of_turn>"); hasStart {
		if _, hasEnd := ttid.TokenToID("<end_of_turn>"); hasEnd {
			return chatTemplate{
				prefix:    "<bos><start_of_turn>user\n",
				suffix:    "<end_of_turn>\n<start_of_turn>model\n",
				stopToken: "<end_of_turn>",
			}
		}
	}
	if _, hasStart := ttid.TokenToID("<|im_start|>"); hasStart {
		if _, hasEnd := ttid.TokenToID("<|im_end|>"); hasEnd {
			return chatTemplate{
				prefix:    "<|im_start|>user\n",
				suffix:    "<|im_end|>\n<|im_start|>assistant\n",
				stopToken: "<|im_end|>",
			}
		}
	}
	return chatTemplate{}
}

Resolve the special EOS, pad, and chat stop token IDs, and encode the formatted prompt (optionally truncating the body to fit a prompt token budget):

var stopTokenIDs []int
stopTokenSet := make(map[int]bool)

if eosID, err := tokenizer.SpecialTokenID(tapi.TokEndOfSentence); err == nil {
	stopTokenIDs = append(stopTokenIDs, eosID)
	stopTokenSet[eosID] = true
}

padTokenID := 0
if padID, err := tokenizer.SpecialTokenID(tapi.TokPad); err == nil && padID >= 0 {
	padTokenID = padID
}

tmpl := detectChatTemplate(tokenizer)
if tmpl.stopToken != "" {
	if ttid, ok := tokenizer.(interface {
		TokenToID(token string) (int, bool)
	}); ok {
		if stopID, ok := ttid.TokenToID(tmpl.stopToken); ok && !stopTokenSet[stopID] {
			stopTokenIDs = append(stopTokenIDs, stopID)
			stopTokenSet[stopID] = true
		}
	}
}

var prefixIDs, suffixIDs []int
if tmpl.prefix != "" {
	prefixIDs = tokenizer.Encode(tmpl.prefix)
}
if tmpl.suffix != "" {
	suffixIDs = tokenizer.Encode(tmpl.suffix)
}

bodyIDs := tokenizer.Encode(userPrompt)
if maxPromptTokens > 0 {
	maxBody := max(maxPromptTokens-len(prefixIDs)-len(suffixIDs), 1)
	if len(bodyIDs) > maxBody {
		bodyIDs = bodyIDs[:maxBody]
	}
}

promptIDs := make([]int, 0, len(prefixIDs)+len(bodyIDs)+len(suffixIDs))
promptIDs = append(promptIDs, prefixIDs...)
promptIDs = append(promptIDs, bodyIDs...)
promptIDs = append(promptIDs, suffixIDs...)

Step 3: Configure the KV Cache and generate.Generator

Before creating the generator, populate the model’s per-layer KV-cache configuration. This automatically handles standard full attention, sliding-window local attention (Gemma 4), and hybrid linear-attention recurrent/conv states (Qwen 3.5’s Gated DeltaNet):

kvCacheConfig := hfModel.KVCacheConfig()
tm := hfModel.CreateGoMLXModel(store.RootScope())
tm.PopulateKVCacheConfigs()

Now wrap hfModel.Forward in a generate.KVCacheModelFn and configure generate.Generator:

var modelFn generate.KVCacheModelFn = func(
	scope *model.Scope,
	newTokens, position *graph.Node,
	cache kvcache.KVCacheNodes,
) (*graph.Node, kvcache.KVCacheNodes) {
	return hfModel.Forward(scope, newTokens, position, nil, nil, cache)
}

gen := generate.New(modelFn).
	WithKVCache(kvCacheConfig, tm.NumKVHeads, tm.HeadDim, tm.DType).
	WithMaxLength(maxPromptTokens + maxGenTokens).
	WithPadToken(padTokenID).
	WithDonateStore(donateStore)

if len(stopTokenIDs) > 0 {
	gen.WithStopTokens(stopTokenIDs...)
}

Important Generator Options

  • WithMaxLength(n): Sets the maximum total sequence length (prompt tokens + generated tokens). Make sure this is strictly greater than len(promptIDs).
  • WithDonateStore(true): On backends that support shared constants (such as the pure-Go go backend), donates model weights from model.Store into shared backend constants reused across prefill and decode executors. This enables one-time weight pre-packing without duplicating memory.
  • WithStopTokens(ids...) / WithEOS(id): Enables early stopping as soon as any of the listed token IDs is produced.

Choosing a Sampling Strategy

By default, generate.New uses sample.StrategyGreedy (deterministic argmax). You can configure stochastic sampling or beam search with builder methods:

StrategyConfigurationDescription
Greedy (default)(none) or .WithStrategy(sample.StrategyGreedy)Always picks the highest-logit token (argmax).
Temperature.WithTemperature(0.7)Scales logits by 1 / temperature and samples via Gumbel-ArgMax.
Top-K.WithTemperature(0.8).WithTopK(40)Restricts sampling to the k most probable tokens.
Top-P (Nucleus).WithTemperature(0.8).WithTopP(0.9)Restricts sampling to the smallest token set with cumulative probability ≥ p.
Beam Search.WithBeamSize(4)Explores beamSize candidate sequences simultaneously (not supported in streaming mode).
When combining WithTemperature with WithTopK or WithTopP, call WithTemperature first (e.g. gen.WithTemperature(0.7).WithTopP(0.9)), because each builder method also updates the active Strategy. Once Decode or GenerateStreaming has been called on a Generator, its configuration is frozen — create a new Generator if you need different sampling parameters.

You can also load generation parameters from scope hyperparameters (generate_strategy, generate_temperature, generate_top_k, generate_top_p, generate_max_length, etc.) via gen.FromScope(store.RootScope()).


Step 4: Generate Text (Decode and GenerateStreaming)

Option A: One-Shot Generation with Decode

gen.Decode runs prompt prefill and the decode loop, returning a 2D Int32 tensor of shape [batch, totalLen] containing the prompt followed by the generated tokens:

outputTensor, err := gen.Decode(backend, store.RootScope(), promptIDs)
if err != nil {
	return err
}
defer outputTensor.FinalizeAll()

allTokens := outputTensor.Value().([][]int32)[0]
generatedIDs := make([]int, 0, len(allTokens)-len(promptIDs))
for _, id := range allTokens[len(promptIDs):] {
	if stopTokenSet[int(id)] {
		break
	}
	generatedIDs = append(generatedIDs, int(id))
}

fmt.Println(tokenizer.Decode(generatedIDs))

Option B: Token-by-Token Streaming with GenerateStreaming

For interactive CLIs or HTTP streaming endpoints, use gen.GenerateStreaming. The callback is invoked after every newly generated token and returns true to continue or false to stop early:

var generated []int
printedBytes := 0

err = gen.GenerateStreaming(backend, store.RootScope(), promptIDs, func(tokenID int) bool {
	if stopTokenSet[tokenID] {
		return false
	}
	generated = append(generated, tokenID)

	// Re-decode the accumulated slice so BPE/SentencePiece spacing and
	// multi-byte UTF-8 sequences render cleanly across token boundaries.
	text := tokenizer.Decode(generated)
	if len(text) > printedBytes && !strings.HasSuffix(text, "\uFFFD") {
		fmt.Print(text[printedBytes:])
		printedBytes = len(text)
	}
	return true
})
if err != nil {
	return err
}
fmt.Println()

Complete Runnable Example

Save the following as main.go and run it against any supported HuggingFace model:

package main

import (
	"flag"
	"fmt"
	"os"
	"strings"
	"time"

	"github.com/gomlx/compute"
	"github.com/gomlx/compute/support/humanize"
	"github.com/gomlx/go-huggingface/hub"
	"github.com/gomlx/go-huggingface/models/transformer"
	"github.com/gomlx/go-huggingface/tokenizers"
	tapi "github.com/gomlx/go-huggingface/tokenizers/api"
	_ "github.com/gomlx/gomlx/backends/default"
	"github.com/gomlx/gomlx/core/graph"
	"github.com/gomlx/gomlx/ml/layers"
	"github.com/gomlx/gomlx/ml/layers/attention/kvcache"
	"github.com/gomlx/gomlx/ml/model"
	"github.com/gomlx/gomlx/ml/zoo/transformer/generate"
)

var (
	flagModel        = flag.String("model", "unsloth/Qwen3.5-4B-GGUF:Q4_0", "HuggingFace model spec (<owner>/<repo>[@rev][:variant]).")
	flagPrompt       = flag.String("prompt", "Explain in three sentences why the sky is blue.", "User prompt.")
	flagPromptTokens = flag.Int("prompt_tokens", 1024, "Maximum prompt token budget.")
	flagGenTokens    = flag.Int("gen_tokens", 128, "Maximum number of tokens to generate.")
	flagTemperature  = flag.Float64("temperature", 0.0, "Sampling temperature (0 for greedy).")
	flagTopP         = flag.Float64("top_p", 0.0, "Nucleus sampling threshold (0 to disable).")
	flagStream       = flag.Bool("stream", true, "Stream tokens to stdout as they are generated.")
	flagDonateStore  = flag.Bool("donate_store", true, "Donate model weights to shared backend constants.")
	flagMMap         = flag.Bool("mmap", false, "Use mmap when loading SafeTensors weights.")
	flagForceF32     = flag.Bool("force_f32", false, "Force Float32 weights and computation.")
)

type chatTemplate struct {
	prefix    string
	suffix    string
	stopToken string
}

func detectChatTemplate(tok tokenizers.Tokenizer) chatTemplate {
	ttid, ok := tok.(interface {
		TokenToID(token string) (int, bool)
	})
	if !ok {
		return chatTemplate{}
	}
	if _, hasStart := ttid.TokenToID("<|turn>"); hasStart {
		if _, hasEnd := ttid.TokenToID("<turn|>"); hasEnd {
			return chatTemplate{
				prefix:    "<bos><|turn>user\n",
				suffix:    "<turn|>\n<|turn>model\n",
				stopToken: "<turn|>",
			}
		}
	}
	if _, hasStart := ttid.TokenToID("<start_of_turn>"); hasStart {
		if _, hasEnd := ttid.TokenToID("<end_of_turn>"); hasEnd {
			return chatTemplate{
				prefix:    "<bos><start_of_turn>user\n",
				suffix:    "<end_of_turn>\n<start_of_turn>model\n",
				stopToken: "<end_of_turn>",
			}
		}
	}
	if _, hasStart := ttid.TokenToID("<|im_start|>"); hasStart {
		if _, hasEnd := ttid.TokenToID("<|im_end|>"); hasEnd {
			return chatTemplate{
				prefix:    "<|im_start|>user\n",
				suffix:    "<|im_end|>\n<|im_start|>assistant\n",
				stopToken: "<|im_end|>",
			}
		}
	}
	return chatTemplate{}
}

func main() {
	flag.Parse()

	if err := run(); err != nil {
		fmt.Fprintf(os.Stderr, "Error: %+v\n", err)
		os.Exit(1)
	}
}

func run() error {
	// 1. Initialize backend.
	backend, err := compute.New()
	if err != nil {
		return fmt.Errorf("initialize backend: %w", err)
	}
	defer backend.Finalize()
	fmt.Printf("Backend: %s\n", backend.Description())

	// 2. Download repository info and load model configuration.
	repo := hub.New(*flagModel)
	if err := repo.DownloadInfo(false); err != nil {
		return fmt.Errorf("download repo info for %q: %w", *flagModel, err)
	}
	hfModel, err := transformer.LoadModel(repo)
	if err != nil {
		return fmt.Errorf("load model config: %w", err)
	}
	hfModel.WithCausalMask(true).
		WithOnlyLastTokenLogits(true).
		WithMMap(*flagMMap).
		WithForceFloat32(*flagForceF32)

	// 3. Load weights into a GoMLX model.Store.
	store := model.NewStore()
	defer store.Finalize()
	store.SetParams(map[string]any{
		layers.ParamQuantizedMatmul: true,
	})
	loadStart := time.Now()
	if err := hfModel.LoadStore(backend, store); err != nil {
		return fmt.Errorf("load weights: %w", err)
	}
	fmt.Printf("Loaded %s in %s\n", *flagModel, humanize.Duration(time.Since(loadStart)))

	// 4. Load tokenizer, detect chat template, and encode the prompt.
	tokenizer, err := hfModel.GetTokenizer()
	if err != nil {
		return fmt.Errorf("get tokenizer: %w", err)
	}

	var stopTokenIDs []int
	stopTokenSet := make(map[int]bool)
	if eosID, err := tokenizer.SpecialTokenID(tapi.TokEndOfSentence); err == nil {
		stopTokenIDs = append(stopTokenIDs, eosID)
		stopTokenSet[eosID] = true
	}
	padTokenID := 0
	if padID, err := tokenizer.SpecialTokenID(tapi.TokPad); err == nil && padID >= 0 {
		padTokenID = padID
	}

	tmpl := detectChatTemplate(tokenizer)
	if tmpl.stopToken != "" {
		if ttid, ok := tokenizer.(interface {
			TokenToID(token string) (int, bool)
		}); ok {
			if stopID, ok := ttid.TokenToID(tmpl.stopToken); ok && !stopTokenSet[stopID] {
				stopTokenIDs = append(stopTokenIDs, stopID)
				stopTokenSet[stopID] = true
			}
		}
	}

	var prefixIDs, suffixIDs []int
	if tmpl.prefix != "" {
		prefixIDs = tokenizer.Encode(tmpl.prefix)
	}
	if tmpl.suffix != "" {
		suffixIDs = tokenizer.Encode(tmpl.suffix)
	}
	bodyIDs := tokenizer.Encode(*flagPrompt)
	if *flagPromptTokens > 0 {
		maxBody := max(*flagPromptTokens-len(prefixIDs)-len(suffixIDs), 1)
		if len(bodyIDs) > maxBody {
			bodyIDs = bodyIDs[:maxBody]
		}
	}
	promptIDs := make([]int, 0, len(prefixIDs)+len(bodyIDs)+len(suffixIDs))
	promptIDs = append(promptIDs, prefixIDs...)
	promptIDs = append(promptIDs, bodyIDs...)
	promptIDs = append(promptIDs, suffixIDs...)

	// 5. Populate KV-cache metadata and configure generate.Generator.
	kvCacheConfig := hfModel.KVCacheConfig()
	tm := hfModel.CreateGoMLXModel(store.RootScope())
	tm.PopulateKVCacheConfigs()

	var modelFn generate.KVCacheModelFn = func(
		scope *model.Scope,
		newTokens, position *graph.Node,
		cache kvcache.KVCacheNodes,
	) (*graph.Node, kvcache.KVCacheNodes) {
		return hfModel.Forward(scope, newTokens, position, nil, nil, cache)
	}

	gen := generate.New(modelFn).
		WithKVCache(kvCacheConfig, tm.NumKVHeads, tm.HeadDim, tm.DType).
		WithMaxLength(len(promptIDs) + *flagGenTokens).
		WithPadToken(padTokenID).
		WithDonateStore(*flagDonateStore)

	if len(stopTokenIDs) > 0 {
		gen.WithStopTokens(stopTokenIDs...)
	}
	if *flagTemperature > 0 {
		gen.WithTemperature(float32(*flagTemperature))
	}
	if *flagTopP > 0 {
		gen.WithTopP(float32(*flagTopP))
	}

	// 6. Generate text.
	fmt.Printf("Prompt (%d tokens): %s\n\nResponse:\n", len(promptIDs), *flagPrompt)
	genStart := time.Now()
	genCount := 0

	if *flagStream {
		var generated []int
		printedBytes := 0
		err = gen.GenerateStreaming(backend, store.RootScope(), promptIDs, func(tokenID int) bool {
			if stopTokenSet[tokenID] {
				return false
			}
			genCount++
			generated = append(generated, tokenID)
			text := tokenizer.Decode(generated)
			if len(text) > printedBytes && !strings.HasSuffix(text, "\uFFFD") {
				fmt.Print(text[printedBytes:])
				printedBytes = len(text)
			}
			return true
		})
		if err != nil {
			return fmt.Errorf("streaming generation: %w", err)
		}
		fmt.Println()
	} else {
		outputTensor, err := gen.Decode(backend, store.RootScope(), promptIDs)
		if err != nil {
			return fmt.Errorf("decode: %w", err)
		}
		defer outputTensor.FinalizeAll()

		allTokens := outputTensor.Value().([][]int32)[0]
		generated := make([]int, 0, len(allTokens)-len(promptIDs))
		for _, id := range allTokens[len(promptIDs):] {
			if stopTokenSet[int(id)] {
				break
			}
			generated = append(generated, int(id))
		}
		genCount = len(generated)
		fmt.Println(tokenizer.Decode(generated))
	}

	elapsed := time.Since(genStart)
	fmt.Printf("\nGenerated %d tokens in %s (%.2f tok/s)\n",
		genCount, humanize.Duration(elapsed), float64(genCount)/max(elapsed.Seconds(), 1e-9))
	return nil
}

Run it with your preferred backend and model:

# Pure-Go CPU backend with a quantized GGUF model:
GOMLX_BACKEND=go go run . -model=unsloth/Qwen3.5-4B-GGUF:Q4_0

# Pure-Go CUDA GPU backend with SafeTensors BF16:
GOMLX_BACKEND=cuda go run . -model=Qwen/Qwen3.5-4B

# Gated Gemma 4 model (requires HF_TOKEN):
HF_TOKEN=hf_... GOMLX_BACKEND=cuda go run . -model=google/gemma-4-E2B-it

Going Further: Custom Generation Loops & Benchmarking

For standard applications, generate.Generator handles prefill, dynamic shapes, KV-cache buffer donation, and sampling automatically.

When you need finer-grained control — such as separating JIT compilation time from Time-To-First-Token (TTFT) and steady-state decode throughput, implementing teacher-forced accuracy benchmarks against a reference runtime, or applying custom prompt bucketing (support.TwoBitBucketLen) on static-shape backends like XLA — you can build custom model.Exec prefill and decode executors directly using kvCacheConfig.SerializeNodes/DeserializeNodes, graph.DonateTensorBuffer, and sample.SampleWithStrategy.

See the full reference implementations in go-huggingface:

Last updated December 5, 2026