# Mamba: Linear-Time Sequence Modeling with Selective State Spaces

Mamba: 선택적 상태 공간을 이용한 선형 시간 시퀀스 모델링

Albert Gu, Tri Dao · arXiv · 2023년 12월 1일

- **연구 문제** Transformer의 어텐션은 강력하지만 문맥 길이에 따라 비용이 커지고, 기존 선형 시간 SSM은 언어처럼 내용에 따라 정보를 골라야 하는 데이터에서 약했습니다.
- **연구 방법** Mamba는 SSM의 Δ, B, C를 입력 함수로 만들어 정보를 선택적으로 전달하거나 잊게 하고, 상태를 GPU의 빠른 메모리에서만 펼치는 scan으로 계산합니다.
- **주요 결과** Selective Copying에서 선택 메커니즘을 넣은 모델은 99.8의 정확도를 보이고, Induction Heads에서는 학습 길이보다 4000배 긴 시퀀스까지 일반화했다고 보고합니다. 언어와 DNA, 오디오 실험에서는 같은 크기의 기준 모델과 비교해 경쟁력 있는 성능을 보입니다.

## Transformer의 효율 문제와 LTI SSM의 한계

Transformer는 대부분의 기반 모델에서 쓰이지만, 어텐션은 문맥 길이에 대해 제곱에 비례하는 비용을 가집니다. 그래서 선형 시간에 가까운 구조가 많이 제안되었으나 언어처럼 정보 밀도가 높은 이산 데이터에서는 어텐션만큼 성능을 내지 못했습니다.

구조화 상태 공간 모델(S4)은 연속 시스템을 이산화해 얻는 효율적인 시퀀스 모델입니다. 그러나 기존 구조화 SSM은 파라미터가 시간에 따라 바뀌지 않는 LTI 모델이었고, 그 때문에 입력 내용에 따라 정보를 고르는 능력이 부족합니다. 논문은 이 결함을 선택적 복사(Selective Copying)와 Induction Heads 같은 합성 과제로 보여 줍니다.

![Figure 2: (Left) The standard version of the Copying task involves constant spacing between input and output elements and is easily solved by time-invariant mo…](https://refivu.com/papers/b149783d-1b22-47f2-94df-544d57bb2621/figures/figure-f518fcc2eceac163139d64b9779d8128.png?thumb=512)

**Figure 2** : (Left) The standard version of the Copying task involves constant spacing between input and output elements and is easily solved by time-invariant models such as linear recurrences and global convolutions. (Right Top) The Selective Copying task has random spacing in between inputs and requires time-varying models that can selectively remember or ignore inputs depending on their content. (Right Bottom) The Induction Heads task is an example of associative recall that requires retrieving an answer based on context, a key ability for LLMs.

[원문](https://arxiv.org/abs/2312.00752v2) · [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) · Albert Gu, Tri Dao · Mamba: Linear-Time Sequence Modeling with Selective State Spaces · 원문 그림 인용 · 원본 PDF 6쪽에서 그림 영역을 추출했습니다.

이 문제는 입력 내용에 따라 달라지는 추론 능력과 긴 시퀀스에서의 계산 효율을 동시에 요구합니다. 논문은 이 두 요구를 함께 다루는 것을 연구 질문으로 삼습니다.

## 입력 의존 파라미터와 선택적 상태 전이

기존 S4는 Δ, A, B, C를 모든 시점에서 같은 값으로 두고 이산화합니다. 선택적 SSM은 B와 C를 입력 x\_t의 선형 투영으로 만들고, Δ는 입력에 따른 투영과 학습되는 편향을 더한 뒤 softplus를 거쳐 양수로 만듭니다. 이 변경으로 파라미터가 길이 축을 갖게 되어 모델은 시간 불변이 아니게 됩니다.

이산화는 Δ를 이용해 연속 파라미터를 이산 파라미터로 바꾸는 단계입니다. 논문은 ZOH 규칙에서 \\\\( \\\\bar{A} = \\\\exp(\\\\Delta A) \\\\)와 \\\\( \\\\bar{B} = (\\\\Delta A)^{-1}(\\\\exp(\\\\Delta A)-I)\\\\cdot \\\\Delta B \\\\)를 사용합니다. Δ가 입력에 따라 달라지므로 \\\\(\\\\bar{A}\\\\)와 \\\\(\\\\bar{B}\\\\)도 시점마다 달라집니다.

이 선택 장치가 게이트 RNN과 어떻게 이어지는지는 특수한 N=1, A=-1, B=1 경우로 보입니다. 이때 재귀는 \\\\\[ g\_t=\\\\sigma(\\\\mathrm{Linear}(x\_t)),\\\\quad h\_t=(1-g\_t)h\_{t-1}+g\_t x\_t \\\\\]로 쓰입니다. 즉 Δ가 입력을 얼마나 받아들이고 이전 상태를 얼마나 유지할지를 정합니다. 논문은 Δ를 가장 중요한 선택 파라미터로 보고, B와 C의 선택성은 입력 내용과 상태 내용에 따른 정보 흐름을 세밀하게 조절하는 역할로 설명합니다.

## 컨볼루션을 쓰지 못하는 계산을 위한 하드웨어 인식 scan

선택적 SSM은 입력마다 파라미터가 달라지므로 기존 SSM처럼 하나의 전역 컨볼루션 커널로 계산할 수 없습니다. 논문은 대신 병렬 scan으로 재귀를 계산합니다. 그러나 상태 텐서의 크기 (B, L, D, N)를 GPU HBM에 쓰면 메모리 입출력이 커지므로, 논문은 Δ, A, B, C를 HBM에서 SRAM으로 읽고 SRAM 안에서 이산화와 scan을 수행한 뒤 출력 (B, L, D)만 HBM에 씁니다.

역전파에 필요한 중간 상태는 저장하지 않고 역전파 때 다시 계산하는 재계산을 사용합니다. 이 설계는 상태 확장 계수 N만큼 줄이는 입출력 감소를 목표로 합니다. 논문은 이 scan이 표준 구현보다 빠르다는 측정을 보고하며, 그 수치는 아래 효율 실험 절에서 조건과 함께 다룹니다.

## H3와 MLP를 결합한 동질적 Mamba 블록

Mamba는 선택적 SSM을 여러 블록으로 쌓되 어텐션 블록과 별도의 MLP 블록을 두지 않습니다. 기존 H3 블록의 선형 투영, 합성곱, SSM 구조와 MLP의 게이트 구조를 하나로 합쳐, 한 종류의 블록을 반복하는 방식입니다. 블록의 입력 투영은 모델 차원 D를 확장 계수 E=2로 넓히며, 대부분의 파라미터는 선형 투영에 있고 SSM 파라미터는 상대적으로 작습니다.

활성화 함수로는 SiLU/Swish를 사용하고, 정규화 층과 잔차 연결을 블록 사이에 둡니다. 이 구조는 SwiGLU 형태의 게이트 MLP와 비슷한 특징을 갖습니다. 따라서 논문의 기여는 새로운 어텐션 대체 모듈보다는 선택적 SSM을 전체 네트워크의 기본 단위로 쓰는 설계에 있습니다.

## 합성 과제와 pre-training 실험에서의 검증

합성 과제에서 Selective Copying은 길이 4096 시퀀스와 16개 토큰 어휘로 수행됩니다. 논문의 Table 1에서 S4 기반 모델은 18.3의 정확도를 보이고, 선택 메커니즘만 추가한 S6 모델은 97.0입니다. Mamba 블록에 S6를 넣은 모델은 99.8의 정확도를 보고합니다. 즉 선택 메커니즘이 과제 해결의 핵심 요소로 나타납니다.

![Table 1: (Selective Copying.) Accuracy for combinations of architectures and inner sequence layers](https://refivu.com/papers/b149783d-1b22-47f2-94df-544d57bb2621/figures/figure-a9953b84649616cfac8b218be26b4a60.png?thumb=512)

**Table 1** : (Selective Copying.) Accuracy for combinations of architectures and inner sequence layers.

[원문](https://arxiv.org/abs/2312.00752v2) · [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) · Albert Gu, Tri Dao · Mamba: Linear-Time Sequence Modeling with Selective State Spaces · 원문 그림 인용 · 원본 PDF 11쪽에서 그림 영역을 추출했습니다.

Induction Heads는 길이 256에서 학습한 뒤 64부터 1048576까지 평가됩니다. 이 실험에서 Mamba는 학습 길이보다 4000배 긴 백만 길이 시퀀스까지 완전하게 일반화한다고 보고합니다. 반면 다른 방법은 2배를 넘는 길이에서 성능을 유지하지 못합니다.

언어 모델링에서는 Pile 데이터셋으로 약 125M부터 1.3B 파라미터까지 스케일링 실험을 수행하고, perplexity와 제로샷 평가를 비교합니다. Table 3에서 Mamba-1.4B는 평균 59.7, Pythia-2.8B는 59.1로 표시됩니다. 같은 표 기준으로 Mamba-2.8B는 평균 63.3으로 Pythia-6.9B의 61.7보다 높습니다. 초록은 이 모델을 Mamba-3B로 쓰고 표 3에서는 2.8B로 표기하므로, 두 표기가 같은 모델을 가리키는지 확인이 필요합니다.

![Figure 4: ( Scaling Laws.) Models of size ≈ 125𝑀 to≈ 1.3𝐵 parameters, trained on the Pile. Mamba scales better than all other attention-free models and is the…](https://refivu.com/papers/b149783d-1b22-47f2-94df-544d57bb2621/figures/figure-5e9825f4d4a52366504aab63872abb2a.png?thumb=512)

**Figure 4** : ( Scaling Laws.) Models of size ≈ 125𝑀 to≈ 1.3𝐵 parameters, trained on the Pile. Mamba scales better than all other attention-free models and is the first to match the performance of a very strong “Transformer++” recipe that has now become standard, particularly as the sequence length grows.

[원문](https://arxiv.org/abs/2312.00752v2) · [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) · Albert Gu, Tri Dao · Mamba: Linear-Time Sequence Modeling with Selective State Spaces · 원문 그림 인용 · 원본 PDF 11쪽에서 그림 영역을 추출했습니다.

![Table 3: (Zero-shot Evaluations.) Best results for each size in bold. We compare against open source LMs with various tokenizers, trained for up to 300B tokens…](https://refivu.com/papers/b149783d-1b22-47f2-94df-544d57bb2621/figures/figure-5ffda9d09982e8b90158f2d83cc082d5.png?thumb=512)

**Table 3** : (Zero-shot Evaluations.) Best results for each size in bold. We compare against open source LMs with various tokenizers, trained for up to 300B tokens. Pile refers to the validation split, comparing only against models trained on the same dataset and tokenizer (GPT-NeoX-20B). For each model size, Mamba is best-in-class on every single evaluation result, and generally matches baselines at twice the model size.

[원문](https://arxiv.org/abs/2312.00752v2) · [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) · Albert Gu, Tri Dao · Mamba: Linear-Time Sequence Modeling with Selective State Spaces · 원문 그림 인용 · 원본 PDF 12쪽에서 그림 영역을 추출했습니다.

DNA 실험에서는 HG38로 사전학습하며, 약 40M 파라미터에서 Mamba가 Transformer++와 HyenaDNA를 약 3배에서 4배 적은 파라미터로 맞춘다고 보고합니다. 문맥 길이를 늘리는 실험에서는 Mamba의 성능이 길이에 따라 개선되고, HyenaDNA는 길이가 길어질수록 나빠진다고 보고합니다.

![Figure 5: (DNA Scaling Laws.) Pretraining on the HG38 (human genome) dataset. (Left) Fixing short context length 210 = 1024 and increasing size from≈ 200𝐾 to≈…](https://refivu.com/papers/b149783d-1b22-47f2-94df-544d57bb2621/figures/figure-046290872e985995df39ba3e0f597ae8.png?thumb=512)

**Figure 5** : (DNA Scaling Laws.) Pretraining on the HG38 (human genome) dataset. (Left) Fixing short context length 210 = 1024 and increasing size from≈ 200𝐾 to≈ 40𝑀 parameters, Mamba scales better than baselines. (Right) Fixing model size and increasing sequence lengths while keeping tokens/batch and total training tokens fixed. Unlike baselines, the selection mechanism of Mamba facilitates better performance with increasing context length.

[원문](https://arxiv.org/abs/2312.00752v2) · [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) · Albert Gu, Tri Dao · Mamba: Linear-Time Sequence Modeling with Selective State Spaces · 원문 그림 인용 · 원본 PDF 13쪽에서 그림 영역을 추출했습니다.

오디오에서는 SaShiMi와 비교합니다. SC09 음성 생성에서 작은 Mamba 모델(6.1M)은 FID 0.94로 SaShiMi의 1.99보다 낮습니다. 이 결과들은 각각 다른 데이터, 평가 지표, 모델 크기에서 얻은 것이므로 하나의 공통 결과로 합칠 수 없습니다.

## 추론 처리량과 scan 속도 측정

효율 실험은 scan 연산과 End-to-end 추론을 나눠 측정합니다. 그림 8 캡션은 학습에서 효율적인 scan이 표준 구현보다 40배 빠르다고 보고하고, 본문은 PyTorch 표준 scan보다 20배에서 40배 빠르다고 설명합니다. 추론에서는 순환 모델로 실행해 Transformer보다 5배 높은 처리량을 낸다고 보고합니다. 본문의 4에서 5배 범위도 같은 효율 실험의 맥락에서 제시됩니다.

![Figure 8: (Efficiency Benchmarks.) (Left) Training: our efficient scan is 40× faster than a standard implementation. (Right) Inference: as a recurrent model, M…](https://refivu.com/papers/b149783d-1b22-47f2-94df-544d57bb2621/figures/figure-ffa357dbbe499c569f61d0cbb3a2320d.png?thumb=512)

**Figure 8** : (Efficiency Benchmarks.) (Left) Training: our efficient scan is 40× faster than a standard implementation. (Right) Inference: as a recurrent model, Mamba can achieve 5× higher throughput than Transformers.

[원문](https://arxiv.org/abs/2312.00752v2) · [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) · Albert Gu, Tri Dao · Mamba: Linear-Time Sequence Modeling with Selective State Spaces · 원문 그림 인용 · 원본 PDF 15쪽에서 그림 영역을 추출했습니다.

이 측정은 A100 80GB PCIe GPU에서 수행되며, 추론은 프롬프트 길이 2048과 생성 길이 128의 조건에서 측정됩니다. 어텐션 비교 대상은 인과 마스크가 적용된 FlashAttention-2입니다. 메모리 벤치마크에서는 125M 모델 기준으로 Mamba가 FlashAttention-2를 쓴 Transformer와 비슷한 메모리 사용량을 보입니다.

![Table 15: (Memory benchmark.) Mamba’s memory footprint is comparable to the most optimized Transformer. Results for 125M models](https://refivu.com/papers/b149783d-1b22-47f2-94df-544d57bb2621/figures/figure-cdd51469f035ce9068ecd1de38e8b98f.png?thumb=512)

**Table 15** : (Memory benchmark.) Mamba’s memory footprint is comparable to the most optimized Transformer. Results for 125M models.

[원문](https://arxiv.org/abs/2312.00752v2) · [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) · Albert Gu, Tri Dao · Mamba: Linear-Time Sequence Modeling with Selective State Spaces · 원문 그림 인용 · 원본 PDF 36쪽에서 그림 영역을 추출했습니다.

이 결과는 특정 GPU, 특정 배치 설정, 특정 모델 크기에서 얻은 측정입니다. 따라서 효율 우위가 모든 하드웨어와 모든 작업 부하에 일반화된다고 볼 수는 없습니다.

## 적용 범위와 남은 질문

이 논문의 기본 설정은 실수값 SSM입니다. 논문은 기본 초기화가 대부분의 과제에서 잘 작동하며 복소수 파라미터화가 항상 필요하지 않다고 보고합니다. 다만 오디오 실험 일부에서는 복소수 파라미터화를 사용했다고 명시합니다.

논문이 가장 분명하게 밝히는 한계는 규모입니다. 실험은 대형 오픈소스 LLM보다 작은 모델 크기에 머물고 있으며, 더 큰 규모에서 Mamba가 여전히 유리한지는 평가하지 못했다고 밝힙니다. 따라서 Transformer 기반 대형 모델과의 직접 비교는 이 논문의 범위 밖입니다.

## 논문 정보

- **저자**: Albert Gu, Tri Dao
- **학회·저널**: arXiv · 프리프린트
- **최초 공개일**: 2023년 12월 1일
- **등록일**: 2026년 10월 20일
- **수정일**: 2024년 5월 31일
- **버전**: v2
- **arXiv**: 2312.00752
- **분류**: cs.LG · cs.AI
- **원문 이용 조건**: [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/)
- **제공 범위**: 논문 정보, 해설, 허용된 원문 그림

[논문 원문 ↗](https://arxiv.org/abs/2312.00752v2) · [원문 PDF ↗](https://arxiv.org/pdf/2312.00752v2)

AI 해설은 논문 원문과 별개의 설명이며 오류가 있을 수 있습니다. 원문과 그림은 각 출처의 이용 조건과 따로 표시된 권리를 따릅니다.

## 초록

Foundation models, now powering most of the exciting applications in deep learning, are almost universally based on the Transformer architecture and its core attention module. Many subquadratic-time architectures such as linear attention, gated convolution and recurrent models, and structured state space models (SSMs) have been developed to address Transformers' computational inefficiency on long sequences, but they have not performed as well as attention on important modalities such as language. We identify that a key weakness of such models is their inability to perform content-based reasoning, and make several improvements. First, simply letting the SSM parameters be functions of the input addresses their weakness with discrete modalities, allowing the model to selectively propagate or forget information along the sequence length dimension depending on the current token. Second, even though this change prevents the use of efficient convolutions, we design a hardware-aware parallel algorithm in recurrent mode. We integrate these selective SSMs into a simplified end-to-end neural network architecture without attention or even MLP blocks (Mamba). Mamba enjoys fast inference (5$\\times$ higher throughput than Transformers) and linear scaling in sequence length, and its performance improves on real data up to million-length sequences. As a general sequence model backbone, Mamba achieves state-of-the-art performance across several modalities such as language, audio, and genomics. On language modeling, our Mamba-3B model outperforms Transformers of the same size and matches Transformers twice its size, both in pretraining and downstream evaluation.

## 원문 인용

Albert Gu, Tri Dao (2023). Mamba: Linear-Time Sequence Modeling with Selective State Spaces. arXiv:2312.00752v2. https://arxiv.org/abs/2312.00752v2

**BibTeX**

```
@misc{gu2023mamba,
  title = {{Mamba: Linear-Time Sequence Modeling with Selective State Spaces}},
  author = {Albert Gu and Tri Dao},
  year = {2023},
  eprint = {2312.00752},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2312.00752v2}
}
```

## 이 논문의 용어

- [Perplexity](https://refivu.com/terms/2b204e513801-perplexity)
- [트랜스포머](https://refivu.com/terms/515e8433c447-transformer)
- [Mamba](https://refivu.com/terms/cc8b7f3226dc-mamba)
- [Pile](https://refivu.com/terms/52bbdb3a0c68-pile)
- [Induction Heads](https://refivu.com/terms/9e3f59843a35-induction-heads)
- [Transformer++](https://refivu.com/terms/10aebc2cb100-transformer)
- [FlashAttention-2](https://refivu.com/terms/6f982d71439c-flashattention-2)
- [Selective Copying](https://refivu.com/terms/b79af2a7ed15-selective-copying)

## 다른 논문 해설

- [RWKV: Reinventing RNNs for the Transformer Era](https://refivu.com/papers/f86c302a-2e46-481a-b0a7-850579f6f3c8-rwkv-reinventing-rnns-for-the-transformer-era.md)
- [Highway Networks](https://refivu.com/papers/78251486-9138-48d8-a03c-8447a3433591-highway-networks.md)
- [Rethinking Attention with Performers](https://refivu.com/papers/be31745a-9080-4105-b177-3b88d23e4f59-rethinking-attention-with-performers.md)
- [Decision Transformer: Reinforcement Learning via Sequence Modeling](https://refivu.com/papers/386e76e8-fee6-4cba-84e8-0ef90a33b3b6-decision-transformer-reinforcement-learning-via-sequence.md)
- [Efficiently Modeling Long Sequences with Structured State Spaces](https://refivu.com/papers/9047ef9d-9e54-48f1-8609-ea4ce704605e-efficiently-modeling-long-sequences-with-structured-state.md)
- [Longformer: The Long-Document Transformer](https://refivu.com/papers/095aa21a-9a7f-4317-a80b-f961fdd4e423-longformer-the-long-document-transformer.md)
- [Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification](https://refivu.com/papers/83083238-3fc6-4f4e-a3b1-6db4f84268de-delving-deep-into-rectifiers-surpassing-human-level.md)
- [Direct Preference Optimization: Your Language Model is Secretly a Reward Model](https://refivu.com/papers/b96eaaaa-8c14-4a06-93bf-d13e70a14b14-direct-preference-optimization-your-language-model-is.md)
- [GShard: Scaling Giant Models with Conditional Computation and Automatic Sharding](https://refivu.com/papers/2481fdbe-b100-433d-877a-6976f982ccaa-gshard-scaling-giant-models-with-conditional-computation-and.md)
- [GLUE: A Multi-Task Benchmark and Analysis Platform for Natural Language Understanding](https://refivu.com/papers/a5e0caad-afbf-4fa4-b072-f6f5cab0c916-glue-a-multi-task-benchmark-and-analysis-platform.md)
- [Retentive Network: A Successor to Transformer for Large Language Models](https://refivu.com/papers/ca4ee5c6-87cf-427b-ae91-b593c10e0b48-retentive-network-a-successor-to-transformer-for-large.md)
- [Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks](https://refivu.com/papers/569bb9ab-8345-4766-a539-e7ffb7b1754e-retrieval-augmented-generation-for-knowledge-intensive-nlp.md)

---

AI 해설에는 오류가 있을 수 있습니다. [Refivu](https://refivu.com/papers/b149783d-1b22-47f2-94df-544d57bb2621-mamba-linear-time-sequence-modeling-with-selective-state)
