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 ...

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...

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...