🤖 AI/ML

Mamba

Mamba

A linear-complexity sequence model based on State Space Models. Drawing attention as an alternative to Transformers.

📖 Detailed Explanation

Mamba is a sequence model architecture based on the State Space Model (SSM) that is drawing attention as an alternative to the Transformer. It operates with linear time complexity (O(n)), solving the Transformer's quadratic complexity (O(n^2)) problem while achieving equal or superior performance.

It was published by Albert Gu and Tri Dao in December 2023. It introduced the Selective State Space to overcome the limitations of existing State Space Models (such as S4). This allows state transitions to be adjusted dynamically according to the input, so that, like the Transformer, it can selectively remember context.

Mamba's core innovations are twofold. First, the Selective SSM dynamically changes the A, B, and C matrices according to the input data. Second, the Hardware-aware Parallel Scan algorithm optimizes the GPU memory hierarchy, improving actual speed by 5x.

In practice, Mamba is promising in fields that require processing long sequences. Mamba-3B outperforms a Transformer of the same size and performs on par with one twice its size. Mamba-2 was released in 2024, enabling more efficient training, and commercialization is underway, including IBM's Bamba and NVIDIA's hybrid models.

💻 Code Example

# Mamba 모델 사용 예제 (mamba-ssm 라이브러리)
# pip install mamba-ssm causal-conv1d

import torch
from mamba_ssm import Mamba

# Mamba 블록 초기화
batch_size = 2
seq_len = 1024
d_model = 768  # 모델 차원

mamba_block = Mamba(
    d_model=d_model,        # 모델 차원
    d_state=16,             # SSM 상태 차원
    d_conv=4,               # 컨볼루션 커널 크기
    expand=2                # 확장 비율
).cuda()

# 입력 데이터 생성
x = torch.randn(batch_size, seq_len, d_model).cuda()

# Mamba 블록 순전파
y = mamba_block(x)
print(f"Input: {x.shape} -> Output: {y.shape}")
# Input: torch.Size([2, 1024, 768]) -> Output: torch.Size([2, 1024, 768])

# ============================================
# 사전학습된 Mamba 모델 사용 (HuggingFace)
# ============================================
from transformers import AutoTokenizer, MambaForCausalLM

model_name = "state-spaces/mamba-2.8b"

tokenizer = AutoTokenizer.from_pretrained(model_name)
model = MambaForCausalLM.from_pretrained(
    model_name,
    torch_dtype=torch.bfloat16,
    device_map="auto"
)

# 텍스트 생성
prompt = "Mamba is a new architecture that"
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)

outputs = model.generate(
    **inputs,
    max_new_tokens=50,
    do_sample=True,
    temperature=0.7,
    top_p=0.9
)

generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
print(f"\n생성된 텍스트:\n{generated_text}")

# 추론 속도 비교 (Transformer 대비 5배 빠름)
import time
long_input = torch.randn(1, 16384, d_model).cuda()  # 16K 시퀀스

start = time.time()
with torch.no_grad():
    _ = mamba_block(long_input)
print(f"16K 시퀀스 처리 시간: {time.time()-start:.3f}초")

🗣️ Say It Like This in Practice

💬 In a Meeting
"We are testing a Mamba-based model for long document analysis. With a 128K token context, inference is 5x faster than a Transformer, and memory usage is half. Performance is equivalent, so cost efficiency is much better."
💬 In an Interview
"Mamba uses a Selective State Space Model. Existing SSMs performed the same state transition regardless of the input, but Mamba dynamically adjusts the A, B, and C matrices according to the input, implementing a selective attention function like the Transformer."
💬 In a Technical Discussion
"Mamba-2 supports both SSM and Attention modes through the concept of State Space Duality. There are also research results showing that hybrid architectures (Mamba + Attention layers) perform better than pure Transformers or pure Mamba."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Assuming Mamba replaces the Transformer in all tasks

The Transformer still has the advantage in In-context Learning and complex reasoning. Mamba has particular strengths in long sequence processing.

✅
Choosing appropriate use cases

Mamba is suitable for tasks that require long sequences, such as DNA/genome analysis, audio processing, and long document summarization. For general NLP, consider hybrid models.

🔗 Related Terms

📚 Learn More