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

Building an MCP Agent with UV, Python & mcp-use

Model Context Protocol (MCP) is an open protocol designed to enable AI agents to interact with external tools and data in a standardized way. MCP is composed of three components: server , client , and host . MCP host The MCP host acts as the interface between the user and the agent   (such as Claude Desktop or IDE) and plays the role of connecting to external tools or data through MCP clients and servers. Previously, Anthropic’s Claude Desktop was introduced as a host, but it required a separate desktop app, license, and API key management, leading to dependency on the Claude ecosystem.   mcp-use is an open-source Python/Node package that connects LangChain LLMs (e.g., GPT-4, Claude, Groq) to MCP servers in just six lines of code, eliminating dependencies and supporting multi-server and multi-model setups. MCP Client The MCP client manages the MCP protocol within the host and is responsible for connecting to MCP servers that provide the necessary functions for the ...

How to Save and Retrieve a Vector Database using LangChain, FAISS, and Gemini Embeddings

How to Save and Retrieve a Vector Database using LangChain, FAISS, and Gemini Embeddings Efficient storage and retrieval of vector databases is foundational for building intelligent retrieval-augmented generation (RAG) systems using large language models (LLMs). In this guide, we’ll walk through a professional-grade Python implementation that utilizes LangChain with FAISS and Google Gemini Embeddings to store document embeddings and retrieve similar information. This setup is highly suitable for advanced machine learning (ML) and deep learning (DL) engineers who work with semantic search and retrieval pipelines. Why Vector Databases Matter in LLM Applications Traditional keyword-based search systems fall short when it comes to understanding semantic meaning. Vector databases store high-dimensional embeddings of text data, allowing for approximate nearest-neighbor (ANN) searches based on semantic similarity. These capabilities are critical in applications like: Question Ans...

RF-DETR: Overcoming the Limitations of DETR in Object Detection

RF-DETR (Region-Focused DETR), proposed in April 2025, is an advanced object detection architecture designed to overcome fundamental drawbacks of the original DETR (DEtection TRansformer) . In this technical article, we explore RF-DETR's contributions, architecture, and how it compares with both DETR and the improved model D-FINE . We also provide experimental benchmarks and discuss its real-world applicability. RF-DETR Architecture diagram for object detection Limitations of DETR DETR revolutionized object detection by leveraging the Transformer architecture, enabling end-to-end learning without anchor boxes or NMS (Non-Maximum Suppression). However, DETR has notable limitations: Slow convergence, requiring heavy data augmentation and long training schedules Degraded performance on low-resolution objects and complex scenes Lack of locality due to global self-attention mechanisms Key Innovations in RF-DETR RF-DETR intr...