New cohort: Agentic AI & LLM Engineering remote internship. Limited seats.Apply now
Lesson 20 of 21 20 minFree

Building with Mistral Models

Mistral AI's open and commercial models, how mixture-of-experts makes Mixtral fast, and how to choose and call Mistral models for your apps.

By the end of this lesson you will be able to:

  • Describe Mistral AI's main model families and their licences.
  • Explain mixture-of-experts (MoE): how a router uses only some "experts" per token.
  • Pick a Mistral model for a task and call it through an API or run it locally.
  • Calculate total vs active parameters for an MoE model.

Who is Mistral AI?

Mistral AI is a French AI company founded in 2023, known for efficient models and for releasing several of them with open weights under the permissive Apache 2.0 licence. Its first model, Mistral 7B (September 2023), outperformed larger open models of its time. That made it a favourite for developers running models on their own hardware.

The model families

Model line-ups change quickly, so always check Mistral's documentation for current versions. The main families:

  • Mistral 7B (Apache 2.0): a small, fast, general model, and a common base for fine-tuning.
  • Mixtral 8x7B and 8x22B (Apache 2.0): mixture-of-experts models that are fast for their quality (explained below).
  • Mistral NeMo (12B, Apache 2.0, built with NVIDIA): multilingual, with a 128K-token context.
  • Ministral: very small models for phones and edge devices.
  • Codestral: specialised for code completion and generation.
  • Pixtral: vision-language models that understand images.
  • Mistral Small, Medium and Large: premier models, available through Mistral's API and cloud platforms such as Azure AI Foundry, some with commercial licences.

Mixture of experts: only wake up the experts you need

In a normal ("dense") model, every parameter works on every token. A mixture-of-experts (MoE) model splits part of each layer into several expert sub-networks plus a small router. For each token the router picks just a few experts. In Mixtral it's the top 2 of 8. So the model holds lots of knowledge (many total parameters) but only uses a fraction per token (fewer active parameters), which makes it much faster than a dense model of the same total size.

Experts aren't neat "maths expert" or "Hindi expert" modules. The specialisation is learned automatically and is usually hard for humans to interpret. In this demo the routing is simulated, but always exactly 2 of 8, like Mixtral.

The numbers for Mixtral 8x7B: about 46.7B parameters in total, but only about 12.9B active for each token. It needs memory for all 46.7B, yet runs at roughly the speed of a ~13B dense model.

Using Mistral models

Through an API

# pip install mistralai   (run on your machine with a key from Mistral's console)
import os
from mistralai import Mistral

client = Mistral(api_key=os.environ["MISTRAL_API_KEY"])
reply = client.chat.complete(
    model="mistral-small-latest",
    messages=[{"role": "user", "content": "Give 3 MCQs on the French Revolution for Class 9."}],
)
print(reply.choices[0].message.content)

Mistral models are also in Azure AI Foundry's model catalogue and on other clouds, using each platform's usual SDK.

Locally

Open-weight versions run with Ollama (ollama run mistral), LM Studio or transformers, exactly as in Lessons 16 and 19.

Choosing a Mistral model

As always, shortlist two or three and compare them on your own evaluation set (Lesson 14).

Hands-on

Your task: the router gives each expert a score for the token. Convert the scores to probabilities with softmax, then return the indexes of the 2 highest, sorted ascending. Expected: Token 'Python' goes to experts [3, 6].

import math

router_scores = {
    "Solve":  [0.2, 2.1, 0.4, 0.1, 1.9, 0.3, 0.5, 0.0],
    "Python": [0.1, 0.3, 0.2, 2.4, 0.6, 0.2, 2.2, 0.4],
}

def softmax(xs):
    exps = [math.exp(x) for x in xs]
    total = sum(exps)
    return [e / total for e in exps]

def top2(scores):
    probs = softmax(scores)
    # TODO: return the indexes of the 2 largest probabilities, sorted ascending
    return []

for token, scores in router_scores.items():
    chosen = top2(scores)
    probs = softmax(scores)
    print(f"Token '{token}' goes to experts {chosen}  (weights {[round(probs[i], 2) for i in chosen]})")
Show solution
    best = sorted(range(len(probs)), key=lambda i: probs[i], reverse=True)[:2]
    return sorted(best)

Your task: a toy MoE model has shared layers plus 8 experts, and uses 2 experts per token. Compute total parameters (shared + all experts) and active parameters (shared + 2 experts), then the active share. Expected last line: Active share: 28%. Only about a quarter of the model works on each token.

# toy model sizes, in billions of parameters
shared = 2.0          # attention, embeddings, etc. used by every token
per_expert = 5.75     # each expert's feed-forward weights
n_experts = 8
top_k = 2

# TODO: total = shared + all experts; active = shared + top_k experts
total = 0.0
active = 0.0

print(f"Total parameters:  {total:.1f}B  (memory needed)")
print(f"Active per token:  {active:.1f}B  (compute per token)")
print(f"Active share: {active / total:.0%}" if total else "Active share: ?")
Show solution
total = shared + per_expert * n_experts
active = shared + per_expert * top_k

Check your understanding

Why is Mixtral 8x7B faster than a dense model with the same total parameters?

  1. It has fewer layers
  2. Each token only uses 2 of the 8 experts, so far fewer parameters are active
  3. It skips the tokenizer
  4. It always uses 4-bit precision

MoE keeps many total parameters but activates only a few experts per token.

Does an MoE model need less memory than a dense model of the same total size?

  1. Yes, it only loads 2 experts
  2. Yes, experts are stored on disk
  3. No, all experts must be in memory because any token might need any expert
  4. It needs no memory

Compute per token drops, but every expert still has to be loaded.

Which Mistral licence makes Mistral 7B and Mixtral easy to use commercially?

  1. Apache 2.0
  2. Non-commercial only
  3. Research-only
  4. No licence

Apache 2.0 is a permissive open-source licence that allows commercial use.

Key takeaways

  • Mistral AI offers open (Apache 2.0) models such as Mistral 7B, Mixtral and NeMo, plus premier API models.
  • Mixture-of-experts routes each token to a few experts: many total parameters, few active ones.
  • Use Mistral models via their API, cloud catalogues or locally with Ollama.
  • Pick by task (code, vision, long multilingual text, edge) and evaluate on your own data.

Last lesson: Meta's Llama family.

Your progress is saved in this browser.

Adapted from Lesson 20 of Microsoft's "Generative AI for Beginners" (MIT License), rewritten and extended by Aiprojects4U. View source