Skip to content
ImagineWorld

Small language models

node_idnode-book_build-small-language-model_chapter-01-small-language-models
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num1
chapter_titleSmall language models
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Part 1 First steps

T his first part of the book will introduce small language models (SLMs), explain the risks and challenges of using generalist LLMs, and discuss how these can be mitigated by switching to SLMs.

This chapter covers

  • Defining small language models
  • Limits and risks of using closed source generalist LLMs
  • Open source alternatives to closed source LLMs
  • Comparing LLMs and domain-specific language models

Whenever a new, potentially disruptive technology emerges, or an existing one undergoes a radical change, there’s inevitable hype about it. If expectations aren’t met, interest can drop quickly; if they are, investments and projects can surge before the real business potential and risks are understood. Either way, the “next big thing” rarely ends well. You can see the same thing happening today with large language models (LLMs): there’s so much hype that it’s difficult to understand what they really can (and can’t) do and whether they would be a good fit for your own business needs. This chapter aims to clarify the LLM world by highlighting the pros, risks, and challenges of both generalist and domain-specific models. Hype is the one thing you won’t find in this book.

Today, regardless of their technical background, most people are familiar with popular commercial LLMs such as GPT, Claude, and Gemini, which power chatbots and services from providers such as OpenAI, Anthropic, Google, and Microsoft. But there’s still limited awareness of a related category: small language models (SLMs). Like LLMs, SLMs are designed for natural language processing tasks, but they use fewer parameters, have a smaller memory footprint, and require less computational power. That makes them suitable for applications that run on mobile or edge devices or on-premises servers or small clusters. SLMs typically range from a few hundred million to a few billion parameters; there’s no official cutoff, but most stay under 10 billion parameters. That’s much smaller than LLMs, which often have hundreds of billions of parameters or more. Because of their small size, SLMs can be optimized for speed and energy efficiency, which are especially important for on-device or commodity hardware deployments. They can run well on CPUs (when no GPU is available) or on consumer GPUs. Since they run locally, the data can stay local, which is important for tasks involving sensitive or personal information. Their deployment flexibility also expands the range of use cases, making them ideal for offline, embedded, and near-real time applications in areas such as robotics and smart devices (such as mobile phones, lab equipment, appliances, and manufacturing machinery).

Although SLMs are smaller than LLMs, they aren’t a new type of model. Both are built on the same core technology—the Transformer architecture and later improvements. The difference is mostly in scale, not the underlying mathematical and architectural principles. As a result, they can address the same kinds of tasks, with SLMs being optimized more for efficiency than raw power.

NOTE The Transformer architecture was introduced in the “Attention is All You Need” paper by Ashish Vaswani and others (https://arxiv.org/abs/1706.03762).

An important benefit of SLMs is that you can specialize them for specific domains and tasks at relatively low cost, using domain-specific and private data plus domain knowledge, and apply techniques that don’t require full fine-tuning. Domain-specific tasks for language models are common in heavily regulated industries where privacy isn’t optional—healthcare, pharma/biotech, manufacturing, chemistry, finance, and others. You’ll see real-world examples in later chapters.

Beyond the well-understood reasons to choose SLMs over LLMs in specific use cases, another emerged with the rise of agentic AI and was highlighted in a mid-2025 NVIDIA research paper: “Small Language Models are the Future of Agentic AI” (https://arxiv.org/abs/2506.02153). The authors argue that SLMs are powerful enough, better suited, and more economical for many uses in agentic systems, making them central to the future of agentic AI. They also suggest that, even when general-purpose conversation is required, heterogeneous agentic systems—agents that invoke multiple models,

LLMs and SLMs—are the natural choice. The final chapters of this book explore the relationship between SLMs and agentic AI.

Before transformers, most tasks on unstructured text were performed using recurrent neural network (RNN) models. Trained on labeled data, these architectures use their internal state to process variable-length sequences of text. Later evolutions, such as LSTM (long short-term memory) or GRU (gated recurrent unit) architectures, introduced the capability to remember and forget important information, but they didn’t solve one of the major challenges of RNNs: slow training. The data must be processed sequentially, which limits parallelism across processor cores. The attention mechanism addressed some RNN limitations by emphasizing relevant parts of the input and downplaying others, effectively expanding the amount of information the model could carry forward. Still, it didn’t solve the scalability issues. That required the Transformer model, which introduced two major changes compared to RNNs:

  • It uses the self-attention mechanism (a specialization of the attention mechanism that relates different positions in a sequence to compute a representation of the sequence itself) so that it can process the entire input all at once.

  • It has no recurrent structure, so a transformer allows more parallelism than an RNN, significantly reducing training time.

Transformers didn’t only succeed because of their architecture. Another key component is word embeddings—high-dimensional vector representations of words that capture their semantic and syntactic properties. Embeddings let a Transformer model manipulate words in a numerical space, where related words end up near one another. This helps the model treat words as connected, not isolated, entities and understand how they interact in context.

Transformer architectures have also been proposed for tasks involving other data types, but multimodal use cases are out of scope for this book, which focuses on generative models for unstructured text.

The Transformer architecture initially proposed by Google Brain was just the start. As soon as researchers and professionals started to use it, they quickly found ways to improve and tailor it for text tasks. The original architecture was encoder–decoder based: the encoder part converts the input text into a numerical representation, while the decoder part takes that representation and converts it back to text. Both use an attention mechanism. Over time, it has become clear that some tasks need only the encoder, while others can rely only on the decoder. This led to two different families of transformers:

  • BERT (bidirectional encoder representation from transformers) uses only the encoder part. This kind of architecture performs better on text classification or prediction tasks.

  • GPT (generative pretrained transformer) uses only the decoder and generally performs better on text generation tasks.

Ultimately, your architecture choice will depend on the tasks you want to accomplish. The examples in this book cover both families.

Another important concept in the Transformer model’s evolution is reinforcement learning from human feedback (RLHF), a technique used behind the scenes for OpenAI’s LLMs. As the name suggests, it applies reinforcement learning so an LLM can learn a policy that maximizes a reward. The models behind ChatGPT are an evolution of the GPT architecture (the first two versions were open source; later versions moved to closed source), with RLHF applied for fine-tuning and improved performance.

The term “LLM” can be misleading. “Large” is clear enough: models range from a few billion to more than 100 billion parameters, or from tens to hundreds of gigabytes. But “language” can make people think that these models generate only natural-language text. Early natural-language processing (NLP) applications did focus on translation tasks, but newer architectures and capabilities let LLMs handle many tasks beyond translation:

  • Language understanding
  • Text classification
  • Test generation
  • Question answering
  • Document summarization
  • Semantic parsing
  • Pattern recognition
  • Basic math solving
  • Code generation
  • Dialogue
  • General knowledge
  • Logical inference chains

This makes it possible for an LLM to handle text beyond natural language—anything that symbolically represents something—as shown in figure 1.1. LLMs will unlock many real-world use cases across industries.

The Transformer architecture didn’t only ignite interest among companies such as OpenAI, Microsoft, and Google; the open source community also began releasing LLMs under varying licenses for models, code, and training data. Figure 1.2, taken from a paper titled “A Survey of Large Language Models” (https://arxiv.org/abs/2303.18223), shows a timeline of the major commercial and open source LLMs from 2019 to mid-2023 (the paper’s latest update; more models have appeared since).

┌──────────────────────────────────┐
┌───►│ Output in natural │
│ │ language │
│ └──────────────────────────────────┘
│ ┌──────────────────────────────────┐
LLM ├───►│ def create_empty_tensor(): │
┌──────────────┐ │ │ return torch.tensor([]) │
│ │ │ └──────────────────────────────────┘
│ (network │───────────────────┤ ┌──────────────────────────────────┐
│ graphic) │ ├───►│ SELECT COUNT(DISTINCT Country) │
│ │ │ │ FROM Customers; │
└──────▲───────┘ │ └──────────────────────────────────┘
│ │ ┌──────────────────────────────────┐
Input in natural language ├───►│ <<Add │
│ │ stir="False" │
│ │ time="20 mins" │
│ │ volume="50 mL" │
│ │ vessel="reactor" │
│ │ reagent="THF" /> │
│ └──────────────────────────────────┘
│ ┌──────────────────────────────────┐
└───►│ O=C1C=CC(=O)C=C1 │
└──────────────────────────────────┘

[!visual-conversion] Figure 1.1 — Some examples of the diverse content an LLM can generate (p. 19)

dslm-fig-1.2-a-timeline-diagram-showing-the.png

[!visual-conversion] Figure 1.2 — The timeline of LLMs from 2019 to mid-2023 (image from “A Survey of Large Language Models”) (p. 19)

1.5 Risks and challenges with generalist LLMs

Section titled “1.5 Risks and challenges with generalist LLMs”

Commercial, generalist, closed source LLMs from third-party vendors are powerful and can handle diverse tasks. They can also provide a good experience for non-technical users, and you pay only for usage (since you don’t have to manage deployment and maintenance). But they also come with risks that can outweigh these benefits:

  • Deployment outside your organization’s network—Any information you include in a prompt may leave your company and, depending on the usage terms, be used to fine-tune the model and be exposed to other customers. You’ve likely read of cases in which employees at large corporations sent sensitive or proprietary data to external model-hosting services (for example, at Samsung, as discussed in “Samsung Bans Staff’s AI Use After Spotting ChatGPT Data Leak” [Bloomberg, May 2, 2023, https://mng.bz/AGEE], and others).

  • Data leakage risks—Because the model is hosted on infrastructure you don’t control, a weak cybersecurity posture (unknown to you and hard to mitigate) can allow malicious actors to access private data. There is evidence that something like this happened once with ChatGPT (“OpenAI Confirms ChatGPT Data Breach,” Trend Micro’s blog, May 13, 2023, https://news.trendmicro.com/2023/05/13/openai-chatgpt-data-breach/).

  • Model or version drift—A provider can update a model without notice, potentially changing the behavior and accuracy of applications built on top of it.

  • Cost unpredictability—Token-based billing can spike, as a provider can decide at any time to change their subscription prices.

  • Closeness—You don’t have details about how an LLM was implemented and trained, so there’s no chance of reproducibility or interpretability, which is often a requirement in heavily regulated sectors. You also may not see infrastructure or model-version changes.

  • Transparency—Data used to train closed source models isn’t publicly disclosed, so there’s no way to verify whether it’s biased or contains copyrighted data used without the owner’s permission.

  • Hallucinations—Generated information may conflict with the source (intrinsic hallucination) or be unverifiable from the available source (extrinsic hallucination). Intrinsic hallucinations can occur even in an organization’s models trained on proprietary data—a challenge with LLMs in general. But extrinsic hallucinations can’t be mitigated when you don’t have access to, or knowledge of, the training data.

  • Compliance—Commercial and closed source LLMs, because of their generalist nature, don’t follow any sectoral rules.

  • Harmful content generation—Models can not only reflect societal biases and stereotyping but can also produce unsafe content. In the rare cases where a provider has set safety filters on generalist models, this can unnecessarily block legitimate content as a side effect.

  • Code generation—This emergent LLM ability makes it possible for a broader audience, including people with limited coding skills, to inadvertently generate code with malicious elements or even produce malware. Many third-party LLMs lack robust guardrails, and those that exist can be bypassed with carefully crafted prompts. Organizations can build their own guardrails (which isn’t a trivial task) or shift the responsibility to internal users to properly validate outputs.

All these risks, plus the fact that large models are trained on many tasks using broad but generalist data sets, mean they aren’t always suitable for important business uses.

1.6 Domain-specific vs. generalist LLMs for business value

Section titled “1.6 Domain-specific vs. generalist LLMs for business value”

Should you move to a custom domain-specific LLM? Several factors can help you make the right choice.

Generalist pretrained LLMs (both commercial and open source) are largely trained on content scraped (with or without consent) from the web, drawn from public scientific or code repositories, or taken from human conversations on generic topics. For tasks that don’t require domain specialization, these models are often powerful enough to generate useful content that can be reused with little or no refinement. But for specialized domains and tasks, you’ll need a strategy to tune the pretrained model on domain-specific data (whether public or private). This process is commonly referred to as transfer learning. In brief, transfer learning involves taking a model trained on one task or domain and applying it to a related task or domain.

In heavily regulated domains, there are stricter requirements for staying compliant. Decisions based on model outcomes cannot cause any sort of harm. In this context, the availability and quality of domain-specific training data (which you may already have in house) plays a key role.

Transfer learning does not necessarily involve the full training of a language model. That’s a possibility, but there are options, as listed in table 1.1.

Table 1.1 Options for specializing an open source SLM on a domain-specific task

Transfer learning strategyProsCons
Full supervised fine-tuning (unfreezing and training all the model’s weights on labeled data)- Strong performance when the data is sufficient and the domain shift is large- High computational costs
- Risk of overfitting
- Domain-specific data will probably need to be combined with other accessory data.
Partial fine-tuning (unfreezing and training only a subset of the model’s layers)- Cheaper than full fine-tuning- Requires initial experimentation to select the proper layers to unfreeze and train
- Risk of catastrophic forgetting

Table 1.1 Options for specializing an open source SLM on a domain-specific task (continued)

Transfer learning strategyProsCons
PEFT (parameter-efficient fine-tuning)—a family of techniques for inserting small trainable modules into each transformer layer while freezing the base■ Prevents catastrophic forgetting
■ Tiny trainable parameter count paired with strong performance
■ It is possible to train multiple adapters (for diverse tasks) that can be easily swapped at runtime.
■ Unlike partial fine-tuning, it doesn’t require experimentation to select the layers to unfreeze and train.
■ Adds a slight runtime overhead. Usually this isn’t a problem, but it depends on the latency KPI for a given application.

NOTE Catastrophic forgetting is a noticeable drop in performance on general knowledge or initial capabilities due to a model being trained on new data and tasks.

When you are specializing an SLM to a given domain and task, full training is rarely the best option.

There are many domains where SLM specialization is mandatory, such as manufacturing, scientific R&D, legal operations, finance, healthcare administration, and niche coding (such as CUDA and PLC programming). Figure 1.5 shows an example of LLM specialization in a very specific domain: after transfer learning on molecule

graph LR
subgraph Molecule generation
G1["The molecule is a quinolinemonocarboxylate that is the conjugate base of xanthurenic acid, obtained by deprotonation of the carboxy group."] --> LLM1["Fine-tuned LLM"]
LLM1 --> G2["C1=CC=C(C=C1)C=O"]
end
subgraph Molecule captioning
C1["C1=CC=C(C=C1)C=O"] --> LLM2["Fine-tuned LLM"]
LLM2 --> C2["It is a quinolinemonocarboxylate and a hydroxy monocarboxylic acid…"]
end

[!visual-conversion] Figure 1.5 — An LLM trained for tasks on molecule structures (generation and captioning) (p. 22)

descriptions and structures represented in the SMILES format, this LLM can generate molecular structures from description, or vice versa. This use case is discussed in chapter 8.

Any situation where you must prevent private data leakage is a good reason to switch to a private, offline, domain-specific LLM that runs inside your corporate network boundaries. In these cases, people often worry whether their existing on-premises or private-cloud infrastructure has enough computational power, especially when budgets are limited. We’ll look at optimization techniques to reduce the memory footprint and computational requirements of custom LLMs, with working examples in each chapter. Table 1.2 summarizes the pros and cons of generalist and domain-specific LLMs.

Table 1.2 Pros and cons of generalist and domain-specific LLMs

Generalist LLMsDomain-specific LLMs
Pros■ Offer a wide range of knowledge and capabilities
■ Can handle diverse tasks and topics
■ Have the flexibility to learn and adapt to new domains (assuming you have the computational power to do it)
■ Can generate content on a wide array of subjects
■ Provide specialized expertise in a specific domain
■ Well-suited for focused applications and specific industries
■ Higher accuracy and performance in specific areas of expertise
Cons■ Lack in-depth expertise in specific domains
■ Require additional fine-tuning and customization for specific tasks
■ Potential risk of making errors or producing inaccurate content
■ Require more computing power and resources
■ Better understanding and context within a specific domain
■ Limited applicability and effectiveness in non-specialized areas
■ Less flexibility to handle tasks outside the chosen domain
■ Could require more data and resources for training, fine-tuning, or RAG

Another advantage of choosing an open source baseline model is that it will likely have only a few billion parameters. After tuning it for domain-specific tasks with private data, the model will likely remain below 10 billion parameters. From a sustainability standpoint, these smaller models generate less CO₂ and have less environmental impact than larger models during training and doing inference.

Finally, let’s look at LLM alignment with users, which you’ve probably heard about. A common definition of “alignment” in this context is adhering to principles of helpfulness (following user instructions, completing a task, and providing results), truthfulness (providing factual information and acknowledging limitations), and harmlessness (avoiding biased or toxic responses and refusing to assist with harmful tasks). Commercial closed-source LLM vendors often pursue this by defining what is right and wrong from their own perspective and then shaping the models accordingly.

In my opinion, alignment should focus less on imposing the provider’s definition of “right” and more on matching the user’s intent. This is similar to working with a human collaborator: motives and knowledge/ability are different. Improving knowledge and ability may lower the mistake rate, but it doesn’t mean the intent is aligned with the person making the request. When you specialize your own models—especially by narrowing the scope to a specific domain—you may have more room to improve this, because “intent” can take on a domain-specific meaning.

  • Transformers use self-attention mechanisms to process entire text sequences at once instead of word by word.
  • Self-supervised learning creates training labels automatically from text data without human annotation.
  • BERT models use only the encoder part of transformers for classification and prediction tasks.
  • GPT models use only the decoder part of transformers for text-generation tasks.
  • Word embeddings convert words into numerical vectors that capture semantic relationships.
  • RLHF uses reinforcement learning to improve large language model (LLM) responses based on human feedback.
  • LLMs can generate any symbolic content including code, math expressions, and structured data.
  • Open source LLMs reduce development costs by providing pretrained models as starting points.
  • Transfer learning adapts pretrained models to specific domains using domain-specific data.
  • Generalist LLMs risk data leakage when they’re deployed outside organizational networks.
  • Closed source models lack transparency about training data and model architecture.
  • Domain-specific LLMs provide better accuracy for specialized tasks than generalist models.
  • Smaller specialized models require less computational power than large generalist models.
  • Fine-tuning costs significantly less than training models from scratch.
  • Regulatory compliance often requires domain-specific models with known training data.