Skip to main content

What is a Singleton Design Pattern?

In programming, a Singleton is a design pattern that ensures a class has only one instance during the entire lifetime of a program, and provides a global access point to that instance.

Singleton is widely used when you want to control resource usage, like database connections, configurations, or loading a heavy machine learning model only once.

Why Use Singleton?

  • Efficient memory usage
  • Controlled access to a resource
  • Ensures consistency across your application

Simple Singleton Implementation in Python

class SingletonMeta(type):
    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            instance = super().__call__(*args, **kwargs)
            cls._instances[cls] = instance
        return cls._instances[cls]

class SingletonExample(metaclass=SingletonMeta):
    def __init__(self):
        print("Initializing SingletonExample")

# Usage
a = SingletonExample()
b = SingletonExample()

print(a is b)  # True

Here, no matter how many times you instantiate SingletonExample, it will always return the same object!

Real-World Example: Singleton for PyTorch Model Loading

In ML projects, model loading can be slow and memory-intensive. If your app tries to load a model multiple times — big performance issues! Using Singleton ensures only one copy is loaded and reused.

PyTorch Singleton Model Loader Example

import torch
import torch.nn as nn

class SingletonMeta(type):
    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            instance = super().__call__(*args, **kwargs)
            cls._instances[cls] = instance
        return cls._instances[cls]

class ModelLoader(metaclass=SingletonMeta):
    def __init__(self, model_path):
        self.model = self.load_model(model_path)

    def load_model(self, model_path):
        print(f"Loading model from {model_path}...")
        model = nn.Sequential(
            nn.Linear(10, 20),
            nn.ReLU(),
            nn.Linear(20, 1)
        )
        model.load_state_dict(torch.load(model_path, map_location="cpu"))
        model.eval()
        return model

    def predict(self, input_tensor):
        with torch.no_grad():
            return self.model(input_tensor)

# Usage Example
if __name__ == "__main__":
    loader1 = ModelLoader("model.pth")
    loader2 = ModelLoader("model.pth")

    print(f"loader1 is loader2: {loader1 is loader2}")

    dummy_input = torch.randn(1, 10)
    output = loader1.predict(dummy_input)
    print(f"Prediction: {output}")

Key Points

  • ModelLoader class loads the model only once.
  • loader1 and loader2 are the same object.
  • Efficient use of memory and faster prediction serving.

Sample Output

Loading model from model.pth...
loader1 is loader2: True
Prediction: tensor([[...]])

References

Final Tip

In production ML services (like APIs or edge devices): Load once, serve fast, and save memory. Singleton is critical for handling large models like BERT, ResNet, and other deep architectures.


Comments

Popular

Understanding SentencePiece: A Language-Independent Tokenizer for AI Engineers

In the realm of Natural Language Processing (NLP), tokenization plays a pivotal role in preparing text data for machine learning models. Traditional tokenization methods often rely on language-specific rules and pre-tokenized inputs, which can be limiting when dealing with diverse languages and scripts. Enter SentencePiece—a language-independent tokenizer and detokenizer designed to address these challenges and streamline the preprocessing pipeline for neural text processing systems. What is SentencePiece? SentencePiece is an open-source tokenizer and detokenizer developed by Google, tailored for neural-based text processing tasks such as Neural Machine Translation (NMT). Unlike conventional tokenizers that depend on whitespace and language-specific rules, SentencePiece treats the input text as a raw byte sequence, enabling it to process languages without explicit word boundaries, such as Japanese, Chinese, and Korean. This approach allows SentencePiece to train subword models di...

Mastering the Byte Pair Encoding (BPE) Tokenizer for NLP and LLMs

Byte Pair Encoding (BPE) is one of the most important and widely adopted subword tokenization algorithms in modern Natural Language Processing (NLP), especially in training Large Language Models (LLMs) like GPT. This guide provides a deep technical dive into how BPE works, compares it with other tokenizers like WordPiece and SentencePiece, and explains its practical implementation with Python code. This article is optimized for AI engineers building real-world models and systems. 1. What is Byte Pair Encoding? BPE was originally introduced as a data compression algorithm by Gage in 1994. It replaces the most frequent pair of bytes in a sequence with a single, unused byte. In 2015, Sennrich et al. adapted BPE for NLP to address the out-of-vocabulary (OOV) problem in neural machine translation. Instead of working with full words, BPE decomposes them into subword units that can be recombined to represent rare or unseen words. 2. Why Tokenization Matters in LLMs Tokenization is th...

Using Gemini API in LangChain: Step-by-Step Tutorial

What is LangChain and Why Use It? LangChain  is an open-source framework that simplifies the use of  Large Language Models (LLMs)  like OpenAI, Gemini (Google), and others by adding structure, tools, and memory to help build real-world applications such as chatbots, assistants, agents, or AI-enhanced software. Why Use LangChain for LLM Projects? Chainable Components : Easily build pipelines combining prompts, LLMs, tools, and memory. Multi-Model Support : Work with Gemini, OpenAI, Anthropic, Hugging Face, etc. Built-in Templates : Manage prompts more effectively. Supports Multi-Turn Chat : Manage complex interactions with memory and roles. Tool and API Integration : Let the model interact with external APIs or functions. Let's Walk Through the Code: Gemini + LangChain I will break the code into  4 main parts , each showcasing different features of LangChain and Gemini API. Part 1: Basic Gemini API Call Using LangChain import os from dotenv import load_dotenv load_dot...