Why Long Context LLMs Slow Down (And How to Fix It w/ Sparse Attention)
▶ YouTube 원본01한국어 번역 · Korean
긴 컨텍스트 LLM이 느려지는 이유와 희소 어텐션(sparse attention)으로 해결하는 방법
원본: https://www.youtube.com/watch?v=cCDviC9B-q0 · 업로드: 2026-04-09 · 길이: 20m · 채널: Onchain AI Garage
왜 이 주제를 다루게 되었나
며칠 전 트위터에서 흥미로운 트윗 하나를 봤다. 그 트윗은 어떤 논문 한 편을 가리키고 있었는데, 바로 어텐션(attention)에 관한 것이었다. 마침 트랜스포머의 어텐션 헤드에 대한 강의를 막 마친 참이었기 때문에 곧바로 논문을 열어 깊이 파고들기 시작했다. 이 논문이 중요한 이유는, 대형 언어 모델(LLM)을 긴 컨텍스트 윈도우로 사용해 본 사람이라면 누구나 경험하는 고질적 문제를 정면으로 다루고 있기 때문이다.
최근 모델들은 128,000 토큰짜리 컨텍스트 윈도우를 흔히 지원하고, 프론티어 모델들은 100만 토큰까지도 다룬다. 그러나 일정 길이를 넘어서면 속도가 급격히 느려지고 품질 자체도 눈에 띄게 나빠진다. 이는 단순한 불편함이 아니라 구조적인 병목이다. 그래서 오늘은 어텐션이라는 개념을 처음부터 되짚고, 이 논문의 아이디어를 실제 모델에 이식해 속도와 품질이 어떻게 변하는지 직접 실험해 본 결과를 공유하려 한다. 마지막에는 오픈소스로 공개한 도구까지 소개한다.
어텐션이란 무엇인가
언어 모델이 텍스트를 읽을 때, 각 단어는 다른 어떤 단어가 자신과 관련이 있는지 결정해야 한다. 이 과정이 바로 어텐션(attention)이다. 마치 사람들로 가득 찬 방에서 질문을 던지고, 누가 쓸 만한 정보를 가졌는지 둘러보며 판단하는 것과 비슷하다. 트랜스포머(Transformer)는 이 메커니즘을 통해 이전 단어들을 하나하나 살펴보며 어디에 귀를 기울일지 결정한다.
간단한 예로 “The cat sat on the mat and it purred”라는 문장을 생각해 보자. “it”이라는 단어는 무엇을 가리키는가? 모델은 뒤로 거슬러 올라가며 “cat”을 찾아야 한다. “purred”는 “cat”, “it”, “mat” 등과 연결된다. 핵심은 각 단어가 바로 옆 단어뿐 아니라 앞에 등장한 모든 단어를 일일이 확인한다는 점이다. 짧은 문장에서는 문제가 없다. 그러나 긴 텍스트에서는 이 성질이 치명적인 비용이 된다.
긴 컨텍스트의 근본 병목
10개 단어 정도면 10명을 확인하면 되지만, 128,000 단어라면 매 단어마다 128,000명을 모두 확인해야 한다. Qwen 3B 파라미터 모델에서 실측해 본 결과, 128,000 토큰 상황에서 어텐션 레이어 하나가 12~26 밀리초를 소비했다. 36개 레이어를 곱하면 어텐션 단계에만 거의 1초가 날아간다. 게다가 비용은 입력 길이에 대해 이차(quadratic)로 증가한다. 입력이 두 배가 되면 연산은 네 배가 된다. 이것이 긴 컨텍스트 LLM의 근본적인 병목이다.
기존 접근들: MHA, GQA, 플래시 어텐션
가장 초기 형태는 MHA(Multi-Head Attention), 즉 다중 헤드 어텐션이다. GPT-2, GPT-3, LLaMA 1 등이 사용한 이 방식에서는 각 헤드가 서로 다른 패턴을 찾는 병렬 작업자처럼 동작하며, 각자 독립된 키(key)와 값(value) 메모리를 가진다. 동작은 잘 되지만 메모리를 엄청나게 소모한다.
GQA(Grouped Query Attention, 그룹화 쿼리 어텐션)는 LLaMA 3, Qwen 2.5, Mistral 등 대다수 최신 모델이 채택한 방식이다. 모든 헤드에 메모리를 분리하지 않고, 여러 헤드 그룹이 같은 키/값 메모리를 공유한다. 예를 들어 Qwen 2.5는 28개의 쿼리 헤드가 있지만 키/값 헤드는 단 4개다. 즉, 쿼리 헤드 7개마다 하나의 키/값 메모리 세트를 공유한다. 품질을 거의 유지하면서 메모리 풋프린트를 극적으로 줄인다.
플래시 어텐션(Flash Attention)은 아키텍처 변경이 아니라 속도 최적화다. 동일한 결과를 더 빠르게 낼 뿐이다. 대부분의 최신 모델이 이 구현을 사용한다. 그러나 이 모든 기법은 한 가지 문제를 해결하지 못한다. 여전히 모든 단어가 모든 단어를 확인한다는 점이다. 메모리를 줄이고 연산을 가속화해도 이차 스케일링 자체는 남는다.
DSA: 딥시크의 희소 어텐션
그렇다면 관련 없는 단어를 아예 건너뛸 수는 없을까? 이것이 바로 딥시크(DeepSeek)가 V3 모델에서 시도한 DSA(Dynamic Sparse Attention, 동적 희소 어텐션)다. 논문에서는 딥시크 희소 어텐션(DeepSeek Sparse Attention)이라고도 부른다.
DSA의 아이디어는 “먼저 모두를 빠르게 훑고, 관련 있는 대상에만 본격적으로 집중한다”이다. 비유하자면 스피드 데이팅 같은 것이다. 방 안의 모든 사람과 긴 대화를 나누는 대신, 5초짜리 빠른 스캔으로 기본 조건을 확인한 뒤, 유망한 상대하고만 오래 이야기하는 식이다. 실제 구현에서는 각 단어가 컨텍스트의 모든 키에 대해 가벼운 점곱(dot product)으로 유사도 점수를 계산하고, 상위 소수만 선택해 완전한 어텐션을 수행한다.
그러나 여기에는 함정이 있다. 관련 토큰을 “고르기 위해” 여전히 전체 토큰을 한 번씩 훑어야 한다. 128,000 토큰 상황이라면 이 스캔 단계만으로도 레이어당 12~26 밀리초가 든다. 어텐션 연산은 가벼워졌지만, 선택 단계는 여전히 전체를 건드린다.
HISA: 계층적 인덱스 희소 어텐션
이 지점을 공격하는 것이 바로 HISA(Hierarchical Indexed Sparse Attention, 계층적 인덱스 희소 어텐션)다. 아이디어는 직관적이다. 방(문장)은 이미 섹션들로 구성되어 있다. 그러면 개개인을 다 면접하는 대신, 먼저 각 섹션에 “여기 이 주제를 아는 사람 있어요?”라고 묻는 편이 훨씬 빠르다.
HISA는 토큰을 128개씩 블록으로 묶는다. 128,000 토큰이라면 약 1,000개 남짓의 블록 요약으로 압축된다. 1단계에서는 이 블록 요약들에 점수를 매겨 중요한 블록만 선택하고, 나머지는 아예 스캔조차 하지 않는다. 2단계에서는 선택된 블록 내부에서 토큰 단위로 점수를 매겨 상위 후보를 고른다. 결과적으로 약 1,000개의 블록 점수와 8,000여 개의 토큰 점수, 총 9,000여 회의 연산만으로 선택이 끝난다. DSA의 128,000 회와 비교하면 압도적으로 적다.
논문 결과와 내 실험
원 논문은 딥시크 V3와 GLM 5를 대상으로 2~4배의 토큰 선택 가속을 보고했다. 커스텀 퓨즈드 GPU 커널을 사용했고, 품질 손실은 사실상 없었으며 재학습도 필요 없었다. 즉 DSA의 완전한 플러그 앤 플레이 교체다.
연구진의 장비는 매우 고급이었지만, 나는 RTX 3060이 장착된 평범한 소비자용 PC에서 같은 철학을 재현해 보고 싶었다. 계획은 Qwen 2.5 3B 스톡 모델의 GQA 어텐션 레이어에 HISA를 “볼트온(bolt on)“하는 것이었다. 모델이 평소처럼 Q, K, V를 투영하게 놔두되, 그 직후에 내가 개입해 HISA 블록 스코어링을 키(key)에 적용하고, 선택된 블록만 모아 작은 텐서를 만든 뒤 그 위에서만 어텐션을 계산했다. 외부에서 model.generate를 호출하는 방식은 전혀 바뀌지 않고, 내부에서 많은 연산을 건너뛴다.
시행착오들
솔직히 말하면 한 번에 되지는 않았다. 첫째, 텍스트 샘플을 짧은 반복문으로 썼더니 모든 블록이 똑같이 생겼고, HISA가 고를 거리가 없었다. 그래서 “오만과 편견(Pride and Prejudice)” 같은 실제 장편 소설로 교체했다. 둘째, 선택 블록 수를 전체 블록 수와 같게 설정해 HISA가 모든 블록을 선택하는 바람에 완벽한 정확도가 나왔지만 아무 의미가 없었다. 파라미터를 제대로 스케일링해 해결했다. 셋째, 어텐션 백엔드가 메모리 비효율적이어서 32,000 토큰을 넘기지 못했다. 메모리 효율이 좋은 백엔드로 교체한 뒤에야 정상적으로 테스트가 가능해졌다. 중간에 컴퓨터가 여러 번 뻗은 것은 덤이다.
속도 측정 결과
이후 DSA의 전체 스캔과 HISA의 블록 스캔을 비교했다. 64,000 컨텍스트에서는 최대 2배 정도 차이였다. 그러나 128,000 컨텍스트에서는 차이가 본격적으로 벌어졌다. DSA는 2.4 밀리초에서 26 밀리초로 급증한 반면, HISA는 거의 일정한 수준을 유지했다. 가속비는 약 7~14배에 달했다. 선택되는 블록 수가 컨텍스트 길이와 무관하기 때문에, 입력이 아무리 길어져도 스코어링 비용은 거의 그대로다. 100만 토큰급 컨텍스트라면 격차는 더 벌어질 것이다.
품질 측정 결과
속도가 아무리 빨라도 생성 품질이 무너지면 의미가 없다. 그래서 퍼플렉서티(perplexity)로 품질을 측정했다. 퍼플렉서티는 모델이 다음 단어를 얼마나 잘 예측하는지 나타내는 표준 지표이며, 낮을수록 좋다. Qwen 2.5 기본(dense) 어텐션은 19.68, HISA 적용 버전은 18.67로 오히려 약간 더 나았다. 검증 삼아 랜덤 희소 어텐션을 돌려 봤더니 점수가 크게 망가져서, HISA의 효과가 단순한 무작위 성과가 아님을 확인했다.
흥미로운 점은 HISA가 약간이나마 더 좋은 점수를 냈다는 것이다. 이는 기존 연구에서도 관찰된 현상이다. 모델이 모든 토큰에 주의를 분산하면 어텐션 가중치가 수천 개의 무관한 토큰에 얇게 퍼진다. 더 적고 더 관련 있는 토큰에 집중하도록 강제하면 신호 대 잡음비(SNR)가 개선된다. 오디오에서 배경 소음을 걷어내는 것과 같은 이치다.
LLaMA 교차 검증
Qwen에만 통하는 결과인지 확인하기 위해 LLaMA 3.2 3B Instruct에도 동일한 실험을 돌렸다. 이 모델 역시 128K 컨텍스트와 GQA 어텐션을 사용한다. 베이스라인 퍼플렉서티는 19.51이었고, HISA 50% 설정에서는 19.95였다. Qwen에서는 살짝 개선, LLaMA에서는 살짝 악화였지만, 둘 다 품질 격차는 크지 않았다. 랜덤 희소 어텐션의 417 같은 폭주에 비하면 사실상 무시할 만한 수준이다.
속도 테스트에서도 후반 레이어에서 최대 4배 가속이 관찰되었고, 이는 Qwen의 경향과 일치했다. 즉, 이 접근은 특정 모델에만 통하는 트릭이 아니라 GQA 기반 모델 일반에 적용 가능한 철학이다.
PyTorch 플러그인과 전체 포워드 패스 결과
이어서 이 아이디어를 임의의 GQA 모델에 볼트온할 수 있는 플러그인으로 만들었다. CUDA 커스텀 커널 없이 순수 파이토치(PyTorch) 약 300줄이다. 교차 레이어 예측(cross-layer prediction)으로 40%, 적응형 희소성(adaptive sparsity)으로 추가 11% 속도를 끌어올렸다. 코드는 Tombi Studio GitHub의 HISA-Pytorch 저장소에 공개했다. 프로덕션 릴리스가 아니라 실험 단계임을 강조한다.
전체 모델 포워드 패스(어텐션 선택뿐 아니라 투영, 피드포워드까지 전부 포함) 기준으로 Qwen 2.5 3B에서 4,000 컨텍스트는 2.3배, 8,000 컨텍스트는 9.3배 빨랐다. 더 흥미로운 것은 16,000과 32,000 컨텍스트에서는 스톡 버전이 12 GB GPU 메모리를 초과해 아예 크래시한 반면, HISA 플러그인을 켠 쪽은 끝까지 돌았다는 점이다. 이 방법은 단순히 빠르게 만드는 것을 넘어, 물리적으로 다루지 못하던 컨텍스트 길이를 다룰 수 있게 해 준다. 전부 순수 파이토치, 윈도우 환경, 소비자용 GPU에서 돌아간 결과다.
결론과 앞으로
정리하면, HISA는 실제로 동작한다. 긴 컨텍스트에서 눈에 띌 만한 품질 손실 없이 속도를 끌어올린다. 다만 개선의 여지는 아직 많다. 플래시 어텐션 기반 퓨즈드 GPU 커널 도입, 생성 중 KV 캐시 에빅션(eviction), vLLM 같은 프로덕션 추론 엔진과의 통합, 더 큰 GPU에서의 장(long) 컨텍스트 검증 등이 다음 과제다. 앞으로 등장할 모델의 컨텍스트 윈도우는 계속 커질 것이고, 로컬 LLM이 긴 컨텍스트를 실용적으로 다루려면 이런 가속 기법이 필수가 될 것이다.
어텐션 방식에 대한 여러분의 생각이 궁금하다. 희소 어텐션 연구 동향을 어떻게 보고 있는지, 댓글로 남겨 주시면 좋겠다.
02리서치 문서 · Document
긴 컨텍스트 LLM은 왜 느려지는가: 희소 어텐션과 HISA가 여는 새로운 지평
원본 영상: YouTube · 업로드: 2026-04-09 · 채널: Onchain AI Garage
서론: 100만 토큰 시대의 역설
LLM의 컨텍스트 윈도우 경쟁은 이미 100만 토큰을 넘어섰다. 그러나 역설적이게도, 컨텍스트가 길어질수록 모델은 느려지고 때로는 품질마저 나빠진다. 128K, 256K, 1M 토큰이라는 숫자가 마케팅 카피에는 멋지게 쓰이지만, 실제로 해당 길이를 꽉 채워 사용해 본 개발자라면 체감한다. 생성 속도는 급격히 떨어지고, 모델은 중간 어딘가의 정보를 놓치기 시작하며, GPU 메모리는 쉽게 터진다.
이 문제의 뿌리는 트랜스포머(Transformer)의 어텐션(attention) 메커니즘이 입력 길이에 대해 이차(O(n²)) 복잡도를 갖는다는 점에 있다. 토큰이 두 배가 되면 연산은 네 배가 된다. 이는 단순한 최적화로 감출 수 있는 수준의 문제가 아니라 구조적인 병목이다. Onchain AI Garage의 최근 실험 영상은 바로 이 병목을 “희소 어텐션(sparse attention)“이라는 아이디어로 공격한다. 구체적으로는 2026년에 공개된 HISA(Hierarchical Indexed Sparse Attention) 논문의 철학을 소비자용 RTX 3060 한 대 위에서 재현해 본 결과를 공유한다.
이 글은 영상의 핵심 아이디어를 정리하고, 관련 학계/산업계 흐름을 교차 검증한 뒤, 더 깊이 파고들고 싶은 독자를 위한 자료를 모아 두는 것을 목표로 한다.
본론
1. 어텐션과 이차 병목(quadratic bottleneck)
어텐션은 한마디로 “각 토큰이 이전의 어떤 토큰에 주의해야 하는지 결정하는” 과정이다. “고양이가 매트 위에 앉아 있고 그것이 울었다”는 문장에서 “그것”은 “고양이”를 가리킨다. 이런 의존 관계를 찾아내려면 각 토큰이 앞선 모든 토큰과의 유사도를 계산해야 한다. 토큰이 10개면 100번, 128,000개면 약 164억 번의 연산이 필요하다. 이것이 바로 이차 스케일링이 실전에서 치명적인 이유다.
영상에서 측정한 수치는 이 문제의 구체성을 잘 보여준다. Qwen 3B 파라미터 모델에서 128K 컨텍스트 기준, 어텐션 레이어 하나가 12~26 밀리초를 소비한다. 레이어가 36개이니 단일 순전파의 어텐션 비용만 1초에 육박한다. 대화형 응답 속도를 기대하는 사용자 입장에서는 이미 실용성을 잃은 수준이다.
2. MHA, GQA, 플래시 어텐션: 이차 병목은 풀지 못한다
지금까지 등장한 주요 어텐션 개선은 크게 세 갈래다.
- MHA(Multi-Head Attention, 다중 헤드 어텐션): GPT-2, GPT-3, LLaMA 1 등이 사용한 초기 형태. 각 헤드가 독립된 키/값 메모리를 갖는다. 품질은 좋지만 메모리 사용이 크다.
- GQA(Grouped Query Attention, 그룹화 쿼리 어텐션): LLaMA 3, Qwen 2.5, Mistral 등 최신 대부분이 사용한다. 여러 쿼리 헤드가 같은 키/값 메모리를 공유해 메모리를 크게 절감한다. 예컨대 Qwen 2.5는 쿼리 헤드 28개에 키/값 헤드 4개, 즉 7:1 공유다.
- 플래시 어텐션(Flash Attention): 결과는 정확히 동일하지만 메모리 접근 패턴과 커널 퓨전(kernel fusion)을 이용해 연산 속도를 끌어올린다. 수학적 변화가 아니라 시스템 최적화다.
이 세 가지 모두 결국 “모든 토큰이 모든 토큰을 본다”는 대전제를 유지한다. 메모리 풋프린트는 줄고 연산은 빨라지지만, 이차 스케일링 자체는 그대로 남는다. 세바스찬 라슈카(Sebastian Raschka)의 어텐션 변형 시각 가이드는 이러한 변형들을 한눈에 비교해 준다.
3. DSA: 딥시크의 희소 어텐션과 그 한계
진정한 의미의 탈출은 “관련 없는 토큰은 아예 건너뛴다”는 아이디어에서 나온다. 딥시크(DeepSeek)는 V3.2 모델에서 DSA(DeepSeek Sparse Attention, 딥시크 희소 어텐션)를 도입했다. 각 쿼리가 모든 키에 대해 가벼운 인덱서(indexer)로 점수를 매긴 뒤, 상위 몇백 개에만 본격적인 어텐션을 수행하는 구조다.
효과는 극적이다. vLLM과 Red Hat AI의 DeepSeek-V3.2-Exp 지원 분석은 긴 컨텍스트 추론에서 DSA가 어떻게 실전 속도를 끌어올리는지 보여준다. SGLang의 Day 0 지원 글 또한 같은 모델을 다루며, DSA가 단순한 연구 프로토타입이 아니라 상용 추론 스택에 바로 통합되고 있음을 말해 준다.
그러나 DSA에는 함정이 있다. 상위 토큰을 “고르려면” 여전히 모든 토큰을 한 번은 훑어야 한다. 어텐션 연산은 줄었지만, 선택(selection) 단계가 새로운 이차 병목이 된 셈이다. 영상에서 측정한 대로 128K 컨텍스트에서는 이 선택 단계만으로 레이어당 12~26 밀리초가 소모된다. 연구자들은 이 인덱서 비용을 어떻게 줄일지 고민하기 시작했고, 그 흐름 위에 HISA가 등장한다.
4. HISA: 블록으로 먼저 본다
HISA(Hierarchical Indexed Sparse Attention) 논문의 핵심 아이디어는 단순하다. “개개인을 다 면접하는 대신 먼저 부서별로 물어본다.” 토큰 128개씩을 하나의 블록으로 묶고, 각 블록의 풀링된 대표 벡터에 대해 점수를 매긴다. 128K 토큰이라면 약 1,000개의 블록 점수를 계산하면 된다. 스코어가 낮은 블록은 아예 버려지고, 선택된 소수의 블록 내부에서만 토큰 단위 정밀 스코어링이 이어진다.
결과적으로 선택 단계의 연산량은 DSA의 128,000회에서 HISA의 약 9,000회로 줄어든다. 논문은 DeepSeek V3.2와 GLM 5의 기존 인덱서를 HISA로 그대로 교체해도 품질 저하 없이 32K에서 2배, 128K에서 4배의 속도를 얻었다고 보고한다. 특히 HISA가 선택한 토큰 집합과 원래 DSA가 선택했을 토큰 집합의 IoU(Intersection-over-Union)가 평균 99% 이상이라는 점이 인상적이다. 즉 HISA는 “거의 같은 것을 훨씬 싸게 찾는다.”
베이스텐(Baseten)의 GLM 5 API 고속화 블로그는 DSA 기반 커스텀 커널이 긴 컨텍스트에서 KV 캐시 비용을 어떻게 줄이는지 실전 사례로 보여주며, HISA 같은 후속 연구가 왜 자연스럽게 같은 계보 위에서 작동하는지를 이해할 단서를 제공한다.
5. 소비자용 GPU에서의 재현: 3x에서 9x까지
영상의 백미는 학계의 아이디어를 평범한 RTX 3060 환경에서 재현해 본 실험이다. Qwen 2.5 3B의 GQA 어텐션 레이어에 HISA를 볼트온(bolt-on)하는 방식으로, 모델의 Q/K/V 투영 직후에 HISA 블록 스코어링을 끼워 넣고 선택된 블록에만 어텐션을 계산했다. 순수 파이토치(PyTorch) 300줄, CUDA 커스텀 커널 없음, 윈도우 환경, 소비자용 12 GB GPU에서의 결과다.
- 속도(인덱서 단계): 64K에서 최대 2배, 128K에서 7~14배 가속.
- 품질(퍼플렉서티, perplexity): Qwen 2.5 기준 dense 19.68 vs HISA 18.67로 오히려 살짝 개선. LLaMA 3.2 3B 기준 19.51 vs 19.95로 살짝 악화. 두 경우 모두 차이는 무시할 만한 수준.
- 전체 포워드 패스: 4K 컨텍스트 2.3배, 8K 컨텍스트 9.3배. 16K/32K에서는 스톡 모델이 GPU 메모리 부족으로 크래시했으나 HISA 버전은 완주.
품질이 오히려 개선되는 현상은 의외지만 선행 연구에서도 관찰된 패턴이다. 어텐션 가중치가 수천 개의 무관한 토큰에 얇게 퍼지면 신호 대 잡음비(SNR)가 나빠진다. 더 적고 관련 높은 토큰에 집중을 “강제”하면 오히려 예측이 또렷해진다. 이는 희소 어텐션이 단순한 속도 트릭이 아니라, 긴 컨텍스트 환경에서 모델의 주의 할당 구조를 개선할 가능성을 시사한다.
핵심 인사이트
- 이차 병목은 두 단계로 쪼개진다. 기존 최적화는 “어텐션 연산 비용” 쪽만 공격했고, DSA는 여기에 “선택” 단계를 추가했다. HISA는 그 선택 단계 자체가 새로운 병목임을 지적하고 계층화(hierarchy)로 공격한다. 문제를 두 층으로 나눠 보면 해결 아이디어의 지형이 훨씬 명료해진다.
- 희소 어텐션은 속도와 품질을 동시에 노릴 수 있다. 무관한 토큰을 쳐내는 것은 단순한 비용 절감이 아니라 주의의 집중도를 높이는 일이기도 하다. NSA 계열 연구는 이 점을 훈련 시점부터 활용해 품질까지 개선한다.
- 플러그 앤 플레이(plug-and-play)가 중요하다. HISA 논문과 이 영상의 실험 모두 “재학습 없이 기존 모델에 꽂기만 하면 된다”는 점을 강조한다. 이는 연구가 바로 제품에 반영될 수 있는 길이며, 실험 단계에서 재현을 쉽게 만드는 결정적 요소다.
- 속도만큼이나 메모리 한계의 해제가 중요하다. HISA 덕분에 기존에는 OOM으로 돌릴 수 없던 16K, 32K 컨텍스트가 12 GB GPU에서 돌아갔다. 로컬 LLM의 실용 영역 자체가 넓어지는 효과다.
- 표준 벤치마크는 여전히 필요하다. Qwen에서는 개선, LLaMA에서는 미세 악화라는 결과는 퍼플렉서티 외에 Needle-in-a-Haystack, LongBench 같은 긴 컨텍스트 전용 평가가 함께 가야 한다는 점을 상기시킨다.
더 알아보기
- HISA: Efficient Hierarchical Indexing for Fine-Grained Sparse Attention (arXiv) — 영상이 다룬 원 논문. 블록 단위 1단계 필터링과 토큰 단위 2단계 정제의 구조, DeepSeek V3.2/GLM 5에서의 직접 교체 실험 결과가 정리되어 있다.
- Native Sparse Attention: Hardware-Aligned and Natively Trainable Sparse Attention (arXiv) — 딥시크의 NSA 논문. 압축/선택/슬라이딩 윈도우 3단 병렬 어텐션을 제안하며, 훈련 시점부터 희소성을 반영하는 방향을 보여준다.
- A Visual Guide to Attention Variants in Modern LLMs (Sebastian Raschka) — MHA, MQA, GQA, MLA, 그리고 희소 계열을 시각적으로 비교해 전체 지형을 잡는 데 유용하다.
- DeepSeek-V3.2-Exp on vLLM, Day 0 (Red Hat Developer) — DSA가 프로덕션 추론 스택에 어떻게 통합되는지 실전 관점에서 설명한다.
- SGLang Day 0 Support for DeepSeek-V3.2 with Sparse Attention (LMSYS Blog) — 또 다른 서빙 엔진 관점에서 DSA를 다루며, HISA 같은 후속 연구가 어디에 꽂힐 수 있는지 엿볼 수 있다.
- How we built the fastest GLM 5 API (Baseten) — DSA 커스텀 커널을 활용해 긴 컨텍스트의 KV 캐시 비용을 줄인 실무 사례.
03찬반 토론 · Debate
토론: “희소 어텐션(sparse attention)은 긴 컨텍스트 LLM의 근본 병목을 실제로 해결한다”
논제: HISA/DSA 같은 희소 어텐션 기법이 긴 컨텍스트 LLM의 속도-품질 트레이드오프를 근본적으로 해소하는 올바른 방향인가?
Round 1
🟢 Pro — “희소 어텐션은 이차 병목을 부수는 가장 현실적인 길이다”
희소 어텐션에 찬성하는 첫 번째 이유는 문제 정의의 정확성이다. 트랜스포머의 이차 복잡도는 긴 컨텍스트 시대의 근본 병목이며, 플래시 어텐션이나 GQA(Grouped Query Attention)는 이를 “완화”할 뿐 “해제”하지 못한다. DSA(DeepSeek Sparse Attention)와 HISA는 “모든 토큰이 모든 토큰을 본다”는 전제를 처음으로 제거한다. 128K 컨텍스트에서 HISA가 DSA 대비 24배, 영상 실험에서는 714배의 인덱서 가속을 낸다는 결과는 이 전환이 이론이 아니라 수치로 증명됨을 보여준다.
두 번째 이유는 품질이 함께 개선될 여지가 크다는 점이다. 영상 실험에서 Qwen 2.5의 퍼플렉서티(perplexity)가 19.68에서 18.67로 오히려 낮아진 것은 우연이 아니다. 어텐션 가중치가 수천 개의 무관한 토큰에 얇게 퍼지면 신호 대 잡음비가 나빠진다. 희소 어텐션은 관련 있는 소수에 주의를 “강제 집중”시켜 예측을 또렷하게 만든다. 즉, 속도와 품질이 상반된 목표가 아니라 같은 방향의 목표일 수 있다.
세 번째 이유는 실전 적합성이다. HISA 논문은 DeepSeek V3.2와 GLM 5의 기존 인덱서를 재학습 없이 교체해 성능을 유지했다. 이 영상의 실험자는 RTX 3060 한 대와 순수 파이토치 300줄로 유사 결과를 재현했다. 학계-산업계-개인 개발자가 같은 아이디어 위에서 수렴한다는 사실 자체가 기술적 성숙도의 신호다.
🔴 Con — “희소 어텐션의 속도는 특정 태스크에서 품질을 팔아 산 것이다”
반대편에서 보면 이야기가 다르다. 희소 어텐션의 첫 번째 약점은 “무엇이 관련 있는가”를 싸게 판단해야 한다는 모순이다. 정밀 검색이나 다단계 추론처럼 약한 단서가 먼 곳에 흩어져 있는 태스크에서는, 블록 단위의 거친 필터링이 정답에 해당하는 토큰을 통째로 버릴 위험이 있다. The Sparse Frontier 논문(arXiv:2504.17768)과 Long-Context Generalization with Sparse Attention(arXiv:2506.16640)은 동일 모델에서도 희소성 수준에 따라 검색 태스크가 급격히 무너지는 사례를 보고한다. 특정 벤치마크에서는 정확도가 -20%p, -25%p씩 떨어지기도 한다. 퍼플렉서티는 평균적인 다음 토큰 예측을 측정할 뿐, 긴 컨텍스트에서 진짜로 중요한 “정확한 리콜”을 측정하지 못한다.
두 번째 약점은 평가의 편향이다. 영상의 실험은 “오만과 편견” 같은 자연어 연속 텍스트로 퍼플렉서티를 측정했다. 이는 희소 어텐션에 유리한 벤치마크다. 문학 텍스트는 국소적 맥락 의존성이 강해 블록 단위 선택이 잘 통한다. 하지만 코드 저장소, 법률 문서, 긴 회의록처럼 원거리 참조가 핵심인 태스크에서는 결과가 전혀 다를 수 있다. Needle-in-a-Haystack, LongBench, SharedContextBench 같은 전용 평가가 빠진 결론은 과대포장이다.
세 번째 약점은 일반화의 한계다. LLaMA 3.2에서는 퍼플렉서티가 살짝 악화되었다(19.51 → 19.95). 작은 차이지만 방향성은 일관되지 않는다. “모델에 따라 다르다”는 말은 곧 실무에서 케이스별 튜닝이 필요하다는 뜻이고, 이는 플러그 앤 플레이(plug-and-play)라는 주장과 충돌한다. 로컬 사용자가 매번 하이퍼파라미터를 고쳐야 한다면 이는 병목 해결이 아니라 병목 이동이다.
Round 2
🟢 Pro (재반론) — Con의 반론에 대하여
먼저 Con의 첫째 주장, 즉 “블록 단위 필터링이 원거리 단서를 버릴 수 있다”는 지적에 답하겠다. 이 우려는 실제 연구 결과로 상당 부분 반박된다. HISA 논문은 HISA가 선택한 토큰 집합과 원래 DSA가 선택했을 토큰 집합의 IoU(Intersection-over-Union)가 모든 레이어와 컨텍스트 길이에서 평균 99%를 넘었다고 보고했다. 즉 HISA는 DSA가 고를 토큰을 “거의 그대로” 고르면서 훨씬 싸게 고른다. Con이 인용한 정확도 급락 사례는 “정적(static) 희소 패턴” 혹은 “공격적 KV 캐시 영구 퇴거(eviction)” 연구에서 나온 것이며, 동적 쿼리 기반 선택을 하는 DSA/HISA 계열과는 메커니즘 자체가 다르다.
둘째, Con의 둘째 주장인 “문학 텍스트로 측정한 퍼플렉서티는 편향된 벤치마크”라는 비판도 타당하지만 과장되었다. HISA 원 논문은 이미 Needle-in-a-Haystack과 LongBench에서 직접 교체 실험을 수행했고, 품질이 밀집(dense) 베이스라인에 “근접”한다고 보고했다. 영상의 개인 실험이 퍼플렉서티만 본 것은 소비자 GPU의 현실적 제약 때문이지 기법 자체의 약점이 아니다. 학계와 개인 실험을 합쳐서 보면 증거는 오히려 일관되게 긍정적이다.
셋째, Con의 셋째 주장인 “LLaMA에서는 미세 악화였다”는 지적에 대해서는 오히려 Pro의 논거가 강화된다. 0.44 포인트 차이는 통계적 잡음에 가깝고, 어떤 공격적 최적화도 모델마다 동일 결과를 낼 수 없다. 중요한 것은 “방향과 규모”이며, HISA는 두 모델 모두에서 폭주 없이 안정적 결과를 낸 반면, 통제군인 랜덤 희소 어텐션은 417이라는 파탄적 퍼플렉서티를 기록했다. 핵심 가설은 여전히 유효하다.
🔴 Con (재반박) — Pro의 반론에 대하여
Pro의 첫째 주장, 즉 “HISA가 선택한 토큰 IoU가 99%“라는 근거를 뒤집어 보자. 이 99%는 “원 DSA가 선택했을 토큰과의 일치율”이지, “정답 태스크에 필요한 토큰과의 일치율”이 아니다. 만약 DSA 자체가 정밀 검색에서 3%의 정답 토큰을 놓치고 있다면, HISA의 99% 재현은 그 3%의 실패를 거의 그대로 복제한다는 뜻이기도 하다. Retrospective Sparse Attention(arXiv:2508.09001) 같은 후속 연구가 “과거에 내린 희소 선택을 되돌아보고 수정”하는 메커니즘을 제안하는 이유가 바로 이것이다. 즉 DSA-호환성은 장점이자 동시에 DSA의 약점까지 계승하는 구조적 한계다.
Pro의 둘째 주장, 즉 “HISA 원 논문이 Needle-in-a-Haystack과 LongBench를 돌렸으니 편향 비판은 과장”이라는 주장에도 한계가 있다. “근접(close)“이라는 표현은 학술 문헌에서 종종 1~3%의 절대 정확도 격차를 의미하며, 이는 전체 시스템 성능을 판가름하는 중요한 폭일 수 있다. 특히 리트리벌 기반 에이전트, 법률 검토, 코드 리팩토링처럼 작은 오차가 하류에서 증폭되는 태스크에서는 “근접”이 “충분”을 뜻하지 않는다. Pro는 평균 성능으로 말하지만, 실패 분포의 꼬리에서 벌어지는 일을 숨기고 있다.
Pro의 셋째 주장인 “방향과 규모가 중요하다”는 논리는 벤치마크 체리피킹 위험을 감춘다. Qwen에서 0.01 개선, LLaMA에서 0.44 악화라는 결과는 결국 “±소음의 폭 안에서 왔다 갔다 한다”는 뜻이지 체계적 개선이 아니다. 특히 영상의 저자는 “어텐션 백엔드를 바꾸고, 블록 수를 재조정하고, 파라미터를 스케일링”하는 시행착오 끝에 숫자를 얻었다. 이 튜닝 비용이 “플러그 앤 플레이”라는 홍보와 모순된다는 점은 여전히 남는 의문이다.
Round 3
🟢 Pro — Con의 Round 2 재반박에 답하며
Con의 첫째 재반박, 즉 “IoU 99%는 DSA의 실패까지 복제한다”는 논리는 형식적으로는 맞지만 실증적으로는 약하다. DSA 자체가 DeepSeek V3.2와 GLM 5라는 프론티어 급 모델의 프로덕션 추론에서 실제로 쓰이고 있다는 사실이 그 “실패의 크기”가 실전에서 수용 가능한 수준임을 방증한다. vLLM Day 0 DeepSeek V3.2 보고서와 SGLang Day 0 지원 글은 DSA가 이미 상용 서빙 엔진에 통합되어 사용자에게 제공되고 있음을 보여준다. Retrospective Sparse Attention 같은 후속 연구는 경쟁이지 반증이 아니다. 분야가 건강하게 성숙하는 신호다.
Con의 둘째 재반박, 즉 “1~3% 격차도 실무에서는 치명적”이라는 주장에는 맥락을 덧붙이고 싶다. 희소 어텐션이 없으면 긴 컨텍스트는 아예 돌지 않거나, 돌더라도 너무 느려서 사용자가 쓰지 않는다. 영상 실험에서 16K와 32K 컨텍스트는 스톡 모델에서는 OOM으로 크래시했고, HISA 버전에서만 완주했다. “완벽한 정확도지만 실행 불가”와 “99% 정확도에 실행 가능” 중 어느 쪽이 실제 사용자 가치에 더 기여하는지는 자명하다. Con은 실행 가능성 자체가 품질의 전제 조건임을 간과하고 있다.
Con의 셋째 재반박, 즉 “시행착오 튜닝 비용이 플러그 앤 플레이 주장과 모순된다”는 논리는 부분적으로만 옳다. 영상의 시행착오는 “개인 개발자가 구현 버그를 잡는 과정”이었지 하이퍼파라미터 탐색이 아니었다. 반복 텍스트 문제, 블록 수 설정 버그, 어텐션 백엔드 선택은 모두 엔지니어링 이슈이며, 성숙한 라이브러리로 포장되면 사라진다. HISA 원 논문이 재학습 없이 프론티어 모델 인덱서를 직접 교체했다는 사실이 더 신뢰할 만한 기준선이다.
🔴 Con — Pro의 Round 2 재반론에 답하며
Pro의 첫째 재반론, 즉 “IoU 99% 논거”에 대해 다시 답하겠다. Pro는 “프로덕션에서 쓰이니까 괜찮다”는 논리로 우회했는데, 이는 선후 관계를 뒤집은 것이다. 프로덕션 서빙 엔진이 DSA를 채택한 주된 이유는 품질 완벽성이 아니라 “풀 어텐션을 돌릴 수 없는 컨텍스트 길이에서도 돌아간다”는 실행 가능성 때문이다. 즉 현재의 채택은 품질 수용이 아니라 체념에 가깝다. 바로 그 때문에 Retrospective Sparse Attention이나 MSA(Memory Sparse Attention) 같은 연구가 계속 등장하고 있다. 희소 어텐션이 정답이었다면 이런 후속 연구가 폭증할 이유가 없다.
Pro의 둘째 재반론, 즉 “실행 불가 vs 99% 정확도 실행 가능”이라는 이분법에도 함정이 있다. 이 이분법은 “희소 어텐션만이 유일한 대안”이라는 전제를 깔고 있지만, 현실에는 다른 전략도 많다. 검색 증강 생성(RAG), 외부 벡터 DB 기반 장기 기억, 컨텍스트 압축(context distillation), 계층적 요약 등은 모두 “전체 컨텍스트를 모델에 다 밀어넣지 않는” 우회로다. 많은 실무 태스크에서 이 우회로는 희소 어텐션보다 정확도-속도 트레이드오프가 더 좋다. Pro는 “긴 컨텍스트를 반드시 풀 스캔해야 한다”는 전제 자체를 의심하지 않고 있다.
Pro의 셋째 재반론, 즉 “시행착오는 엔지니어링 버그였다”는 해명도 불완전하다. “블록 수 설정 실수로 모든 블록이 선택되어 완벽한 정확도를 얻고 기뻐했다”는 일화는 반대로 “희소 어텐션의 성능 측정이 얼마나 쉽게 오염되는가”를 드러낸다. 학계 논문이 한 번의 깨끗한 설정에서 얻은 결과와, 개인 실험자가 깨진 설정을 고치며 얻은 결과 사이에는 현장 조건의 큰 간극이 있다. 성숙한 라이브러리가 이 간극을 좁혀 주리라는 기대는 아직 “약속”일 뿐, “증거”가 아니다.
🧭 종합
합의 지점
Pro와 Con 모두 “긴 컨텍스트 LLM의 이차 병목은 실재하는 문제이며, 단순 커널 최적화로는 근본 해결이 안 된다”는 데 동의한다. 양측은 또한 “희소 어텐션 계열 연구(DSA, HISA, NSA, MSA 등)가 현재 가장 활발하게 탐구되는 해결책 후보군”이라는 사실에도 이의를 달지 않는다. 영상에서 재현된 실험이 “동적(dynamic) 희소 선택은 랜덤 선택과 질적으로 다르다”는 점을 경험적으로 보여주었고, 원 논문의 IoU와 LongBench 결과가 최소한 “DSA 수준의 품질을 훨씬 낮은 비용으로 얻을 수 있다”는 구조적 장점을 뒷받침한다는 점도 함께 인정할 수 있다.
또한 양측 모두 “희소 어텐션의 평가는 퍼플렉서티 단일 지표로는 불충분하다”는 데 동의한다. Needle-in-a-Haystack, LongBench, SharedContextBench 같은 전용 벤치마크, 특히 정답 토큰이 멀리 떨어진 원거리 참조 태스크에서의 꼬리 분포 평가가 반드시 함께 가야 한다. 소비자 GPU 위의 실험이 이 평가를 완벽히 수행하기는 어렵다는 점도 공통 인정 사항이다.
열린 질문
- HISA와 그 후속들이 코드베이스 탐색, 법률 문서 대조, 학술 메타 분석처럼 원거리 단서가 흩어진 태스크에서 밀집 어텐션 대비 실제로 몇 %p까지 품질을 유지할 수 있는가?
- 희소 어텐션의 이득은 RAG, 컨텍스트 압축, 계층 요약 같은 대안 전략과 비교했을 때 어느 지점에서 교차(crossover)하는가? 즉 “전체를 모델에 밀어 넣는다”는 전략 자체가 타당한 영역의 경계선은 어디인가?
- 동적 희소 어텐션을 훈련 시점부터 반영한 NSA 계열이 추론 시점만 희소화한 DSA/HISA 계열을 어느 시점에 따라잡거나 추월하는가? 프론티어 모델이 학습부터 “희소 친화적”으로 설계되면 HISA 같은 사후 교체형 최적화의 수명은 얼마나 짧아지는가?
- 희소 선택의 실수를 되돌릴 수 있는 회고적(retrospective) 메커니즘, KV 캐시 복구, 섹션 단위 재스캔 같은 보완책이 HISA의 기본 구조에 어떻게 결합될 수 있는가?
- 개인 개발자의 재현 결과를 학계 수준의 평가와 비교 가능한 형태로 표준화할 공통 툴킷이 가능할까? “오만과 편견 한 권”이 아닌 “긴 컨텍스트 표준 스위트”에서의 손쉬운 측정이 필요하다.
더 나아간 관점
이 토론의 표면은 “희소 어텐션 vs 풀 어텐션”이지만, 한 겹 벗기면 “긴 컨텍스트라는 추상 자체를 어떻게 재설계할 것인가”라는 질문이 드러난다. 100만 토큰을 한 번에 모델에 밀어 넣는 것은 과연 “문제 해결”인가, 아니면 “미해결 문제에 연산을 쏟아붓는” 것인가. 희소 어텐션은 후자의 진영에 서 있다. 반면 RAG, 메모리 네트워크, 계층적 요약은 전자의 진영에서 “애초에 모든 토큰이 필요하지 않다”고 말한다.
HISA 같은 연구의 진짜 기여는 두 진영을 잇는 다리라는 데 있다. 블록 단위 계층 구조는 사실상 “입력을 요약하고 관련 섹션만 선택”하는 RAG의 논리를 어텐션 안쪽으로 내재화한 것이다. 이렇게 보면 희소 어텐션은 모델 외부의 리트리벌 시스템과 경쟁 관계가 아니라 연속선 위의 한 점이다. 앞으로의 방향은 둘 중 하나를 고르는 것이 아니라, 토큰 수준의 어텐션 희소화와 문서 수준의 리트리벌을 매끄럽게 연결하는 통합 아키텍처일 가능성이 크다.
개인 개발자의 RTX 3060 위에서 재현된 이 실험이 주는 가장 큰 메시지는 기술적 결과 자체가 아니다. “프론티어 연구가 소비자 하드웨어에서 며칠 만에 플러그인으로 복제될 수 있다”는 사실, 그리고 이 사이클이 점점 짧아지고 있다는 사실이다. 속도와 품질의 트레이드오프가 어디서 균형을 이루든, 이 복제 사이클 자체가 로컬 LLM의 실용 영역을 끌어올리는 가장 강력한 힘이다.
04영문 원본 · Transcript
So the other day on Twitter, I saw this tweet, and it refers to this paper over here. So I got into looking into the paper, and it was about attention, which I had just done a lesson on attention heads in Transformers, so I was interested in this topic. I took a look and kind of started digging deeper on it. And I thought it was interesting because it addresses a big issue that I think a lot of us have faced if you're using LLMs with long context windows. A lot of the more recent ones have 128,000 context windows. Obviously, the frontiers, a lot of them have a million context windows. But once you get to a certain point, you'll notice the performance gets a lot worse. It gets slow. The LLM itself will start performing worse. It's actually a big issue. So these kind of innovations in attention are actually really key to this. So in today's video, I wanted to dive deep into this concept of attention and then run an experiment to see if I could apply some of the concepts in this paper. To an actual model itself and get similar results in terms of speed and performance. So watch the end to see the results I get and see what kind of tool I'm able to build with this. I will be sharing. Everything will be open sourced, so I'll share that towards the end of the video. But first, what is attention? When a language model reads text, each word needs to figure out which other words are relevant to it. That process is called attention. So think of it like being in a room full of people. You ask a question and to answer it well, you need to look around and figure out who has the useful information. Attention is the model to doing that. And this is part of transformers. You have to check each previous word to decide who you have to listen to. And we have this interactive. Demo here, I click cat and the lights up, click sat, and you need to have all three of the words. Click Matt. You see. The word Matt attends. Directly to sat because it's talking about the location where this action happened. You click it and it highlights cat because it in the sentence, the cat sat on the mat and it purred it is referring to cat, right? So when you get to it, you need to go back and see which word it's actually referring to. And if you click purred here, you could see what purred the cat and it, which was on the mat is this kind of demo shows. How words in a sentence are related. So the key thing to understand is that each word checks every word that came before it, not just the word right next to it, right? Every single one. So for one sentence or a short, short. Text like this. This is fine, but for longer texts, it becomes a problem. So the issue here is that attention doesn't scale 10 words. You could check 10 people. That's not a problem, but 128,000 words, you have to check 128,000 people. For every single word using our analogy of people in the room. So we've measured this actually on the quen 3 billion parameter model, and each layer takes 12 to 26 milliseconds at 128,000 tokens. You multiply that by 36 layers, and you're looking at almost a full second just for the attention step alone. It's far too slow to be workable and the cost grows quadratically, which means that double the input length actually doesn't just do double it's four times. The work, and this is a fundamental bottleneck in long context language models. So how do we handle this? There's a few approaches models used to deal with this. And the original version was this MHA multi-head attention. And this is the original version used by GBT, two GBT, three Lama one, every attention head and think of heads as parallel workers, each looking for different patterns. It's gets its own separate memory. This works well, but it uses a ton of memory as you can imagine, because you're storing separate key. In vector. Values for every single head. GQA is grouped query attention, and it's what most modern models use Lama three quen, 2.5 Mistral instead of every single head and getting its own memory groups of heads share the same key value memory. For instance, quen 2.5 has 28 query heads, but only four key value heads. So every group of seven query heads shares one set of key value memory, and this cuts the memory footprint dramatically while keeping most of the quality. Flash attention is just a optimization on the speed, not an architectural change. So it gives exactly the same result, even if it's faster. And most modern models use this flash attention version, but here's the key thing that none of these solve. Every word still checks every other word. GQA here makes the memory smaller flash attention makes the computation faster, but the quadratic scaling issue remains. Every person in the room has to look at every other person. So the question is, what if we could skip. The relevant words entirely, and that's exactly what deep seek tried in their version three model, they introduce what's called DSA dynamic sparse attention. It's also referred to as deep seek sparse attention over here. They call it deep seek sparse attention. So you may see bolt in the literature just to keep in mind. So deep seeks innovation was to quick scan everything first, and then only listen carefully to the relevant ones. So think of it like speed dating instead of having deep conversations with every person in the room. You do a five quick. Five second scan of everyone first. Does this person meet my basic requirements? And then you could sit down and have real long conversations only with those that you think are a promising match. So in practice, for each word, DSA does a quick dot product, basically a similarity score against every key in the context. And you can see in this visualization, these green ones are selected, the dark ones are skipped. And the blue one barked here is the current word that's deciding who to think about. So basically, DSA does a quick scan of everything, finds which words, which tokens are most important, and then attends fully to just them. But there is a catch in order to find these tokens, these smaller group of tokens, DSA still had to do that quick scan of every token, right? At 128,000 token, that scan alone can take 12 to 26 milliseconds per layer. The attention computation gets cheaper, but the selection step still touches on everything. It's faster than having a full conversation. But it's still. Requires that full scan at the beginning. And this is what HISA intends to fix. HISA stands for Hierarchical Indexed Sparse Attention. And the insight is pretty simple. The room, the sentence or text in this case, is organized already into sections. So why interview every single person when you can first ask each section, hey, does anyone here know about this token? So it does this by splitting these into blocks. You have 128 tokens grouped into blocks of 128. So you end up with a little over 1000 block summaries instead of the entire 128,000 individual tokens you're looking at. So these highlighted blocks get attention and the rejected blocks are skipped entirely. You don't even need to scan them. And that is part of the stage one, which is selecting these blocks. Stage two is within these relevant blocks. You score tokens with it within each of the selected blocks. And then pick the top candidates from there. So you end up with the 1000 block. 1000 plus. Summaries plus a little over 8000 token scores for each of the relevant blocks. So you end up with around 9000 total operations and compare that to DSA, which had the original 128,000 operations for this attention level. And the nice thing is that this scales really well as context gets longer. HISA barely slows down because you're always selecting the same number of blocks regardless. So this is the results of the paper I was telling you about this one. There's been several papers on this topic of sparse attention, but this is the one. We're looking at today. It looked at deep sick version three and GLM five. They reported two to four times faster token selection. And they were using custom fuse GPU kernels with essentially zero quality loss and zero retraining needed. So it was a plug and play replacement for the DSA itself. So obviously these researchers had a very advanced setup, but I wanted to see if I could somehow recreate the concept itself using my simple RTX 3060 on a normal consumer PC. So this was the plan basically to just bolt HISA into a quen 2.5, 3 billion parameter stock model. And this model, like I said, is a normal GQ a attention model. So the model's attention layers normally project the input into queries, keys and values, and then compute the full attention. So we intercept that process. What I did is I let the model do its normal QK and V projections, but then we stepped in, we ran this HISA block scoring. On the keys themselves, figure out which blocks are relevant, physically gather only the selected key and value entries, and then created smaller tensors, and then compute attention only on those that smaller set. So obviously, this isn't a perfect recreation of what they did in the paper, but it recreated the philosophy at least. And the nice thing is the model didn't know anything was changed, you get the same attention output format. From the outside, you call model dot generate the same way as always, it's just under the hood. You get to skip a lot of the attention computation. Now to be perfectly transparent, this did not go I did not one shot this is took a lot of trial and error, as you would imagine. So it's worth showing that as well. So one of the mistakes we had is with the text sample we were using, it just contained a small repeated text. So that resulted in every block looking identical. HISA had nothing to work with, because every block was the same. So we replaced that with a very large novel Pride and Prejudice. So that it would be more reflective. Okay. So we had a lot of real text, not repeated issue two, we came up with was that this let set block count equal to selected count. HSA ended up selecting every block, which is not the same as using it. So at first, we were getting perfect accuracy. And I was very excited, but it ended up being meaningless, obviously. So we had to properly scale the parameters to avoid this. And the other issue we came into is that we couldn't get past 32,000 tokens. Because we're using the wrong attention back end, which was very memory inefficient. So we switched it out with a more efficient memory back end, which allowed us to run tests properly. A computer crashed many times, nonetheless, but we were able to get some results from it. So after fixing those issues, and several other small bugs, we were able to measure how fast HISA finds important tokens compared to DSA scanning every single token. So this is the DSA results where it has to do that quick scan of everything, HISA, which only use the blocks, you can see it. So we're looking at a DSA with 64,000 context, it was up to a two x. But when we got to 128,000 context, and that's really where you saw the difference, because HISA, like I said, doesn't increase that much. Whereas with DSA, you had to obviously go you're going from 2.4 milliseconds to 26 milliseconds on the high end. So our speedup went from around up to two x to seven to 14 x, actually, the essays cost grows with context length. But he says he stays nearly flat. because it's always scoring the same number of block summaries, regardless of how long the input is. So if you could do an even longer context window, up to a million, you would probably see even better speed advantages to this. So the speed advantage is great, but if the model starts generating garbage, right, none of it matters. So we had to test the quality as well, and we used this with perplexity. Perplexity is a standard metric for language model quality. It measures how well the model predicts the next word. So lower perplexity means less surprise, which means better predictions. So you're aiming for lower. So you can see the score here. Dense just means the stock attention method that QEN 2.5 uses. It got 19.68. And then our HISA adaptation using sparse attention got actually 18.67, which is slightly better, actually. And just as a sanity check to make sure that it wasn't just like any sparse attention could work, we did a random sparse attention picker. And you could see it got terrible score there. So it actually was effective, not just random. So I was a little surprised that it actually got slightly better, but this has actually been seen in the research before. When the model attends to everything, the attention weights get spread thin across thousands of irrelevant tokens. Each one gets a tiny sliver of focus. By forcing the model to concentrate on fewer, more relevant tokens, the signal-to-noise ratio improves. Think of it like removing background noise from a recording. So this was with the QEN 2.5 model. And right now I'm going to run a live test on a LAMA model. It has a similar attention method to the QEN one, but it's obviously a different model. I just want to make sure that these results kind of stand up regardless of which model you use. I'm going to do now a live test using this one, LAMA 3.2 3B Instruct, which also has 128K context. So we're going to run the same kind of test here. We're testing the speed and the quality, comparing the baseline, what they're using naturally, that GQA method, with our HESA implementation here. Okay, so it's running the quality test on the LAMA. Had some struggles here, but I think we're finally getting somewhere. So this is just to show that it wasn't... It wasn't just with the QEN results there, to see how well it runs on a different type of model. Same attention method LAMA and QEN use, but obviously different models. Okay, so it finally ran. And these are the quality tests. And perplexity is our benchmark. And here the term dense just means kind of the baseline attention method that LAMA uses. You could see 19.5. 19.5.1 as the baseline. Then we ran some of the sanity checks just to make sure everything was working properly. And they all passed. You could see how it compares with DSA and with the HESA at 50%. Slightly higher, 19.95. More than dense, but not a huge difference. It's not like it's jumping up to this random 417. Very small and should have a negligible... impact on the actual quality. So with QEN it had a slightly positive effect. And with this one it had a slightly negative effect. But generally we can say that there's not a huge gap in terms of quality. So now we're going to run the speed test to see how fast it has gotten. Because it's not really meant to improve quality. The key here is to improve speed. Okay, we got our results back. Took a little while, but the LAMA results are in. And we can see some patterns that we saw with QEN. So the indexer speed at 64k context on LAMA 3, 3.2, 3B. You could see the later layers show up to 4x speedup, which is consistent with what we saw with the QEN model. And the quality test confirmed a negligible PPL impact. So there's going to be some variance, but I think generally the trend you could see is that the quality is roughly... Roughly the same, a little better or a little worse. And then the speedup is pretty significant. So we got good results from these early tests, this kind of bolted on indexer. I wanted to see if I could actually create a plugin to basically bolt this onto any GQA model and have these speedup advantages. Now, most of the options were using Linux or hardware that I just didn't have access to. I'm just on a normal PC. So I did this in PyTorch. And all in all, it's around 3x speedup. 300 lines of Python. So I've been testing this and trying to optimize it in several ways. These were two of the optimizations I did. One using cross-layer prediction, which made it 40% faster. And then adaptive sparsity, which boosted it another 11% faster. So you can find this right now on Tombi Studio, GitHub. ISA-Pytorch. Please take a look at it yourself. This is very much an experiment. This is not a production release at all. And we're going to be doing a lot of research on this. And we're going to be doing a lot of research on this. By the time you're seeing this, I probably tweaked it several other times. But I thought it was an interesting experiment into different attention methods. So while the plugin itself is pretty buggy and needs a lot of work, I was able to get some results from it. So this is a complete model forward pass, not just the attention selection, the entire thing, including projections, feedforward layers, everything. And this is on the Qen 2.5 model I was talking about, the 3 billion parameter. And the dense just means the stock version, the baseline, what it came with. And the HISA plugin is what we built. You can see at 4,000 context, it was 2.3 times faster. And at 8,000 context, it was 9.3 times faster. And kind of interesting, at 16,000 and 32,000, I wanted to run more tests, but the actual stock version crashed on me. And this is just because it couldn't run on my GPU, my 12 gig GPU. But we were able to actually run through the full test when I had the plugin enabled, which is kind of interesting. It kind of suggests that this method doesn't just make the model faster. It lets it handle context lanes that it physically couldn't before. And keep in mind, this is always zero lines of custom CUDA code. This is pure PyTorch running on Windows on my consumer GPU. So these were the results I got. Please double check my work if you're interested in this. I double checked it. I think these are accurate numbers, but please, if you're more knowledgeable about this stuff than me, please take a look at this plugin. And try to tear it apart. Or try to suggest ways to improve upon it. It would be pretty great if you could just have a simple plugin for local models that could speed up in longer context windows. So what does this prove? We proved that HESA does work. It results in faster speeds at longer context windows without any recognizable quality loss. But we could obviously build on this a lot. And there's a lot of research going on in this area. Some suggestions of where we can go next is in the description below. And I'll see you in the next video. Bye. This is using fused GPU kernels, using flash attention to increase the speed even more. Using KV cache eviction during generation, production integration. Someone has already suggested using VLLM, which I might try. I haven't tried to use that before, but it could be a good idea. And if I have access to larger GPUs, I'd like to test it at even larger context. Because as we see new models coming out, the context windows are going to get even larger. And these kind of speed up methods are going to become absolutely crucial in order to have LLMs, especially local LLMs that can handle large context windows without being dreadfully slow. So I hope you found this video interesting. I was pretty interested doing this kind of research on something that addresses a real issue for LLMs. Please leave a comment. What are your thoughts on attention methods? How would you approach it? What are your thoughts on this recent research on sparse attention? And if you liked the video, please leave a like, please subscribe, and I'll see you in the next one.