mojolearn.models#
Load and run Hugging Face-format causal language models.
Reads .safetensors checkpoints (single file or sharded) and their
config.json, maps the weights onto mojolearn’s transformer blocks, and
runs them on the GPU.
CausalLM: embedding, decoder blocks, final norm and head built from a checkpoint, withforward,allocate_state,stepand greedygenerate.ParallelCausalLM: the same model with each layer assigned to a device (layer_devices).Tokenizer:Tokenizer.from_pretrainedovertokenizer.jsonfor byte-level BPE tokenizers, with the pre-tokenization pattern (PATTERNS: GPT-2, Llama 3, Qwen 2) as a parameter.HFConfig, plan_for(),FAMILIES: whichmodel_typevalues are supported (Llama 2/3 and SmolLM, Mistral, Qwen 2, Qwen 3, …), how config fields map onto block options, and which fields are refused by name withUnsupportedModel.Checkpoint,SafetensorsFile: the.safetensorsreader; tensors come back asmojolearn.Array.
Examples
>>> from mojolearn import Array
>>> from mojolearn.models import CausalLM, Tokenizer
>>> lm = CausalLM.load("path/to/model", weight_format="bfloat16")
>>> tok = Tokenizer.from_pretrained("path/to/model")
>>> ids = tok.encode("The capital of France is")
>>> out = lm.generate(Array.from_list([ids], "<i4"), 8)
Functions
|
The |
Classes
|
Experimental layer ownership. |
|
See the module header. |
|
The decode state: one block state per layer in stack order (each caller-owned and documented by its block class), |
|
A single |
|
A |
|
What |
|
One |
|
See the module header. |
Exceptions
A config field the blocks cannot honor, refused by name. |
- class mojolearn.models.ParallelCausalLM(plan, weights, *, layer_devices, **kwargs)[source]#
Bases:
CausalLMExperimental layer ownership. Use
load(path, layer_devices=(0, 1)).One device index per checkpoint layer; repeated indices are allowed. Metal requires every index to be zero (one worker on one GPU). Close explicitly or use a context manager. Calls and states must not be used concurrently. Output and state mathematics are the ordinary CausalLM path.
- class mojolearn.models.CausalLM(plan, weights, *, weight_format='float32', max_positions=None, device='auto', numeric_profile=None)[source]#
Bases:
objectSee the module header. Build with
load(a checkpoint directory) or directly from aModelPlanand a weight dict shaped like_read_weightsreturns.- classmethod load(path, *, weight_format='float32', max_positions=None, device='auto', numeric_profile=None)[source]#
A checkpoint directory (
config.jsonplusmodel.safetensorsormodel.safetensors.index.jsonand its shards).
- forward(ids, state=None)[source]#
(B, L)int32 ids in,(B, L, vocab)float32 logits out. Withstate=Noneevery block runs from a zero state and nothing is kept; with aCausalLMStatethe blocks read and update it in place.
- allocate_state(batch_size, max_tokens)[source]#
The zero decode state for
batch_sizerows of up tomax_tokenspositions each (Mamba*Block.allocate_state(B),TransformerBlock.allocate_state(B, max_tokens)).
- reset_state(state)[source]#
Replace caches with fresh zero state, preserving capacity and batch size.
States are owned by their allocating model; cross-model reuse is refused.
- step(ids, state)[source]#
One decode token per row:
(B,)or(B, 1)ids in,(B, vocab)logits out,stateupdated in place. It isforwardat L = 1 with each block’sstep(their one spelling for decode).
- generate(ids, max_new_tokens, *, greedy=True)[source]#
(B, L)ids in,(B, L + max_new_tokens)int32 ids out: the prompt followed by greedy continuations (argmax of the last position, ties to the lowest index), one carried state, the prompt as one prefill and every later token as onestep. No stop token: exactlymax_new_tokensare produced per row.
- class mojolearn.models.CausalLMState(batch_size, max_tokens, layers, *, owner=None)[source]#
Bases:
objectThe decode state: one block state per layer in stack order (each caller-owned and documented by its block class),
batch_size,max_tokens(the capacity the transformer caches were allocated for) andpositions, how many tokens each row has consumed.
- class mojolearn.models.Checkpoint(files, weight_map, root)[source]#
Bases:
objectA single
model.safetensors, an explicit.safetensorspath, or a directory holdingmodel.safetensors.index.jsonand its shards. Shards are opened on first use and closed byclose().
- class mojolearn.models.HFConfig(data, path=None)[source]#
Bases:
objectA
config.jsonas a read-only mapping withmodel_type,get,[]andpath.
- class mojolearn.models.ModelPlan(**kw)[source]#
Bases:
objectWhat
CausalLMassembles from. Fields:model_type,kind(“transformer” | “mamba1” | “mamba2”),n_layers,d_model,vocab_size,tie_embeddings,norm_eps(the FINAL norm’s epsilon, always passed to the norm primitive),max_position_embeddings,block_options(every interface option with its value, transformer only),block_kwargs(Mamba-2’sdt_limit, else empty),embed_name,norm_name,head_name(None when tied),layer_weights(i)-> list of(block_key, checkpoint_name, row_slice_or_None),family(the matrix row).
- class mojolearn.models.SafetensorsFile(path)[source]#
Bases:
objectOne
.safetensorsfile.names(),info(name),read(name); a context manager that closes the map. The map is opened on the first read and released byclose().
- class mojolearn.models.Tokenizer(tokens, merges, *, pattern, added=None, normalizer=None, bos_ids=(), eos_ids=(), ignore_merges=False, source='<tokens>')[source]#
Bases:
objectSee the module header.
tokensare the rank-ordered token bytes,mergesthe(left, right)byte pairs,patterna name inPATTERNS,added{content: id}.- classmethod from_pretrained(path)[source]#
pathis a directory holdingtokenizer.json(and optionallytokenizer_config.json), or thetokenizer.jsonitself.
- property n_vocab#
The ranks, extended by the added tokens above them.
- pretokenize(data)[source]#
The pre-tokens of
data(bytes) under this tokenizer’s pattern, as a list of bytes; the cut before any merge.
- encode_bytes(data, *, allow_special=False)[source]#
The ids of a byte string. Added tokens are recognized only with
allow_special=True; the segments between them are encoded alone (a special token ends the text before it, as the binding’s<|endoftext|>rule has it).
- exception mojolearn.models.UnsupportedModel[source]#
Bases:
ValueErrorA config field the blocks cannot honor, refused by name.