models

package module
v0.0.0-...-ac36a33 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 12, 2026 License: Apache-2.0 Imports: 19 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

gollmx

GoMLX L

Documentation

Overview

Package models provides support for loading and running Hugging Face models in GoMLX.

It parses config.json files to understand model architectures and loads weights from safetensors format into GoMLX contexts.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ListArchitectures

func ListArchitectures() []string

ListArchitectures returns all registered model types.

func RegisterArchitecture

func RegisterArchitecture(modelType string, constructor BuilderConstructor)

RegisterArchitecture registers an architecture builder for a model type. Multiple model types can map to the same builder (e.g., "bert" and "roberta").

Types

type ArchitectureBuilder

type ArchitectureBuilder interface {
	// Name returns the architecture name for logging/debugging.
	Name() string

	// ParseConfig extracts architecture-specific config from BaseConfig.Raw.
	// This is called after the base config is parsed.
	ParseConfig(base *BaseConfig) error

	// LoadWeights loads weights into the GoMLX context from any weight source.
	// The context should use hierarchical scopes matching WeightMapping.
	LoadWeights(ctx *context.Context, weights WeightSource) error

	// WeightMapping returns the mapping from safetensors keys to context scope paths.
	// Used for debugging and documentation.
	WeightMapping() map[string]string

	// Config returns the base configuration.
	Config() *BaseConfig
}

ArchitectureBuilder defines the interface for building model architectures.

func NewBuilder

func NewBuilder(modelType string) (ArchitectureBuilder, error)

NewBuilder creates a new architecture builder for the given model type.

type BaseConfig

type BaseConfig struct {
	// Path to the config file (not from JSON).
	ConfigFile string `json:"-"`

	// Core architecture identifier.
	ModelType     string   `json:"model_type"`
	Architectures []string `json:"architectures,omitempty"`

	// Common dimensions.
	VocabSize             int `json:"vocab_size"`
	HiddenSize            int `json:"hidden_size"`
	NumHiddenLayers       int `json:"num_hidden_layers"`
	NumAttentionHeads     int `json:"num_attention_heads"`
	IntermediateSize      int `json:"intermediate_size"`
	MaxPositionEmbeddings int `json:"max_position_embeddings"`

	// Normalization.
	LayerNormEps float64 `json:"layer_norm_eps,omitempty"`
	RMSNormEps   float64 `json:"rms_norm_eps,omitempty"`

	// Activation function.
	HiddenAct string `json:"hidden_act,omitempty"`

	// Dropout (used during training).
	HiddenDropoutProb     float64 `json:"hidden_dropout_prob,omitempty"`
	AttentionProbsDropout float64 `json:"attention_probs_dropout_prob,omitempty"`

	// Type embeddings (BERT-style).
	TypeVocabSize int `json:"type_vocab_size,omitempty"`

	// The raw JSON for architecture-specific parsing.
	Raw map[string]interface{} `json:"-"`
}

BaseConfig contains fields common to all Hugging Face models. Architecture-specific fields are available in Raw for custom parsing.

func ParseConfigContent

func ParseConfigContent(content []byte) (*BaseConfig, error)

ParseConfigContent parses config.json content from bytes.

func ParseConfigFile

func ParseConfigFile(filePath string) (*BaseConfig, error)

ParseConfigFile loads and parses a config.json file.

func ParseConfigFromGGUF

func ParseConfigFromGGUF(f *gguf.File) (*BaseConfig, error)

ParseConfigFromGGUF creates a BaseConfig from GGUF file metadata. GGUF files embed configuration as metadata key-value pairs using the pattern "{architecture}.{field}" (e.g., "gemma3.block_count", "llama.embedding_length").

func (*BaseConfig) BOSTokenID

func (c *BaseConfig) BOSTokenID() int

BOSTokenID returns the beginning-of-sequence token ID from GGUF metadata, or 0 if not set.

func (*BaseConfig) EOSTokenID

func (c *BaseConfig) EOSTokenID() int

EOSTokenID returns the end-of-sequence token ID from GGUF metadata, or 0 if not set.

func (*BaseConfig) GetBool

func (c *BaseConfig) GetBool(key string) (bool, bool)

GetBool retrieves a boolean field from Raw config.

func (*BaseConfig) GetFloat

func (c *BaseConfig) GetFloat(key string) (float64, bool)

GetFloat retrieves a float field from Raw config.

func (*BaseConfig) GetInt

func (c *BaseConfig) GetInt(key string) (int, bool)

GetInt retrieves an integer field from Raw config.

func (*BaseConfig) GetString

func (c *BaseConfig) GetString(key string) (string, bool)

GetString retrieves a string field from Raw config.

func (*BaseConfig) GetStringSlice

func (c *BaseConfig) GetStringSlice(key string) ([]string, bool)

GetStringSlice retrieves a string slice from Raw config.

func (*BaseConfig) HeadDim

func (c *BaseConfig) HeadDim() int

HeadDim returns the dimension of each attention head. If an explicit head_dim is set in Raw config, it is used (e.g., Gemma 3). Otherwise falls back to hidden_size / num_attention_heads.

func (*BaseConfig) SpecialTokenID

func (c *BaseConfig) SpecialTokenID(key string) (int, bool)

SpecialTokenID returns a special token ID by its config key name, or (0, false) if not found. Common keys: "image_token_id", "start_of_image_token_id", "end_of_image_token_id", "start_of_turn_token_id", "end_of_turn_token_id".

type BuilderConstructor

type BuilderConstructor func() ArchitectureBuilder

BuilderConstructor is a function that creates a new ArchitectureBuilder.

func GetArchitecture

func GetArchitecture(modelType string) (BuilderConstructor, bool)

GetArchitecture returns the builder constructor for a model type.

type GGUFSource

type GGUFSource struct {
	Model *gguf.Model
}

GGUFSource adapts *gguf.Model to the WeightSource interface.

func (*GGUFSource) GetTensor

func (g *GGUFSource) GetTensor(name string) (*LoadedWeight, error)

GetTensor loads a tensor from the GGUF model. For supported quantized types, returns raw quantized bytes as [N, bytesPerRow] Uint8 with GGMLType set. For native types, returns the tensor directly. Callers must handle quantized tensors appropriately (QuantizedDense for matmul, QuantizedGather for embedding lookups, etc.).

func (*GGUFSource) ListTensorNames

func (g *GGUFSource) ListTensorNames() []string

ListTensorNames returns all tensor names in the GGUF model.

type LoadWeightsOptions

type LoadWeightsOptions struct {
	// ComputeDType is the target dtype for non-quantized weights.
	// If set (non-zero), Float16 and BFloat16 weights are converted to this dtype
	// at load time, eliminating per-inference dtype conversion overhead.
	// Quantized weights (GGML formats) are never converted — they stay in native
	// block format for fused quantized matmul kernels.
	// Zero means no conversion (weights keep their original dtype).
	ComputeDType dtypes.DType
}

LoadWeightsOptions configures weight loading behavior.

type LoadedWeight

type LoadedWeight struct {
	Tensor       *tensors.Tensor
	GGMLType     backends.GGMLQuantType // Quantization format (only valid when Quantized is true).
	Quantized    bool                   // True for GGML-quantized tensors.
	LogicalShape []int                  // Original dimensions before block packing; nil for non-quantized.
}

LoadedWeight wraps a tensor with optional quantization metadata. For non-quantized tensors (safetensors, native GGUF types), Quantized is false. For GGML-quantized tensors, Tensor contains raw quantized bytes as [N, bytesPerRow] Uint8, GGMLType indicates the quantization format, and LogicalShape gives the original [N, K] dimensions.

func (*LoadedWeight) IsQuantized

func (lw *LoadedWeight) IsQuantized() bool

IsQuantized returns true if the weight uses GGML quantization.

type Model

type Model struct {
	// Config is the parsed model configuration.
	Config *BaseConfig

	// Builder is the architecture-specific builder.
	Builder ArchitectureBuilder

	// Weights provides access to model tensors (safetensors or GGUF).
	Weights WeightSource
}

Model represents a loaded Hugging Face model with its weights and architecture.

func New

func New(repo *hub.Repo) (*Model, error)

New creates a Model from a Hugging Face repository. It downloads config.json and model.safetensors, parses the config, and sets up the architecture builder.

func NewFromGGUF

func NewFromGGUF(path string) (*Model, error)

NewFromGGUF creates a Model from a local GGUF file. Configuration is parsed from GGUF metadata (no config.json needed).

func NewFromGGUFRepo

func NewFromGGUFRepo(repo *hub.Repo, filenames ...string) (*Model, error)

NewFromGGUFRepo creates a Model from a HuggingFace repo containing GGUF files. If filenames are specified, only those files are downloaded. Otherwise, all .gguf files in the repo are downloaded. For repos with many quantization variants (e.g., second-state/Llava-v1.5-7B-GGUF), specify filenames to avoid downloading all variants.

func NewFromLocal

func NewFromLocal(dir string) (*Model, error)

NewFromLocal creates a Model from a local directory containing config.json and model.safetensors. The directory should be a cached HuggingFace model directory (e.g., from a previous download).

func (*Model) LoadWeightsIntoContext

func (m *Model) LoadWeightsIntoContext(ctx *context.Context) error

LoadWeightsIntoContext loads all model weights into the given GoMLX context. This should be called once before building the computation graph.

func (*Model) Summary

func (m *Model) Summary() string

Summary returns a summary of the model configuration and weights.

func (*Model) WeightMapping

func (m *Model) WeightMapping() map[string]string

WeightMapping returns the mapping from safetensors keys to context scope paths.

type ModelInputs

type ModelInputs struct {
	InputIDs      interface{} // Token IDs: [batch, seq_len]
	AttentionMask interface{} // Attention mask: [batch, seq_len]
	TokenTypeIDs  interface{} // Optional segment IDs: [batch, seq_len]
	PositionIDs   interface{} // Optional position IDs: [batch, seq_len]
}

ModelInputs contains the standard inputs for transformer models.

type ModelOutputs

type ModelOutputs struct {
	LastHiddenState interface{}   // Final hidden states: [batch, seq_len, hidden_size]
	PoolerOutput    interface{}   // Pooled output: [batch, hidden_size] (optional)
	AllHiddenStates []interface{} // All layer hidden states (optional)
	Attentions      []interface{} // All attention weights (optional)
}

ModelOutputs contains the standard outputs from transformer models.

type QuantInfo

type QuantInfo map[string]backends.GGMLQuantType

QuantInfo maps context scope paths to their GGML quantization type. Only contains entries for quantized tensors.

func LoadWeightsFromMapping

func LoadWeightsFromMapping(weights WeightSource, mapping map[string]string, ctx *context.Context, opts ...LoadWeightsOptions) (QuantInfo, error)

LoadWeightsFromMapping loads weights from a WeightSource into a GoMLX context using the given mapping from tensor names to context scope paths. Missing tensors (not found errors) are silently skipped. Returns quantization info for any quantized tensors that were loaded.

type SafetensorsSource

type SafetensorsSource struct {
	Model *safetensors.Model
}

SafetensorsSource adapts *safetensors.Model to the WeightSource interface.

func (*SafetensorsSource) GetTensor

func (s *SafetensorsSource) GetTensor(name string) (*LoadedWeight, error)

GetTensor loads a tensor from the safetensors model.

func (*SafetensorsSource) ListTensorNames

func (s *SafetensorsSource) ListTensorNames() []string

ListTensorNames returns all tensor names in the safetensors model.

type WeightSource

type WeightSource interface {
	// GetTensor loads a single tensor by name.
	// For quantized GGUF tensors, returns raw bytes with quantization metadata.
	GetTensor(name string) (*LoadedWeight, error)

	// ListTensorNames returns all available tensor names.
	ListTensorNames() []string
}

WeightSource abstracts over different weight storage formats (safetensors, GGUF).

Directories

Path Synopsis
architectures
bert
Package bert provides a BERT architecture implementation for GoMLX.
Package bert provides a BERT architecture implementation for GoMLX.
common
Package common provides shared components for transformer architectures.
Package common provides shared components for transformer architectures.
deberta
Package deberta provides DeBERTa v2/v3 architecture implementation for GoMLX.
Package deberta provides DeBERTa v2/v3 architecture implementation for GoMLX.
gemma3
Package gemma3 provides a Gemma 3 architecture implementation for GoMLX.
Package gemma3 provides a Gemma 3 architecture implementation for GoMLX.
llama
Package llama provides Llama/Mistral architecture implementation for GoMLX.
Package llama provides Llama/Mistral architecture implementation for GoMLX.
phi3
Package phi3 provides Phi-3/Phi-3-Vision architecture implementation for GoMLX.
Package phi3 provides Phi-3/Phi-3-Vision architecture implementation for GoMLX.
cmd
download command
Command download downloads a specific file from a HuggingFace repo.
Command download downloads a specific file from a HuggingFace repo.
examples
gemma3 command
Command gemma3 generates text using a Gemma 3 model loaded from a GGUF file, using the serving engine with engine-managed KV cache.
Command gemma3 generates text using a Gemma 3 model loaded from a GGUF file, using the serving engine with engine-managed KV cache.
llava command
Command llava generates text using a LLaVA model loaded from a GGUF file, using the serving engine with paged KV cache.
Command llava generates text using a LLaVA model loaded from a GGUF file, using the serving engine with paged KV cache.
phi3v command
Command phi3v generates text using a Phi-3-Vision model loaded from a GGUF file, using the serving engine with paged KV cache.
Command phi3v generates text using a Phi-3-Vision model loaded from a GGUF file, using the serving engine with paged KV cache.
Package engine provides a continuous batching inference engine for GoMLX.
Package engine provides a continuous batching inference engine for GoMLX.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址