Artificial Intelligence
AI model types beyond the LLM: eight acronyms, four questions
LLM, VLM, MoE, SLM, LAM: the acronyms for AI models tend to show up in a single list, as if they were types to choose from. They are not on the same axis. Some say what goes into the model and what comes out, one says how it is built inside, one says how big it is and one says what it was trained for. Knowing which question each acronym answers avoids comparing things that do not compare and picking a model by the wrong label.
Four questions behind eight acronyms
An AI model is a function with many numbers adjusted during training, its parameters. The acronyms describe that model from different angles:
| Question | Acronyms | What it decides |
|---|---|---|
| What goes in and what comes out? | LLM, MLM, VLM, LCM, SAM | The task it can do |
| How is it built inside? | MoE | How much compute each token takes and how much memory the server needs |
| How big is it? | SLM | Where it can run |
| What was it trained or sold for? | LAM | Whether its output is text or actions |
That is why "LLM or MoE" is not a choice: Mixtral is an LLM and is built as an MoE.
What goes in and what comes out: LLM, MLM, VLM, LCM and SAM
These five acronyms describe the shape of the input and the output. A model that does not take images cannot read a photo, however large it is.
LLM: text that continues text
An LLM (large language model) predicts the next token, the piece of text it works with, from the previous ones, and repeats until the answer is done. GPT-3 was presented as an autoregressive model with 175 billion parameters, and almost all LLMs are based on the Transformer. It is used to generate or transform text and code, hold a conversation and follow instructions; to choose one by task, there is a guide on which Claude model to use for each case. It does not see images or take actions on its own: that takes a VLM or an agent with tools.
MLM: the missing word
An MLM (masked language model) is defined by its training objective: hiding part of the tokens and guessing them from the text around them, on both sides. BERT, an encoder, is the representative example: during training it hid 15% of the tokens in each sequence. Of those, 80% are replaced with [MASK], 10% with a random word and 10% are left as they are. It does not generate long texts; it classifies texts, extracts entities and helps retrieve documents, at a much smaller size: bert-base-uncased has about 110 million parameters.
For similarity search, BERT as it is does not work: comparing pairs, finding the two most similar sentences among 10,000 takes it about 65 hours, and with Sentence-BERT, a model trained to produce embeddings, about 5 seconds. Those embeddings are what the search step of a RAG system uses.
VLM: image and text in, text out
A VLM (vision-language model) is a language model that also takes images, as the Hugging Face documentation defines it. LLaVA, for example, connects an image encoder to an LLM. It is used to ask about a photo or a screenshot, read a scanned document or describe an image, and there are small ones: Phi-3.5-Vision has 4.2 billion parameters. Its output is text: a VLM does not generate images.
LCM: images in a few steps
The acronym LCM has two owners. Here it means latent consistency model: an image generator obtained from a latent diffusion model, such as Stable Diffusion, so that it generates in a few steps. A regular diffusion refines the image many times; an LCM reaches 768 x 768 images in 2 to 4 steps. It fits when generation speed matters. Meta uses the same acronym for something else, Large Concept Model, a language model that predicts whole sentences in an embedding space and does not generate images.
SAM: the outline of an object
SAM (Segment Anything Model) takes an image and a prompt (a point, a box or a mask) and returns the mask of the object it points to. It was trained on over a billion masks across 11 million images, and once the image is processed it gives each mask in 50 ms in the browser. SAM 2 adds video and is 6 times faster on images. SAM 3 segments by concept: from a short phrase, such as "yellow school bus", or from visual examples (example boxes drawn on the image), it finds every instance of that concept and returns a mask for each one. According to its repository, it has 848 million parameters. It is used to cut out objects, label training data or count objects in video. SAM and SAM 2 do not say what the object is, only where it is; also, SAM 3 changed its license and asks for terms to be accepted before its weights can be downloaded.
How it is built: MoE
MoE (mixture of experts) is a way of building the feed-forward layer: instead of a single network there are several, the experts, and a router picks a few of them for each token. In Mixtral, at each layer, the router picks 2 of 8 experts. A large LLM can be an MoE, like Mixtral; DeepSeek-V3, which has 671 billion parameters and uses 37 billion per token; or Phi-3.5-MoE, which activates 6.6 of its 41.9 billion.
"8x7B" is not 56 billion. The eight experts only replace the feed-forward layer; attention and embeddings are shared, so Mixtral's total comes to 46.7 billion. Routing also has its own cost: the Mixtral authors point it out as overhead.
Splitting the experts across several GPUs, or offloading part of the weights to RAM or disk, lowers the memory each device needs, but the total is still there. Hugging Face's Accelerate library, for example, fills the GPUs first and then the CPU and the disk, and each offloaded layer travels to the GPU on every pass, which adds overhead to inference.
How big it is: SLM
An SLM (small language model) is a small LLM, and "small" has no fixed threshold. SmolLM2 puts "small" in quotes for 1.7 billion parameters; Microsoft calls Phi-3-mini, at 3.8 billion, an SLM; and Google measures Gemma 3n in "effective" parameters, lower than the total. It is used on the device, offline, when latency or budget is the constraint. According to its technical report, Phi-3-mini quantized to 4 bits takes 1.8 GB and ran at more than 12 tokens per second on an iPhone 14.
A small model fitting on a phone says nothing about its quality on each task: that is measured on the tasks it will actually do. The comparisons each vendor publishes against larger models are claims by their authors.
What it was trained for: LAM
A LAM (large action model) is a model trained to produce actions, such as function calls or steps in an interface, instead of a text answer. It is not an architecture of its own. Microsoft's paper on LAMs says they are often built on LLMs, and Salesforce's xLAM models are fine-tuned LLMs, two of them starting from DeepSeek-Coder, with dense and MoE versions. Rabbit uses the same name for its product, so the acronym is also a commercial label.
Its place is inside an agent that calls tools, but a LAM is not a requirement: an ordinary LLM with tool calling can already be the piece that acts. Many chat models are trained to request those calls, according to the transformers documentation, and the agent runs them. A LAM does not bring safety by itself: the permissions, the confirmations and the log of each action are designed in the agent, outside the model.
An example: support for an online store
A hypothetical case shows how the acronyms fit together in one system:
- a fine-tuned MLM classifies each ticket (shipping, refund, defect) and an embedding model finds similar help articles;
- a VLM reads the photo of the damaged product the customer sends;
- SAM cuts the product out of that photo for the supplier report;
- an LLM writes the answer from all of the above;
- a LAM, or an LLM with function calling, prepares the refund, which a person confirms;
- an SLM runs in the courier's app, offline, to summarize the delivery note;
- an LCM generates variants of the promotion banner in seconds.
Each step picks its model by what goes in and what comes out. Whether the LLM that writes is MoE or dense does not change the task: it changes how much memory the server needs.
Counting parameters without downloading the model
The cost of an MoE shows without running anything. A transformers model on Hugging Face publishes a config.json with its dimensions, and the total and active parameters per token come from there. The script below does that count with nothing but the Python standard library. It also gives the memory the weights take at 16, 8 and 4 bits. For the five configs in the repository, the total matches the one Hugging Face publishes for each model.
The full script, model_size.py:
"""Count the parameters of a model from its Hugging Face config.json, without downloading weights.
For a mixture-of-experts (MoE) model it reports two numbers: the total parameters, which all have to
be loaded in memory, and the active parameters, the ones a single token goes through. It also gives
the memory the weights alone take at 16, 8 and 4 bits per parameter.
Only the layer layouts below are supported; any other model_type is rejected:
llama, phi3 decoder-only causal LM, RMSNorm, dense MLP
mixtral decoder-only causal LM, RMSNorm, MoE MLP
phimoe decoder-only causal LM, LayerNorm with bias, MoE MLP
bert encoder-only masked LM (pooler, MLM head and NSP head included)
Standard library only. Python 3.10 or later.
"""
from __future__ import annotations
import json
import sys
from dataclasses import dataclass
from pathlib import Path
MAX_CONFIG_BYTES = 1_000_000
DECODER_NORMS = {
"llama": "rmsnorm",
"phi3": "rmsnorm",
"mixtral": "rmsnorm",
"phimoe": "layernorm",
}
MOE_TYPES = {"mixtral", "phimoe"}
ENCODER_TYPES = {"bert"}
BITS = {"16-bit": 16, "8-bit": 8, "4-bit": 4}
class ConfigError(ValueError):
"""The config is not one this tool can count exactly."""
@dataclass(frozen=True)
class ModelSize:
model_type: str
family: str
total: int
active: int
experts: int
experts_per_token: int
def weight_bytes(self, bits: int) -> int:
# Weights only: no KV cache, activations or quantization scales.
return self.total * bits // 8
def _reject_duplicate_keys(pairs: list[tuple[str, object]]) -> dict[str, object]:
seen: dict[str, object] = {}
for key, value in pairs:
if key in seen:
raise ConfigError(f"duplicate key {key!r}")
seen[key] = value
return seen
def _reject_constant(name: str) -> object:
raise ConfigError(f"'{name}' is not valid JSON")
def load_config(path: str | Path) -> dict[str, object]:
path = Path(path)
size = path.stat().st_size
if size > MAX_CONFIG_BYTES:
raise ConfigError(f"config is {size} bytes; the limit is {MAX_CONFIG_BYTES}")
text = path.read_text(encoding="utf-8")
try:
data = json.loads(text, object_pairs_hook=_reject_duplicate_keys, parse_constant=_reject_constant)
except json.JSONDecodeError as error:
raise ConfigError(f"invalid JSON: {error.msg} at line {error.lineno}") from None
except ConfigError:
raise
except (ValueError, RecursionError) as error:
# json raises these for an integer over 4,300 digits and for very deep nesting.
raise ConfigError(f"invalid JSON: {error}") from None
if not isinstance(data, dict):
raise ConfigError("config must be a JSON object")
return data
def _int(config: dict[str, object], key: str, minimum: int = 1) -> int:
if key not in config:
raise ConfigError(f"missing key '{key}'")
value = config[key]
# bool is a subclass of int in Python, so it is rejected explicitly.
if isinstance(value, bool) or not isinstance(value, int):
raise ConfigError(f"'{key}' must be an integer, got {type(value).__name__}")
if value < minimum:
raise ConfigError(f"'{key}' must be >= {minimum}, got {value}")
return value
def _bool(config: dict[str, object], key: str, default: bool | None = None) -> bool:
if key not in config:
if default is None:
raise ConfigError(f"missing key '{key}'")
return default
value = config[key]
if not isinstance(value, bool):
raise ConfigError(f"'{key}' must be true or false, got {type(value).__name__}")
return value
def _decoder(config: dict[str, object], model_type: str) -> ModelSize:
hidden = _int(config, "hidden_size")
vocab = _int(config, "vocab_size")
layers = _int(config, "num_hidden_layers")
heads = _int(config, "num_attention_heads")
kv_heads = _int(config, "num_key_value_heads")
intermediate = _int(config, "intermediate_size")
# The default of tie_word_embeddings differs between config classes, so it must be explicit.
tied = _bool(config, "tie_word_embeddings")
# transformers builds attention biases only for llama and phimoe; mixtral and phi3 hard-code bias=False.
attention_bias = _bool(config, "attention_bias", default=False)
if attention_bias and model_type not in ("llama", "phimoe"):
raise ConfigError(f"attention_bias true is not used by model_type {model_type!r}")
mlp_bias = _bool(config, "mlp_bias", default=False) if model_type == "llama" else False
lm_head_bias = _bool(config, "lm_head_bias", default=False) if model_type == "phimoe" else False
if config.get("head_dim") is not None:
head_dim = _int(config, "head_dim")
elif hidden % heads:
raise ConfigError(f"hidden_size {hidden} is not divisible by num_attention_heads {heads}")
else:
head_dim = hidden // heads
if heads % kv_heads:
raise ConfigError(f"num_attention_heads {heads} is not a multiple of num_key_value_heads {kv_heads}")
if model_type in MOE_TYPES:
experts = _int(config, "num_local_experts")
per_token = _int(config, "num_experts_per_tok")
if per_token > experts:
raise ConfigError(f"num_experts_per_tok {per_token} is larger than num_local_experts {experts}")
router = hidden * experts
else:
experts, per_token, router = 1, 1, 0
q_out, kv_out = heads * head_dim, kv_heads * head_dim
attention = hidden * q_out + 2 * hidden * kv_out + q_out * hidden
if attention_bias:
attention += q_out + 2 * kv_out + hidden
norm = 2 * hidden if DECODER_NORMS[model_type] == "layernorm" else hidden
expert = 3 * hidden * intermediate + ((2 * intermediate + hidden) if mlp_bias else 0)
shared = vocab * hidden + norm
if not tied:
shared += vocab * hidden + (vocab if lm_head_bias else 0)
per_layer = attention + 2 * norm + router
total = shared + layers * (per_layer + experts * expert)
active = shared + layers * (per_layer + per_token * expert)
family = "decoder-only causal LM" + (f", MoE {per_token} of {experts} experts" if experts > 1 else "")
return ModelSize(model_type, family, total, active, experts, per_token)
def _encoder(config: dict[str, object], model_type: str) -> ModelSize:
hidden = _int(config, "hidden_size")
vocab = _int(config, "vocab_size")
layers = _int(config, "num_hidden_layers")
heads = _int(config, "num_attention_heads")
intermediate = _int(config, "intermediate_size")
positions = _int(config, "max_position_embeddings")
token_types = _int(config, "type_vocab_size")
# BertConfig defaults to tied word embeddings and no cross-attention; other values add weights not counted here.
if not _bool(config, "tie_word_embeddings", default=True):
raise ConfigError("bert with tie_word_embeddings false is not supported")
if _bool(config, "add_cross_attention", default=False):
raise ConfigError("bert with add_cross_attention true is not supported")
if hidden % heads:
raise ConfigError(f"hidden_size {hidden} is not divisible by num_attention_heads {heads}")
def linear(n_in: int, n_out: int) -> int:
return n_in * n_out + n_out
layer_norm = 2 * hidden
embeddings = (vocab + positions + token_types) * hidden + layer_norm
layer = 4 * linear(hidden, hidden) + layer_norm + linear(hidden, intermediate) + linear(intermediate, hidden) + layer_norm
pooler = linear(hidden, hidden)
# MLM head: transform dense + LayerNorm + output bias (its weight is tied to the word embeddings).
mlm_head = linear(hidden, hidden) + layer_norm + vocab
nsp_head = linear(hidden, 2)
total = embeddings + layers * layer + pooler + mlm_head + nsp_head
return ModelSize(model_type, "encoder-only masked LM", total, total, 1, 1)
def count(config: dict[str, object]) -> ModelSize:
model_type = config.get("model_type")
if not isinstance(model_type, str):
raise ConfigError("missing or non-string 'model_type'")
if model_type in DECODER_NORMS:
return _decoder(config, model_type)
if model_type in ENCODER_TYPES:
return _encoder(config, model_type)
raise ConfigError(f"unsupported model_type {model_type!r}")
def describe(name: str, size: ModelSize) -> str:
lines = [f"{name} [{size.model_type}: {size.family}]"]
lines.append(f" total parameters {size.total:>18,}")
share = 100 * size.active / size.total
lines.append(f" active per token {size.active:>18,} ({share:.1f}% of total)")
memory = ", ".join(
f"{label} {size.weight_bytes(bits) / 1e9:.2f} GB ({size.weight_bytes(bits) / 2**30:.2f} GiB)"
for label, bits in BITS.items()
)
lines.append(f" weights in memory {memory}")
return "\n".join(lines)
def main(argv: list[str]) -> int:
if not argv:
print("usage: python model_size.py <config.json> [more configs]", file=sys.stderr)
return 2
status = 0
for arg in argv:
try:
print(describe(Path(arg).stem, count(load_config(arg))))
except (ValueError, OSError, OverflowError) as error:
print(f"{Path(arg).name}: error: {error}", file=sys.stderr)
status = 1
return status
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
With a downloaded config, python model_size.py configs/mixtral-8x7b.json is enough. The script takes several at once; this is the output for the five in the repository (results/report.txt):
bert-base-uncased [bert: encoder-only masked LM]
total parameters 110,106,428
active per token 110,106,428 (100.0% of total)
weights in memory 16-bit 0.22 GB (0.21 GiB), 8-bit 0.11 GB (0.10 GiB), 4-bit 0.06 GB (0.05 GiB)
mixtral-8x7b [mixtral: decoder-only causal LM, MoE 2 of 8 experts]
total parameters 46,702,792,704
active per token 12,879,925,248 (27.6% of total)
weights in memory 16-bit 93.41 GB (86.99 GiB), 8-bit 46.70 GB (43.50 GiB), 4-bit 23.35 GB (21.75 GiB)
phi-3-mini-4k [phi3: decoder-only causal LM]
total parameters 3,821,079,552
active per token 3,821,079,552 (100.0% of total)
weights in memory 16-bit 7.64 GB (7.12 GiB), 8-bit 3.82 GB (3.56 GiB), 4-bit 1.91 GB (1.78 GiB)
phi-3.5-moe [phimoe: decoder-only causal LM, MoE 2 of 16 experts]
total parameters 41,873,153,344
active per token 6,640,999,744 (15.9% of total)
weights in memory 16-bit 83.75 GB (77.99 GiB), 8-bit 41.87 GB (39.00 GiB), 4-bit 20.94 GB (19.50 GiB)
smollm2-1.7b [llama: decoder-only causal LM]
total parameters 1,711,376,384
active per token 1,711,376,384 (100.0% of total)
weights in memory 16-bit 3.42 GB (3.19 GiB), 8-bit 1.71 GB (1.59 GiB), 4-bit 0.86 GB (0.80 GiB)
Mixtral uses 27.6% of its parameters per token. In a dense model, such as Phi-3-mini, SmolLM2 or BERT, the active ones are 100%: compute and memory grow together. Phi-3-mini at 4 bits comes to 1.91 GB, which is 1.78 GiB: the "1.8 GB" in its technical report matches GiB, not GB.
The script rejects the configs it would count wrong instead of guessing. Python's json module accepts duplicate keys by default, keeping the last one, and NaN; the script rejects both. Since bool is a subclass of int, it rejects true where a size goes. If num_experts_per_tok is missing, it stops instead of using the transformers default, which is 2.
What it does not cover
The memory the script gives is a floor: it only counts the weights. On top of that number come the KV cache, the activations, the quantization scales and what the runtime takes.
- It does not measure speed. Active parameters set the compute per token, not the latency.
- It does not check whether a size is reasonable.
- It only understands the layers of Llama, Phi-3, Mixtral, Phi-3.5-MoE and BERT. DeepSeek-V3, with shared experts and a different attention, is rejected.
- It does not check that a config matches its weights, except for the five in the repository.
- The speed figures in this text come from each model's paper; nobody measured them here. No model's quality was compared either.
Conclusion
A LAM is almost always an LLM fine-tuned for actions, LCM has two meanings and MoE lowers the compute per token, not the memory. Before choosing a model, it pays to answer all four questions: which task it does, how much memory the server needs, where it will run and whether it will take actions, with permissions outside the model.
References
- NippysoftLabs: ai-model-types-beyond-llm (github.com)
- Mixtral of Experts (arxiv.org)
- BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding (arxiv.org)
- Large Action Models: From Inception to Implementation (arxiv.org)
- Segment Anything (arxiv.org)
- Phi-3 Technical Report: A Highly Capable Language Model Locally on Your Phone (arxiv.org)
- Big Model Inference (huggingface.co)
- Tool use (huggingface.co)
Tags
Share this post
Subscribe
Get the latest posts delivered right to your inbox.
Leave a comment