AI·News
뒤로

LLM 아키텍처의 최근 발전: KV 공유, mHC, 그리고 압축된 어텐션

Recent Developments in LLM Architectures: KV Sharing, mHC, and Compressed Attention

짧은 가족 휴가 후 돌아와서 지난 몇 주간의 활발한 오픈 웨이트 LLM 출시들을 따라잡으려니 정말 설렙니다. 제가 주목한 것은 최신 아키텍처들이 얼마나 많이 장문맥 효율성에 집중하고 있다는 점입니다.

추론 모델과 에이전트 워크플로우가 점점 더 많은 토큰을 유지하면서(더 오랫동안), KV 캐시 크기, 메모리 트래픽, 그리고 어텐션 비용이 빠르게 주요 병목이 되고 있으며, LLM 개발자들은 이러한 비용을 줄이기 위해 점점 더 많은 아키텍처 트릭을 추가하고 있습니다.

제가 살펴보고 싶은 주요 예시들은 Gemma 4의 KV 공유와 계층별 임베딩, Laguna XS.2의 계층별 어텐션 예산 책정, ZAYA1-8B의 압축 합성곱 어텐션, 그리고 DeepSeek V4의 mHC와 압축 어텐션입니다.

이러한 변경들 중 대부분은 제 아키텍처 다이어그램에서는 작은 조정으로 보이지만, 일부는 상당히 복잡한 설계 변경으로 더 자세한 논의가 필요합니다.

그림 1. 최근의 주요 오픈 웨이트 출시들의 LLM 아키텍처 다이어그램(4월~5월). 이미지와 더 많은 세부사항은 제 LLM 아키텍처 갤러리에서 찾을 수 있습니다. 모든 모델 크기가 표시된 것은 아니며, Qwen3.6은 27B 및 35B-A3B 변형을 포함하고, ZAYA1은 8B 모델로 표현됩니다(ZAYA1-base 및 ZAYA1-reasoning-base 제외). 점선 상자의 아키텍처들은 이 글에서 더 자세히 다룹니다.

이 글은 아키텍처 설계에 관한 것이므로, 저는 주로 데이터셋 혼합, 훈련 일정, 사후 훈련 세부사항, RL 레시피, 벤치마크 표, 그리고 제품 비교를 건너뛸 것입니다. 그 더 좁은 범위에서도 다룰 내용이 많습니다. 그리고 예상대로 이 글이 생각보다 길어졌으므로, 트랜스포머 블록, 잔차 스트림, KV 캐시, 또는 어텐션 계산 내에서 무엇이 변하는지에 초점을 맞추겠습니다.

또한 제가 지금까지 다루지 않은 흥미로운(새로운) 설계 선택만 다루고 있다는 점도 유의하시기 바랍니다. 이 목록은 다음을 포함합니다:

  1. Gemma 4의 KV 공유 및 계층별 임베딩

  2. ZAYA1의 압축 합성곱 어텐션

  3. Laguna XS.2의 어텐션 예산 책정

  4. DeepSeek V4의 mHC 및 압축 어텐션

새로운 부분으로 들어가기 전에, 제가 다시 참고할 두 개의 이전 글이 있습니다. 첫 번째는 최근 MoE 모델, 라우팅된 전문가, 활성 매개변수, 그리고 모델 크기 비교에 대한 더 광범위한 아키텍처 배경을 제공합니다. 두 번째는 아래에서 반복적으로 나오는 어텐션 배경을 다루며, MHA, MQA, GQA, MLA, 슬라이딩 윈도우 어텐션, 희소 어텐션, 그리고 하이브리드 어텐션 설계를 포함합니다.

현대 LLM의 어텐션 변형에 대한 시각적 가이드

원래는 DeepSeek V4에 대해 쓸 계획이었습니다. 아직 출시되지 않아서, 지난 몇 년간 다뤄온 다양한 LLM 아키텍처들을 수집, 정리, 그리고 정제하는 데 오래 계획해온 작업을 하는 데 시간을 사용했습니다.

또한 이러한 설명 중 여러 개를 LLM 아키텍처 갤러리의 짧고 독립적인 튜토리얼 페이지로 변환했습니다. 예를 들어, 독자들은 GQA, MLA, 슬라이딩 윈도우 어텐션, DeepSeek 희소 어텐션, MoE 라우팅 등에 대한 간결한 설명을 찾을 수 있으며, 이들은 해당 모델 카드 및 개념 라벨에서 링크되어 있습니다.

아키텍처 발전과 조정 투어를 위해, 우리는 4월 초로 돌아가서 Google이 새로운 오픈 웨이트 Gemma 4 모델 제품군을 출시했을 때부터 시작하겠습니다. 이들은 3가지 광범위한 카테고리로 나뉩니다:

  • 모바일 및 소형 로컬(임베디드) 기기(즉, IoT)용 Gemma 4 E2B 및 E4B 모델,

  • 효율적인 로컬 추론에 최적화된 Gemma 4 26B 혼합 전문가(MoE) 모델,

  • 최대 품질과 더 편리한 사후 훈련을 위한 Gemma 4 31B 밀집 모델(MoE는 작업하기가 더 까다롭기 때문)

그림 2: Gemma 4 아키텍처 다이어그램입니다.

E2B 및 E4B 변형의 첫 번째 작은 아키텍처 조정은 공유 KV 캐시 방식을 채택하는 것으로, 나중 계층들이 이전 계층의 키-값 상태를 재사용하여 장문맥 메모리와 계산을 줄입니다.

이 KV 공유는 Gemma 4에서 발명되지 않았습니다. 예를 들어, Brandon et al., "교차 계층 어텐션을 통한 트랜스포머 키-값 캐시 크기 감소" (NeurIPS 2024)를 참조하세요. 하지만 이 개념이 적용된 첫 번째 인기 있는 아키텍처입니다. (교차 계층 어텐션은 교차 어텐션과 혼동되어서는 안 됩니다.)

KV 공유를 더 자세히 설명하기 전에 동기를 간단히 논의해봅시다. 최근 몇 개월 동안 제가 쓰고 말한 바와 같이, LLM 아키텍처 설계의 주요 최근 테마 중 하나는 KV 캐시 크기 감소입니다. 차례로, KV 캐시 크기 감소 뒤의 동기는 필요한 메모리를 줄이는 것이고, 이것은 우리가 더 긴 문맥으로 작업할 수 있도록 합니다. 이는 추론 모델과 에이전트의 시대에 특히 관련이 있습니다. KV 캐싱에 대한 더 많은 배경 정보는 제 "LLM의 KV 캐시 이해 및 처음부터 코딩하기" 글을 참조하세요:

실질적으로 제 이전 현대 LLM의 어텐션 변형에 대한 시각적 가이드 글에서 설명한 모든 인기 있는 어텐션 변형들은 KV 캐시 크기를 줄이도록 설계되었습니다:

고전적인 예(Gemma 4가 여전히 사용하는)를 들자면: 그룹화된 쿼리 어텐션(GQA)은 이미 서로 다른 쿼리 헤드 간에 키-값(KV) 헤드를 공유하여 KV 캐시 크기를 줄입니다. 아래 그림에 나와 있습니다.

그림 3: 그룹화된 쿼리 어텐션(GQA)은 여러 쿼리(Q) 헤드 간에 동일한 키(K) 및 값(V) 헤드를 공유합니다.

앞서 언급했듯이, Gemma 4는 GQA를 사용합니다. 하지만 GQA의 일부인 쿼리 간 KV 공유 외에도, Gemma 4는 또한 각 계층의 어텐션 모듈의 일부로 계산하는 대신 서로 다른 계층 전체에서 KV 프로젝션을 공유합니다. 이 KV 공유 방식, 또한 교차 계층 어텐션이라고 불리며, 아래 그림에 나와 있습니다.

그림 4: 일반 트랜스포머 블록은 각 어텐션 모듈에서 개별 Q, K, 및 V 프로젝션을 계산합니다(왼쪽). 교차 계층 어텐션 설계(오른쪽)는 여러 계층 전체에서 동일한 K 및 V 프로젝션을 공유합니다.

그림 2의 아키텍처 개요에서 간단히 언급했듯이, Gemma 4 E2B는 4:1 패턴에서 일반 GQA와 슬라이딩 윈도우 어텐션을 사용합니다. (더 정확히는, Gemma 4 E2B는 GQA의 한 KV 헤드 특수 경우인 MQA를 사용합니다).

GQA(또는 MQA)의 경우, KV 공유는 이렇게 작동합니다. 나중 계층들은 더 이상 자신의 키와 값 프로젝션을 계산하지 않고, 동일한 어텐션 유형의 가장 최근 이전 비공유 계층에서 KV 텐서를 재사용합니다. 즉, 슬라이딩 윈도우 계층은 이전 슬라이딩 윈도우 계층과 KV를 공유합니다. 전체 어텐션 계층은 이전 전체 어텐션 계층과 KV를 공유합니다. 계층들은 여전히 자신의 쿼리 프로젝션을 계산하므로, 각 계층은 자신의 어텐션 패턴을 형성할 수 있습니다만, 비싸고 메모리 집약적인 KV 캐시는 여러 계층 전체에서 재사용됩니다.

예를 들어, Gemma 4 E2B는 35개의 트랜스포머 계층을 가지고 있지만, 처음 15개만 자신의 KV 프로젝션을 계산합니다; 마지막 20개 계층은 동일한 어텐션 유형의 가장 최근 이전 비공유 계층에서 KV 텐서를 재사용합니다. 유사하게, Gemma 4 E4B는 42개 계층을 가지고 있으며, 24개 계층은 자신의 KV를 계산하고 마지막 18개 계층은 이들을 공유합니다.

이것이 실제로 얼마나 절감될까요? 계층 전체에서 KV의 약 절반을 공유하므로, KV 캐시 크기의 약 절반을 절감합니다. 가장 작은 E2B 모델의 경우, 아래에 나온 대로 긴 128K 문맥에서 (bfloat16 정밀도에서) 2.7 GB 절감을 초래합니다. (E4B 변형의 경우, 이는 128K에서 약 6 GB를 절감합니다.)

그림 5: Gemma 4 E2B와 유사한 설정에서 GQA 및 교차 계층 KV 공유의 KV 캐시 메모리 절감. 단순화를 위해 슬라이딩 윈도우 어텐션의 추가 절감은 표시되지 않습니다.

KV 공유의 단점은 물론, 실제의 "근사치"라는 것입니다. 또는 더 정확히, 모델 용량을 줄입니다. 그러나 교차 계층 어텐션 논문에 따르면, 영향은 미미할 수 있습니다(테스트된 작은 모델의 경우).

Gemma 4 E2B 및 E4B 변형은 계층별 임베딩(PLE)이라고 불리는 두 번째 효율성 지향 설계 선택을 포함합니다. 이는 위의 KV 공유 방식과는 별개입니다.

KV 공유는 KV 캐시를 줄입니다. PLE는 대신 매개변수 효율성에 관한 것으로, 작은 Gemma 4 모델들이 전체 매개변수 수가 같은 밀집 모델처럼 주요 트랜스포머 스택을 비용이 많이 들지 않게 하면서 더 많은 토큰별 정보를 사용할 수 있게 합니다.

예를 들어, Gemma 4 E2B 및 E4B의 "E"는 "효과적"을 의미합니다. 구체적으로, Gemma 4 E2B는 2.3B 효과적 매개변수, 또는 임베딩을 포함할 때 5.1B 매개변수로 나열됩니다. (유사하게, Gemma 4 E4B는 4.5B 효과적 매개변수, 또는 임베딩이 있는 8B입니다).

간단히, "E" 모델에서, 주요 트랜스포머 스택 계산은 더 작은 수에 더 가깝고, 더 큰 수는 추가 임베딩 테이블 계층을 포함합니다. (임베딩 계층이 어떻게 작동하는지의 설명은, 제 "임베딩 계층과 선형 계층의 차이 이해하기" 코드 노트북을 참조하세요.)

개념적으로, 새로운 PLE 경로는 다음과 같습니다:

그림 6: PLE 잔차 경로가 있는 단순화된 Gemma 4 블록. 일반 블록은 먼저 어텐션 및 피드포워드 잔차 업데이트를 계산합니다. 결과 숨겨진 상태는 계층별 PLE 벡터를 게이트하고, 프로젝션된 PLE 업데이트는 블록 끝에 추가 잔차 업데이트로 추가됩니다.

PLE 벡터 자체는 반복된 트랜스포머 블록 외부에서 준비됩니다. 단순화된 형태로, PLE 구성에 두 가지 입력이 있습니다. 첫째, 토큰 ID들은 계층별 임베딩 조회를 통과합니다. 둘째, 일반 토큰 임베딩들은 동일한 패킹된 PLE 공간으로의 선형 프로젝션을 통과합니다. 이 두 조각은 더해지고, 스케일되고, 계층당 하나의 슬라이스가 있는 텐서로 재형성됩니다. 각 블록은 자신의 슬라이스를 받는다는 점에 주목하세요.

그림 7: 단순화된 PLE 구성. 토큰 ID들은 계층별 임베딩 조회를 제공하고, 일반 토큰 임베딩들은 동일한 공간으로 프로젝션됩니다. 두 기여는 결합되고 재형성되어 각 트랜스포머 블록이 자신의 계층별 PLE 슬라이스를 받도록 합니다.

중요한 세부 사항은 PLE가 각 트랜스포머 블록에 일반 토큰 임베딩 계층의 완전 독립 복사본을 제공하지 않는다는 것입니다. 대신, 계층별 임베딩 조회는 한 번 계산됩니다. 그 다음, 앞서 언급했듯이, 각 계층에 작은 토큰별 임베딩 슬라이스를 제공합니다("슬라이스 재형성 / 계층 l 선택"). 각 입력 토큰에 대해, Gemma 4는 디코더 계층당 하나의 작은 벡터를 포함하는 패킹된 PLE 텐서를 준비합니다. 그 다음, 순전파 동안, 계층 l은 자신의 슬라이스(그림 6의 Gemma4WithPLEBlock에서 ple_l)만을 받습니다.

트랜스포머 블록 내부에서, 일반 어텐션 및 피드포워드 분기는 평상시처럼 실행됩니다. 먼저, 블록은 어텐션 잔차 업데이트를 계산합니다. 그 다음, 피드포워드 잔차 업데이트를 계산합니다. 두 번째 잔차 추가 후, 그림 6의 의사 코드에서 z로 표시한 결과 숨겨진 상태가 계층별 PLE 벡터를 게이트하는 데 사용됩니다. 게이트된 PLE 벡터는 모델 숨겨진 크기로 프로젝션되고, 정규화되고, 추가 잔차 업데이트로 추가됩니다.

따라서 유용한 정신적 모델은 트랜스포머 블록이 여전히 동일한 주요 어텐션 및 피드포워드 경로를 가지지만, Gemma 4는 피드포워드 분기 후 작은 계층별 토큰 벡터를 추가한다는 것입니다. 이것은 임베딩 매개변수 및 작은 프로젝션을 통해 표현 용량을 증가시킵니다. 이는 계산 오버헤드를 추가하지만 전체 트랜스포머 스택을 더 큰 매개변수 수에 확장하는 비용을 피합니다.

그럼 왜 PLE일까요? 더 간단한 대안은 더 적은 계층, 더 좁은 숨겨진 상태, 또는 더 작은 피드포워드 네트워크를 사용하여 밀집 모델을 더 작게 만드는 것입니다. 이것은 메모리와 레이턴시를 줄이겠지만, 또한 모델의 주요 계산을 수행하는 부분에서 용량을 제거합니다.

PLE 설계는 비용이 많이 드는 트랜스포머 블록을 더 작은 "효과적" 크기에 더 가깝게 유지하면서, 추가 용량을 계층별 임베딩 테이블에 저장합니다. 이들은 더 많은 어텐션 또는 FFN 가중치를 추가하는 것보다 사용하기에 훨씬 저렴하며, 주로 캐시할 수 있는 조회식 매개변수이기 때문입니다.

또한, 우리는 Google을 믿어야 합니다. 이것이 효과적이고 가치 있는 설계 선택입니다. 이 E2B 설계가 일반 Gemma 4 2.3B 모델 및 일반 Gemma 4 5.1B 모델과 어떻게 비교되는지 보기 위해 비교 연구를 보는 것이 흥미로울 것입니다.

또한 원칙적으로 PLE는 작은 모델로 제한되지 않습니다. 우리는 계층별 임베딩 슬라이스를 더 큰 모델에도 부착할 수 있습니다. 그러나 더 큰 모델들은 이미 이러한 추가 임베딩이 많은 도움이 되지 않을 수 있는 충분한 용량을 가지고 있습니다. 또한, 더 큰 모델의 경우, 우리는 이미 MoE 설계를 사용하여 계산 풋프린트를 더 작게 유지하면서 용량을 증가시키는 트릭으로 사용합니다.

그런데, 비교적 간단하고 읽기 쉬운 코드 구현에 관심이 있다면, 저는 Gemma 4 E2B 및 E4B 모델을 처음부터 구현했습니다 여기.

Laguna는 Poolside의 첫 번째 오픈 웨이트 모델이며, Poolside는 코딩 응용을 위한 LLM 훈련에 중점을 두는 유럽 기반 회사입니다. 제 여러 전 동료들은 최근 몇 년간 Poolside에 참여했으며, 그들은 많은 재능을 가진 훌륭한 팀을 가지고 있습니다. 더 많은 회사들도 자신의 모델 중 일부를 오픈 웨이트 변형으로 출시하는 것을 보는 것이 좋습니다.

어쨌든, 아래에 나온 Laguna XS.2 아키텍처는 처음 보기에는 매우 표준으로 보입니다. 하지만 제가 다이어그램에 나타내지 않은(또는 그려 넣으려고 하지 않은) 한 가지 세부 사항은 "계층별 어텐션 예산 책정"이라고 할 수 있는 개념입니다.

그림 9: Poolside의 Laguna XS.2 아키텍처입니다.

여기에서 어텐션 예산 책정 뒤의 아이디어의 일부는 모든 트랜스포머 계층에 동일한 전체 어텐션 예산을 제공하는 대신, Laguna XS.2는 계층별로 어텐션 비용을 변화시킨다는 것입니다. 이것은 총 40개 계층을 가지고 있으며, 30개 슬라이딩 윈도우 어텐션 계층 및 10개 전역/전체 어텐션 계층을 가집니다. 평상시처럼, 슬라이딩 윈도우 계층은 로컬 윈도우(여기: 512 토큰)를 통해서만 참석하며, 이는 KV 캐시와 어텐션 계산을 저렴하게 유지합니다. 전역 계층은 더 비싸지만 문맥 윈도우의 모든 정보에 접근할 수 있는 능력을 보존합니다.

이 혼합 슬라이딩 윈도우 + 전역/전체 어텐션 패턴은 Laguna XS.2에만 고유하지 않으며 다른 많은 아키텍처(Gemma 4 포함)에서 사용됩니다.

하지만 새로운 것은 계층별 쿼리 헤드 수의 사용입니다. 예를 들어, Hugging Face 모델 허브 config.jsonnum_attention_heads_per_layer 설정을 포함합니다. 따라서 계층들은 KV 캐시 형태를 호환 가능하게 유지하면서 서로 다른 수의 쿼리 헤드를 가질 수 있습니다.

그림 10: Laguna의 계층별 쿼리 헤드 예산 책정, 여기서 전체 어텐션 계층은 KV 헤드당 6개 쿼리 헤드를 사용하고, 슬라이딩 윈도우 어텐션 계층은 KV 헤드당 8개 쿼리 헤드를 사용합니다.

따라서 Laguna XS.2는 슬라이딩 윈도우 계층에 더 많은 쿼리 헤드를 제공하고 전역 계층에 더 적은 쿼리 헤드를 제공하면서, KV 헤드를 8로 고정합니다. 이것이 설정의 실제 계층별 헤드 예산 책정입니다.

Laguna XS.2는 프로덕션 스타일 오픈 모델에서 이 계층별 쿼리 헤드 예산 책정의 가장 저명한 최근 예 중 하나입니다. 하지만 계층별로 모델 용량을 변화시키는 더 광범위한 아이디어는 (최소한) Apple의 2024 OpenELM까지 거슬러 올라갑니다.

그리고 다시 이러한 설계의 목적은 무엇일까요? KV 공유와 유사하게, 목적은 모든 계층에 동일한 예산을 제공하는 대신 어텐션 용량이 가장 유용한 곳에 사용하는 것입니다. 구체적으로, 전체 어텐션 계층은 전체 문맥을 보기 때문에 비싸므로, Laguna는 슬라이딩 윈도우 어텐션 모듈과 비교하여 더 적은 쿼리 헤드를 제공합니다.

(게다가, 또 다른 더 작은 구현 세부사항은 Laguna가 또한 계층별 헤드 어텐션 출력 게이팅을 적용한다는 것입니다; 이는 Qwen3-Next 등과 다소 유사하며, 저는 이전 글에서 다루었으므로 여기서 생략합니다.)

Laguna와 유사하게, ZAYA1-8B는 오픈 웨이트 시장의 또 다른 새로운 플레이어입니다. 이는 Zyphra에 의해 개발되며, 출시 주변의 흥미로운 세부사항 중 하나는 모델이 더 일반적인 NVIDIA GPU(또는 Google TPU) 설정이 아닌 AMD GPU에서 훈련되었다는 것입니다.

주요 아키텍처 세부사항은 그룹화된 쿼리 어텐션과 함께 사용되는 압축 합성곱 어텐션(CCA)입니다. MLA 스타일 설계와는 달리 주로 잠재 표현을 압축 KV 캐시 형식으로 사용하는 대신, CCA는 압축 잠재 공간에서 어텐션 작동을 직접 수행하지만, 더 자세한 내용은 나중에 말씀드리겠습니다.

(사이드 노트: ZAYA1-8B config.json은 40개의 일반 트랜스포머 블록보다 80개의 교대 계층 항목을 나열합니다. 이 항목들은 CCA/GQA 어텐션 및 MoE 피드포워드 계층 사이에서 교대로 나타납니다. 하지만 아키텍처 그림의 경우, 개념적으로 동등한 40개의 반복 어텐션 + MoE 쌍으로 이를 시각화하는 것이 더 편리합니다.)

그림 11: 압축 합성곱 어텐션을 특징으로 하는 트랜스포머 블록이 있는 Zaya1(8B)입니다.

위의 그림에서 힌트로 나타낸 대로, ZAYA1-8B는 압축 합성곱 어텐션(CCA)을 4:1 GQA 레이아웃과 함께 사용합니다. 핵심 포인트는 어텐션 블록이 표준 슬라이딩 윈도우 어텐션 블록이 아닌 CCA 주위에 구축되어 있다는 것입니다.

압축 합성곱 어텐션이 무엇인가요?

제가 말하기로는 CCA는 정신상으로 DeepSeek의 모델에서 다중 헤드 잠재 어텐션(MLA)과 관련이 있습니다. 둘 다 어텐션 블록에 압축 잠재 표현을 도입하기 때문입니다. 그러나 그들은 그 잠재 공간을 다르게 사용합니다. MLA는 주로 잠재 표현을 KV 캐시를 줄이는 데 사용합니다. MLA에서, KV 텐서는 압축되게 저장되고 실제 어텐션 계산을 위해 어텐션 헤드 공간으로 프로젝션됩니다.

그림 12: 일반 다중 헤드 어텐션(MHA)과 다중 헤드 잠재 어텐션(MLA)입니다.

CCA는 Q, K, 및 V를 압축하고 압축 잠재 공간에서 직접 어텐션 작동을 수행합니다. 이것이 CCA가 KV 캐시 크기뿐만 아니라 프리필 및 훈련 중의 어텐션 FLOP도 줄일 수 있는 이유입니다.

그림 13: 다중 헤드 잠재 어텐션(MLA)과 압축 합성곱 어텐션(CCA)입니다.

그림 13 위에 나온 대로, CCA에서, 압축된 잠재 표현들은 어텐션 메커니즘으로 직접 들어가고, 결과 압축된 어텐션 벡터는 그 다음 업 프로젝션됩니다.

이것이 압축 합성곱 어텐션이라고 불리는 이유는, 단순히 압축 어텐션이 아니라, 잠재 K와 Q 표현에서 발생하는 추가 합성곱 혼합이 있기 때문입니다. 합성곱 혼합 부분은 그림 12에 나타나지 않습니다. 왜냐하면 너무 꽉 찼을 것이기 때문이지만, 이것은 비교적 간단합니다.

그림 12에서 힌트로 나타낸 대로, 합성곱 혼합은 압축된 Q 및 K 텐서에서 직접 발생합니다. 목적은 압축이 Q, K, 및 V를 더 좁게 만들고, 이는 계산과 캐시를 절감하지만, 또한 어텐션을 덜 표현적으로 만들 수 있다는 것입니다. 합성곱들은 압축된 Q 및 K 벡터들이 어텐션 점수를 계산하는 데 사용되기 전에 더 많은 로컬 문맥을 주는 저렴한 방법입니다. (합성곱 혼합은 Q 및 K에만 적용되며 V에는 적용되지 않습니다. Q와 K는 어텐션 점수를 결정하고, V는 이 점수를 통해 평균되는 내용을 표현하기 때문입니다).

그림 14: 수열 혼합 합성곱의 개념적 개요

그림 13에 나온 수열 혼합 옆에, 채널 혼합 성분도 있습니다. 원칙적으로 유사하지만, 제는 설명을 생략하고 있습니다.

CCA는 ZAYA1-8B 기술 보고서 이전의 Zyphra 도입 어텐션 메커니즘으로 보이며. 독립적인 CCA 논문, 압축 합성곱 어텐션: 압축 잠재 공간의 효율적 어텐션, 2025년 10월에 처음 게시되었으며 명시적으로 CCA를 도입합니다. ZAYA1-8B는 그 다음 이 메커니즘을 핵심 부분 중 하나로 사용합니다.

하지만 질문은, "MLA보다 나을까요?"입니다. CCA 논문 자체 실험에 따르면, 예. 그들은 비교 가능한 압축 설정 하에서 MLA를 능가한다고 CCA를 보고합니다.

전반적으로, 흥미로운 부분은 정말 새로운 어텐션 메커니즘입니다. 모델은 또한 꽤 극단적인(= 매우 희소) MoE 설정을 사용하며, 토큰당 활성 전문가만 하나만 있지만, 그 부분은 더 익숙합니다. CCA는 더 이상하므로, 압축 잠재 공간에서 어텐션 작동을 직접 수행하고 압축된 Q 및 K 표현에 합성곱 혼합을 사용하여 이 압축 어텐션을 덜 제한적으로 만들기 때문입니다. 따라서 간단히, ZAYA1-8B는 피드포워드 계층에서만이 아닌 어텐션 메커니즘 자체에서 계산을 절감하려고 시도합니다.

DeepSeek V4는 지금까지 올해 가장 큰 출시였으며, 과대 광고와 모델 크기 측면에서 모두 그렇습니다. 흥미롭게도, DeepSeek V4-Pro는 또한 아래 표에 나온 모델들 중 활성 매개변수 공유로 측정된 가장 매개변수 희소 MoE이며, 아래 표에 요약되어 있습니다.

주의: 활성 매개변수 공유는 단지 하나의 렌즈입니다. 이는 KV 캐시 크기, 어텐션 패턴, 문맥 길이, 라우팅 오버헤드, 하드웨어 효율성, 또는 훈련 품질을 캡처하지 않습니다. 하지만 희소 모델을 비교할 때 빠른 확인으로 도움이 됩니다.

DeepSeek V4에 대해 말할 것이 많지만, 이미 뉴스에 모두 나왔고, 주제에 머물기 위해 아키텍처 조정과 관련하여 이전 아키텍처와 비교하여 새로운 가장 관련성 높은 두 부분에만 집중하겠습니다:

  1. 더 넓은 잔차 경로를 위한 mHC,

  2. 긴 문맥 어텐션 압축 및 희소성을 위한 CSA/HCA

아래의 DeepSeek V4 아키텍처 그리기를 보면, 많은 일들이 진행 중인 것처럼 보입니다. 이를 읽는 유용한 방법은 잔차 경로 변경인 mHC를 어텐션 경로 변경인 CSA/HCA 및 압축 어텐션 캐시로부터 분리하는 것입니다.

그림 17: DeepSeek V4-Pro 아키텍처 개요입니다.

DeepSeek V4의 mHC 성분부터 시작해봅시다. 이는 DeepSeek 팀이 지난해 공유한 연구 논문으로 거슬러 올라갑니다(2025년 12월 31일, mHC: 다양체 제약 하이퍼 연결). 하지만, 이 논문에서, 기술은 실험용 27B 스케일 모델에서만 테스트되었습니다. 이제, 우리는 이것을 그들의 주력 출시에서 봅니다. 이는 이 아이디어가 프로덕션에서 실제로 좋게 작동한다는 좋은 신호입니다.

여기서 mHC 뒤의 주요 아이디어는 트랜스포머 블록 내 잔차 연결의 설계를 현대화하는 것입니다. 이는 신선합니다. 왜냐하면 아키텍처 조정은 일반적으로 어텐션 메커니즘, 정규화 계층 배치, 그리고 MoE 부분에 초점을 맞추기 때문입니다.

이제, mHC는 이전 하이퍼 연결 작업을 기반으로 합니다(참조 하이퍼 연결 by Zhu et al., 2024). 하이퍼 연결은 본질적으로 단일 잔차 스트림을 여러 병렬 잔차 스트림 및 이들 간의 학습된 매핑으로 교체하여 트랜스포머 블록 내 단일 잔차 스트림을 수정합니다.

(잔차 연결을 처음 접하는 사람들을 위해, 저는 여러 해 전에 일반적인 메커니즘을 설명한 잔차 신경망 비디오를 만들었습니다.)

하이퍼 연결 뒤의 아이디어는 잔차 스트림을 넓히는 것입니다. 우리는 이를 추가 Res 매핑 선형 변환이 있는 여러 병렬 잔차 스트림을 유지하고 계층 전체에서 이들을 혼합하는 것으로 생각할 수 있습니다. 어텐션 또는 MoE 계층 자체가 여전히 정상 숨겨진 크기에서 작동하므로, 하이퍼 연결도 병렬 잔차 스트림을 정상 숨겨진 벡터로 결합하는 사전 매핑을 추가하고, 계층 출력을 병렬 잔차 스트림 전체에 분배하는 사후 매핑을 추가합니다. 이는 아래 그림에서 시각적으로 요약됩니다.

그림 18: 일반 트랜스포머 블록(상단) vs 주석이 달린 그림들을 사용한 하이퍼 연결(하단)이 있는 트랜스포머 블록 https://arxiv.org/abs/2512.24880.

아래 그림은 트랜스포머 블록의 어텐션 계층 부분에만 집중하지만, 동일한 개념이 MoE 계층 주변의 두 번째 잔차 분기에도 적용됩니다.

하이퍼 연결의 목적은 실제 어텐션 또는 MoE 계층을 더 넓히지 않으면서 잔차 경로를 더 표현적으로 만드는 것입니다. 이는 추가 매핑이 작은 잔차 스트림 축에서 작동하기 때문에 FLOP에서 약간만 더 비쌀 뿐입니다. 예를 들어, n = 4 in DeepSeek V4, 거대한 숨겨진 차원이 아닙니다.

원래의 하이퍼 연결 논문에서, 7B OLMo MoE 실험은 13.36G에서 13.38G FLOP per token으로 가며, 이는 기본적으로 변경되지 않습니다. 보고된 이득의 측면에서, 아래 그림에 나온 대로 겸손한(하지만 일관된) 개선이 있었습니다.

(그러나 FLOP를 보는 것만은 다소 단순합니다. 넓혀진 잔차 상태는 여전히 저장되고, 메모리를 통해 이동하고, 혼합되어야 합니다. 따라서 실질적인 오버헤드는 명시적으로 측정되지 않는 메모리 트래픽 및 구현 복잡성에서 더 많이 올 수 있습니다. 그러나 DeepSeek V4는 모두 효율성에 관한 것이므로, 이것이 가치 있는 추가 같습니다.)

또한, 위 그림에 나온 대로, 메트릭은 대략 절반의 훈련 토큰을 사용하는 기준선의 성능에 도달했습니다.

정규 하이퍼 연결(HC)에서 다양체 제약 하이퍼 연결(mHC)으로의 주요 변경은 매핑이 더 이상 제약 없다는 것입니다. 정규 HC에서, Res 매핑은 병렬 잔차 스트림을 혼합하는 학습된 행렬이지만, 많은 이러한 행렬을 스택하면 신호를 예측 불가능하게 증폭하거나 축소할 수 있습니다.

mHC에서, 이 잔차 매핑은 이중 확률적 행렬의 다양체에 프로젝션되며, 이는 모든 항목이 음이 아니고 각 행과 열이 1로 합산됨을 의미합니다. 이는 잔차 혼합이 스트림 전체에서 정보의 더 안정적인 재분배처럼 작동하게 합니다. 사전 매핑사후 매핑도 음이 아니고 경계지어져 있어 넓혀진 잔차 상태에서 읽고 쓸 때 취소를 피합니다. 간단히, mHC는 HC의 더 풍부한 잔차 혼합을 유지하지만, 더 큰(더 깊은) 모델의 경우 더욱 관련이 있는 더 안전하게 스케일되도록 제약을 추가합니다.

그 외에도, 병렬 잔차 스트림을 사용하는 주요 아이디어는 아래 그림에 나온 대로 남습니다.

그림 20: 하이퍼 연결(HC) 및 다양체 제약 하이퍼 연결(mHC)이 있는 트랜스포머 블록 https://arxiv.org/abs/2512.24880.

mHC 논문에서, 27B 매개변수 모델을 사용하는 실험에서, DeepSeek 팀의 최적화된 구현(융합, 재계산, 및 파이프라인 스케줄러 포함)은 4개 잔차 스트림(n = 4) 대 단일 스트림 기준선의 모든 트랜스포머 블록 전체에서 훈련 시간 오버헤드를 단 6.7% 추가합니다.

이 섹션을 요약하자면, HC/mHC는 단일 잔차 스트림을 여러 상호작용 잔차 스트림으로 교체하여, mHC에서 추가된 안정성 제약과 함께, 계산 오버헤드를 최소화하면서 이 계층 주변에서 정보가 어떻게 전달되는지를 변경합니다. 또한 CSA/HCA 어텐션 변경과 잘 쌍을 이루며, 이는 트랜스포머 블록의 다른 부분을 수정하며, 아래에서 논의하겠습니다.

다른 주요 DeepSeek V4 아키텍처 변경은 어텐션 쪽에 있습니다. 다시 동기는 매우 긴 문맥 길이에서 어텐션이 어텐션 점수 계산뿐만 아니라 KV 캐시가 수열 길이와 함께 성장하기 때문에 비싸진다는 것입니다. DeepSeek V4는 이 문제를 두 개의 압축 어텐션 메커니즘의 하이브리드인 압축 희소 어텐션(CSA) 및 완전 압축 어텐션(HCA)으로 처리합니다.

새로새긋, 저는 이전 "현대 LLM의 어텐션 변형에 대한 시각적 가이드" 글을 확인하는 것을 권장하며, 이는 다중 헤드 잠재 어텐션(MLA) 및 DeepSeek 희소 어텐션(DSA) 등을 다룹니다.

주목할 첫 번째 일은 DeepSeek V4의 CSA/HCA는 DeepSeek V2/V3에서 사용된 MLA 스타일 압축과는 다른 종류의 압축입니다. MLA는 주로 토큰별 KV 표현을 압축하는 반면, CSA 및 HCA는 수열 차원을 따라 압축합니다. 따라서 이전 토큰마다 하나의 전체(또는 압축된) KV 항목을 유지하는 대신, 토큰 그룹들을 더 적은 압축된 KV 항목으로 요약합니다. 결과적으로 캐시가 더 짧아집니다. DeepSeek V4는 또한 압축된 항목과 공유 KV 어텐션을 사용하지만, MLA와의 주요 구별은 수열 길이 압축입니다. 이는 아래 그림에 나와 있습니다.

그림 21: MLA 스타일 토큰별 잠재 캐싱, CSA, 및 HCA의 개념적 비교. MLA는 저장된 KV 표현을 압축하지만 토큰당 하나의 잠재 항목을 유지합니다. CSA는 m=4로 밀드하게 수열을 단축하고 희소 상위 k 선택을 하며, HCA는 m'=128로 훨씬 더 무거운 수열 압축을 사용하고 더 짧은 캐시를 통해 밀집 어텐션을 합니다.



CSA/HCA의 품질 트레이드오프도 MLA와 다릅니다. 위 그림에 나온 대로, MLA는 각 토큰에 대해 저장된 표현을 압축하지만, 토큰당 하나의 잠재 KV 항목을 여전히 유지합니다. CSA와 특히 HCA는 수열 항목 자체의 수를 줄임으로써 더 나아가므로, 모델은 훨씬 더 낮은 긴 문맥 비용으로 교환하여 일부 토큰 레벨 정보를 포기합니다.

다시, 모두 긴 문맥 비용을 줄이는 것에 관한 것이지만, 이 트레이드오프는 압축이 너무 강하면 모델링 품질을 해칠 수 있으며, 이것이 DeepSeek V4가 하나의 압축 방식만 의존하지 않고 CSA와 HCA를 교대로 사용하는 이유입니다. CSA는 더 온화한 압축 속도 및 DeepSeek 희소 어텐션(DSA) 스타일 선택기를 사용하고, HCA는 더 저렴한 전역 커버리지를 위해 훨씬 더 무거운 압축을 사용합니다. 둘 다 최근 압축 해제 토큰을 위한 로컬 슬라이딩 윈도우 분기를 유지합니다. CSA의 이 희소 선택은 DeepSeek 희소 어텐션(DSA)을 기반으로 하며, 제가 제 이전 DeepSeek V3.2 기록에서 더 자세히 논의했습니다.

HCA는 둘 중 더 공격적인 변형입니다. 이것은 128개 토큰마다 하나의 압축 KV 항목으로 압축하지만, 그 다음 이들 완전히 압축된 항목들에 대해 밀집 어텐션을 사용합니다. 다시 말해, CSA는 더 많은 세부사항을 유지하지만 희소 선택을 사용하고, HCA는 훨씬 더 적은 항목을 유지하고 이들에 대해 밀집 어텐션을 사용할 수 있으며, 아래 그림에 나와 있습니다. 이는 두 메커니즘을 다소 보완적으로 만들며, DeepSeek V4가 두 개 중 하나만 사용하는 대신 CSA 및 HCA 계층을 교대로 사용하는 이유입니다.

그림 22: CSA는 압축된 기록의 희소 집합을 선택하고, HCA는 더 완전히 압축된 블록들에 밀집으로 참석합니다. 두 경로 모두 또한 128 토큰 슬라이딩 윈도우 분기를 통해 최근 압축 해제 KV 항목을 포함합니다.

DeepSeek V4 논문은 1M 토큰 문맥 길이에서, DeepSeek V4-Pro가 MLA 및 DeepSeek 희소 어텐션(DSA)을 사용하는 DeepSeek V3.2와 비교하여 단일 토큰 추론 FLOP의 27% 및 KV 캐시 크기의 10%만을 사용한다고 보고합니다. DeepSeek V4-Flash는 더욱 작아서, DeepSeek V3.2 대비 FLOP의 10% 및 KV 캐시 크기의 7%입니다.

그림 23: DeepSeek V4 논문에서 보고된 1M 문맥 효율성 숫자, DeepSeek V3.2 대비입니다.

그런데, 저는 CSA/HCA를 일반적인 의미에서 "더 나은" 것보다는 MLA라고 설명하지 않을 것입니다. CSA/HCA는 더 공격적인 긴 문맥 설계입니다. 그리고 또한 확실히 더 복잡합니다. 불행히도 논문에 절제 연구가 없습니다. 하지만 전반적으로 논문은 기본 모델 벤치마크 대다수에서 DeepSeek V4-Flash-Base가 DeepSeek V3.2-Base를 능가하고 강한 1M 토큰 검색 결과를 포함한 강한 전반적인 모델링 결과를 보고합니다만, 이 결과들은 전체 DeepSeek V4 레시피 때문이며, 이는 또한 더 나은 데이터, Muon 기반 최적화, mHC, 정밀도/저장소 최적화, 그리고 훈련/추론 시스템 변경을 포함합니다.

개인적으로, 지금으로서는, 나는 CSA/HCA를 장문맥 설계를 보존하는 것으로 보인다는 효율성 초점 긴 문맥 설계로 취급할 것입니다만 그들의 큰 주력 모델에서 모델링 품질을 잘 보존하는 것처럼 보이지만 반드시 보편적으로 MLA보다 나은 것은 아닙니다.

전반적으로, 올해의 흥미로운 패턴은 대부분의 새로운 오픈 웨이트 모델들이 단순히 총 매개변수 측면에서 모델을 축소하지 않으면서 긴 문맥 추론을 더 저렴하게 만들려고 한다는 것입니다. 예를 들어,

  • Gemma 4는 교차 계층 KV 공유로 KV 캐시 메모리를 줄이고 계층별 임베딩으로 용량을 추가합니다.

  • Laguna XS.2는 각 계층이 얼마나 많은 어텐션 용량을 얻는지를 조정합니다.

  • ZAYA1-8B는 어텐션을 압축 잠재 공간으로 이동합니다.

  • DeepSeek V4는 제약 잔차 스트림 혼합 및 압축 긴 문맥 어텐션을 추가합니다.

이러한 조정 모두는 더 많은 복잡성을 추가하며, LLM 아키텍처가 지금 진행 중인 곳이 맞는 것처럼 보입니다.

제 주요 핵심은 트랜스포머 블록이 여전히 변하고 있다는 것입니다만, 상당히 대상이 지정된 방식으로. 기본 레시피는 여전히 원본 GPT 디코더 온리 트랜스포머 아키텍처를 기반으로 하지만, 많은 부분들이 업그레이드되거나 교체되며, 그리고 더 길고 더 효율적인 추론에 더 특화되고, 정성적 모델링 성능은 주로 데이터 품질(및 양) 및 훈련 레시피에 의해 주도되는 것처럼 보입니다.

많은 분들이 저에게 과거에 물어본 질문은 트랜스포머들이 다른 것으로 대체되는 언제(또는 만약) 중심입니다. 물론, 확산 모델과 같은 다른 설계들이 있지만, 트랜스포머들은 최신 아키텍처 출시의 상태로 남습니다.

하지만, 증가하는 매 분기 출시마다, 우리는 더 많은 조정을 얻습니다. 기본 트랜스포머 블록을 아마도 50-100줄의 PyTorch 코드로 구현할 수 있었던 동안, 이러한 조정들(특히 어텐션 변형들 주변)은 아마도 코드 복잡성을 10배 높입니다. 이는 본질적으로 나쁜 것이 아닙니다. 이러한 조정들은 (증가하지 않고) 런타임 비용을 줄입니다. 그러나, 개별 구성 요소들과 그들의 상호작용의 명확한 이해를 얻기가 점점 어려워지고 있습니다.

그림 24: GPT-2(2019)에서 DeepSeek V4-Pro(2026)로의 진화

예를 들어, LLM 아키텍처에 처음 뛰어드는 사람은 DeepSeek V4 소스 코드를 볼 때 완전히 압도당할 것으로 정말 확신합니다. 그러나, 원본 디코더 스타일 LLM(GPT/GPT-2)에서 시작하여 그 다음 이 새로운 구성 요소들을 한 번에 하나씩 점차 추가/학습함으로써, 우리는 학습 노력을 관리 가능하게 유지할 수 있습니다. 이야기의 교훈은 아마도 계속 배우는 것입니다, 한 번에 한 아키텍처씩 :).


그런데, 저는 추론 모델 구축(처음부터)을 완성했다고 공유하게 되어 정말 신나며, 모든 장이 이제 조기 접근에 있습니다. 출판사 및 나는 지난 달에 최종 레이아웃을 위해 열심히 일했으며, 이것이 이주에 인쇄로 전송될 것입니다. (좋은 소식: 인쇄 버전은 이번에 색상으로 될 것입니다!)

이것은 아마도 지금까지 제 가장 야심찬 책입니다. 저는 약 1.5년을 써서 보냈고, 많은 수의 실험이 그것에 들어갔습니다. 또한 아마도 제가 시간, 노력, 그리고 광택 측면에서 가장 열심히 일한 책이며, 당신이 이것을 즐기기를 바랍니다.

주요 주제들은

LLM의 "추론"에 관한 많은 논의가 있습니다, 그리고 나는 LLM의 맥락에서 그것이 정말 의미하는 것을 이해하는 가장 좋은 방법은 하나를 처음부터 구현하는 것입니다!

After a short family break, I am excited to be back and catching up on a busy few weeks of open-weight LLM releases. The thing that stood out to me is how much newer architectures are focused on long-context efficiency.

As reasoning models and agent workflows keep more tokens around (for longer), KV-cache size, memory traffic, and attention cost quickly become the main constraints, and LLM developers are adding a growing number of architecture tricks to reduce those costs.

The main examples I want to look at are KV sharing and per-layer embeddings in Gemma 4, layer-wise attention budgeting in Laguna XS.2, compressed convolutional attention in ZAYA1-8B, and mHC plus compressed attention in DeepSeek V4.

Most of these changes look like small tweaks in my architecture diagrams, but some of them are quite intricate design changes that are worth a more detailed discussion.

Figure 1. LLM architecture drawings of recent, major open-weight releases (April to May). You can find the images, and more details, in my LLM architecture gallery. Not all model sizes are shown; Qwen3.6 includes the 27B and 35B-A3B variants, and ZAYA1 is represented by the 8B model (omitting ZAYA1-base and ZAYA1-reasoning-base). The architectures in the dotted boxes are covered in more detail in this article.

Note that this article is about architecture designs, so I will mostly skip dataset mixtures, training schedules, post-training details, RL recipes, benchmark tables, and product comparisons. Even with that narrower scope, there is a lot to cover. And, like always, the article turned out longer than I expected, so I will keep the focus on what changes inside the transformer block, residual stream, KV cache, or attention computation.

Please also note that I am only covering those topics that are interesting (new) design choices and that I haven’t covered elsewhere, yet. This list includes:

  1. KV sharing and per-layer embeddings in Gemma 4

  2. Compressed convolutional attention in ZAYA1

  3. Attention budgeting in Laguna XS.2

  4. mHC and compressed attention in DeepSeek V4

Before getting into the new parts, here are the two previous articles I will refer back to. The first one gives a broader architecture background on recent MoE models, routed experts, active parameters, and model-size comparisons. The second one covers the attention background that comes up repeatedly below, including MHA, MQA, GQA, MLA, sliding-window attention, sparse attention, and hybrid attention designs.

A Visual Guide to Attention Variants in Modern LLMs

I had originally planned to write about DeepSeek V4. Since it still hasn’t been released, I used the time to work on something that had been on my list for a while, namely, collecting, organizing, and refining the different LLM architectures I have covered over the past few years.

I also turned several of these explanations into short, standalone tutorial pages in the LLM Architecture Gallery. For example, readers can find compact explainers for GQA, MLA, sliding-window attention, DeepSeek Sparse Attention, MoE routing, and other concepts linked from the corresponding model cards and concept labels.

For this tour of architecture advances and tweaks, we will go back to the beginning of April when Google released their new open-weight Gemma 4 suite of models. They come in 3 broad categories:

  • the Gemma 4 E2B and E4B models for mobile and small, local (embedded) devices (aka IoT),

  • the Gemma 4 26B mixture-of-experts (MoE) model, optimized for efficient local inference,

  • and the Gemma 4 31B dense model, for maximum quality and more convenient post-training (since MoEs are trickier to work with)

Figure 2: Gemma 4 architecture drawings.

The first small architecture tweak in the E2B and E4B variants is that they adopt a shared KV cache scheme, where later layers reuse key-value states from earlier layers to reduce long-context memory and compute.

This KV-sharing was not invented by Gemma 4. For instance, see Brandon et al., “Reducing Transformer Key-Value Cache Size with Cross-Layer Attention” (NeurIPS 2024). But it’s the first popular architecture where I saw this concept applied. (Cross-layer attention is not to be confused with cross-attention.)

Before explaining KV-sharing further, let’s briefly talk about the motivation. As I wrote and talked about in recent months, one of the main recent themes in LLM architecture design is KV cache size reduction. In turn, the motivation behind KV cache size reduction is to reduce the required memory, which allows us to work with longer contexts, which is especially relevant in the age of reasoning models and agents. For more background on KV caching, see my “Understanding and Coding the KV Cache in LLMs from Scratch” article:

Practically all of the popular attention variants I described in my previous A Visual Guide to Attention Variants in Modern LLMs article are designed to reduce the KV cache size:

To pick a classic example (that Gemma 4 still uses): Grouped Query Attention (GQA) already shares key-value (KV) heads across different query heads to reduce the KV cache size, as illustrated in the figure below.

Figure 3: Grouped Query Attention (GQA) shares the same key (K) and value (V) heads among multiple query (Q) heads.

As mentioned before, Gemma 4 uses GQA. However, in addition to the KV sharing among queries as part of GQA, Gemma 4 also shares KV projections across different layers instead of computing it as part of the attention module in each layer. This KV-sharing scheme, also called cross-layer attention, is illustrated in the figure below.

Figure 4: Regular transformer blocks compute separate Q, K, and V projections in each attention module (left). Cross-layer attention designs (right) share the same K and V projections across multiple layers.

As briefly hinted at in the architecture overview in Figure 2, Gemma 4 E2B uses regular GQA and sliding window attention in a 4:1 pattern. (More precisely, Gemma 4 E2B uses MQA, which is the one-KV-head special case of GQA).

In the case of GQA (or MQA), the KV-sharing works like this. Later layers no longer compute their own key and value projections but reuse the KV tensors from the most recent earlier non-shared layer of the same attention type. In other words, sliding-window layers share KV with a previous sliding-window layer. Full-attention layers share KV with a previous full-attention layer. The layers still compute their own query projections, so each layer can form its own attention pattern, but the expensive and memory-heavy KV cache is reused across several layers.

For example, Gemma 4 E2B has 35 transformer layers, but only the first 15 compute their own KV projections; the final 20 layers reuse KV tensors from the most recent earlier non-shared layer of the same attention type. Similarly, Gemma 4 E4B has 42 layers, with 24 layers computing their own KV and the final 18 layers sharing them.

How much does this actually save? Since we share roughly half of the KVs across layers, we save approximately half of the KV cache size. For the smallest E2B model, this results in a 2.7 GB saving (at bfloat16 precision) in long 128K contexts, as shown below. (For the E4B variant, this saves about 6 GB at 128K.)

Figure 5: KV cache memory savings from GQA and cross-layer KV sharing in a Gemma 4 E2B-like setup. For simplicity, additional savings from sliding window attention are not shown.

The downside of KV-sharing is, of course, that it’s an “approximation” of the real thing. Or, more precisely, it reduces model capacity. However, according to the cross-layer attention paper, the impact can be minimal (for small models that were tested).

The Gemma 4 E2B and E4B variants include a second efficiency-oriented design choice called per-layer embeddings (PLE). This is separate from the KV-sharing scheme above.

KV sharing reduces the KV cache. PLE is instead about parameter efficiency, where it lets the small Gemma 4 models use more token-specific information without making the main transformer stack as expensive as a dense model with the same total parameter count.

For instance, the “E” in Gemma 4 E2B and E4B stands for “effective”. Concretely, Gemma 4 E2B is listed as 2.3B effective parameters, or 5.1B parameters when the embeddings are counted. (Similarly, Gemma 4 E4B is listed as 4.5B effective parameters, or 8B parameters with embeddings).

In short, in the “E” models, the main transformer-stack compute is closer to the smaller number, while the larger number includes the additional embedding-table layers. (For an illustration of how embedding layers work, see my “Understanding the Difference Between Embedding Layers and Linear Layers” code notebook.)

Conceptually, the new PLE path looks like this:

Figure 6: Simplified Gemma 4 block with the PLE residual path. The normal block first computes the attention and feed-forward residual updates. The resulting hidden state gates the layer-specific PLE vector, and the projected PLE update is added as an extra residual update at the end of the block.

The PLE vectors themselves are prepared outside the repeated transformer blocks. In simplified form, there are two inputs to the PLE construction. First, the token IDs go through a per-layer embedding lookup. Second, the normal token embeddings go through a linear projection into the same packed PLE space. These two pieces are added, scaled, and reshaped into a tensor with one slice per layer. Note that each block then receives its own slice.

Figure 7: Simplified PLE construction. The token IDs provide a per-layer embedding lookup, while the normal token embeddings are projected into the same space. The two contributions are combined and reshaped so that each transformer block receives its own layer-specific PLE slice.

The important detail is that PLE does not give each transformer block a full independent copy of the normal token embedding layer. Instead, the per-layer embedding lookup is computed once. Then, as mentioned before, it gives each layer a small token-specific embedding slice (via “reshape / select layer l”.

So, for each input token, Gemma 4 prepares a packed PLE tensor that contains one small vector per decoder layer. Then, during the forward pass, layer l receives only its own slice (ple_l in the Gemma4WithPLEBlock in figure 6).

Inside the transformer block, the regular attention and feed-forward branches run as usual. First, the block computes the attention residual update. Then it computes the feed-forward residual update. After that second residual add, the resulting hidden state, which I denoted as z in the pseudocode in figure 6, is used to gate the layer-specific PLE vector. The gated PLE vector is projected back to the model hidden size, normalized, and added as one extra residual update.

So the useful mental model is that the transformer block still has the same main attention and feed-forward path, but Gemma 4 adds a small layer-specific token vector after the feed-forward branch. This increases representational capacity through embedding parameters and small projections. This adds computational overhead but avoids the cost of scaling the entire transformer stack to the larger parameter count.

But why PLEs? The simpler alternative would be to make the dense model smaller, using fewer layers, narrower hidden states, or smaller feed-forward networks. That would reduce memory and latency, but it also removes capacity from the parts of the model that do the main computation.

The PLE design keeps the expensive transformer blocks closer to the smaller “effective” size, while storing additional capacity in per-layer embedding tables. These are much cheaper to use than adding more attention or FFN weights, since they are mainly lookup-style parameters that can be cached.

Also, we have to take Google’s word here that this is an effective and worthwhile design choice. It would be interesting to see some comparison studies to see how this E2B design compares to a regular Gemma 4 2.3B model and a regular Gemma 4 5.1B model.

Also, in principle, PLE is not inherently limited to small models. We could attach per-layer embedding slices to larger models, too. However, larger models already have sufficient capacity where these extra embeddings may not help that much. Also, for larger models, we already use MoE designs as a trick to increase capacity while keeping the compute footprint smaller.

By the way, if you are interested in a relatively simple and readable code implementation, I implemented the Gemma 4 E2B and E4B models from scratch here.

Laguna is the first open-weight model by Poolside, a Europe-based company focused on training LLMs for coding applications. Several of my former colleagues joined Poolside in recent years, and they have a great team with lots of talent. It’s just nice to see more companies also releasing some of their models as open-weight variants.

Anyways, the Laguna XS.2 architecture depicted below looks very standard at first glance. However, one detail that I didn’t show (/try to cram into there) is a concept we can refer to as “Layer-wise attention budgeting”.

Figure 9: Poolside’s Laguna XS.2 architecture.

Part of the idea behind the attention budgeting here is that instead of giving every transformer layer the same full attention budget, Laguna XS.2 varies the attention cost by layer. It has 40 layers total, with 30 sliding-window attention layers and 10 global/full attention layers. As usual, the sliding-window layers only attend over a local window (here: 512 tokens), which keeps the KV cache and attention computation cheaper. The global layers are more expensive but preserve the ability to access all information in the context window.

This mixed sliding-window + global/full attention pattern is not unique to Laguna XS.2 and is used by many other architectures (including Gemma 4).

But what’s new is the use of per-layer query-head counts. For instance, the Hugging Face model hub config.json includes a num_attention_heads_per_layer setting, so layers can have different numbers of query heads while keeping the KV cache shape compatible.

Figure 10: Per-layer query-head budgeting in Laguna, where full attention layers use 6 query heads per KV head, and sliding window attention layers use 8 query heads per KV head.

So Laguna XS.2 gives more query heads to sliding-window layers and fewer query heads to global layers, while keeping the KV heads fixed at 8. That is the actual layer-wise head budgeting in the config.

Laguna XS.2 is one of the most prominent recent examples of this per-layer query-head budgeting in a production-style open model. But the broader idea of varying model capacity by layer goes back to (at least) Apple’s 2024 OpenELM.

And again, what’s the point of such a design? Similar to KV-sharing, the point is to spend attention capacity where it is most useful, instead of giving every layer the same budget. Specifically, full-attention layers are expensive because they look across the whole context, so Laguna gives them fewer query heads compared to sliding window attention modules.

(Besides, another smaller implementation detail is that Laguna also applies per-head attention-output gating; this is somewhat similar to Qwen3-Next and others, which I also omit here since I covered it in earlier articles.)

Similar to Laguna, ZAYA1-8B is another new player on the open-weight market. It is developed by Zyphra, and one of the interesting details around the release is that the model was trained on AMD GPUs rather than the more common NVIDIA GPU (or Google TPU) setup.

The main architecture detail, though, is Compressed Convolutional Attention (CCA), used together with grouped-query attention. Unlike MLA-style designs that mainly use a latent representation as a compact KV cache format, CCA performs the attention operation directly in the compressed latent space, but more on that later.

(Sidenote: the ZAYA1-8B config.json lists 80 alternating layer entries rather than 40 conventional transformer blocks. These entries alternate between CCA/GQA attention and MoE feed-forward layers. But for the architecture figure, it is more convenient to visualize this as 40 repeated attention + MoE pairs, which is conceptually equivalent.)

Figure 11: Zaya1 (8B) with transformer blocks featuring compressed convolutional attention.

As hinted at in the figure above, ZAYA1-8B uses Compressed Convolutional Attention (CCA) together with a 4:1 GQA layout. The key point is that its attention block is built around CCA rather than a standard sliding-window attention block.

What is Compressed Convolutional Attention?

I would say CCA is related in spirit to Multi-head Latent Attention (MLA) in DeepSeek’s models, since both introduce a compressed latent representation into the attention block. However, they use that latent space differently. MLA mainly uses the latent representation to reduce the KV cache. In MLA, the KV tensors are stored compactly and then projected into the attention-head space for the actual attention computation.

Figure 12: Regular Multi-head Attention (MHA) and Multi-head Latent (MLA) attention side by side.

CCA compresses Q, K, and V and performs the attention operation directly in the compressed latent space. This is why CCA can reduce not only KV cache size, but also attention FLOPs during prefill and training.

Figure 13: Multi-head Latent Attention (MLA) and Compressed Convolutional Attention (CCA) side by side.

As Figure 13 above illustrates, in CCA, the compressed, latent representations enter the attention mechanism directly, and the resulting compressed attention vector is then up-projected.

Note that this is called Compressed Convolutional Attention, not just Compressed Attention, since there is an additional convolutional mixing happening on the latent K and Q representations. The convolutional mixing part is not shown in Figure 12, because it would have been too crammed, but it’s relatively straightforward.

As hinted at in Figure 12, the convolutional mixing happens directly on the compressed Q and K tensors. The point is that compression makes Q, K, and V narrower, which saves compute and cache, but it can also make attention less expressive. The convolutions are a cheap way to give the compressed Q and K vectors more local context before they are used to compute attention scores. (The convolutional mixing is only applied to Q and K, not V, because Q and K determine the attention scores, while V represents the content that gets averaged via these scores).

Figure 14: conceptual overview of the sequence-mixing convolution

Next to the sequence mixing shown in Figure 13, there is also a channel mixing component. It’s in principle similar though, so I am omitting the illustration.

CCA appears to be a Zyphra-introduced attention mechanism that predates the ZAYA1-8B technical report. The standalone CCA paper, Compressed Convolutional Attention: Efficient Attention in a Compressed Latent Space, was first posted in October 2025 and explicitly introduces CCA. ZAYA1-8B then uses this mechanism as one of the core pieces.

But the question is, “is it better than MLA”? According to the CCA paper’s own experiments, yes, they report CCA outperforming MLA under comparable compression settings.

Overall, the interesting part here is really the new attention mechanism. The model also uses a pretty extreme (= very sparse) MoE setup, with only one routed expert active per token, but that part is more familiar. CCA is more unusual because it performs the attention operation directly in a compressed latent space, and then uses convolutional mixing on the compressed Q and K representations to make this compressed attention less limiting. So, in short, ZAYA1-8B is not only trying to save compute in the feed-forward layers, but also in the attention mechanism itself.

DeepSeek V4 was the biggest release of the year so far, both in terms of hype and model size. Interestingly, DeepSeek V4-Pro is also the most parameter-sparse MoE among the models in the table below, measured by active-parameter share, as summarized in the table below.

Caveat: active parameter share is only one lens. It does not capture KV cache size, attention pattern, context length, routing overhead, hardware efficiency, or training quality. But it is a helpful, quick check when comparing sparse models.

There’s a lot to say about DeepSeek V4, but since it’s been all over the news already, and to stay on topic regarding architecture tweaks, I will focus on the two most relevant parts that are new compared to previous architectures:

  1. mHC for a wider residual pathway,

  2. CSA/HCA for long-context attention compression and sparsity

Looking at the DeepSeek V4 architecture drawing below, there seems to be a lot going on. The useful way to read it is to separate the residual-path change, mHC, from the attention-path changes, CSA/HCA, and compressed attention caches.

Figure 17: DeepSeek V4-Pro architecture overview.

Let’s start with the mHC component of DeepSeek V4. This goes back to a research paper that the DeepSeek team shared last year (31 Dec 2025, mHC: Manifold-Constrained Hyper-Connections). However, in this paper, the technique was only tested on an experimental 27B scale model. Now, we see it in their flagship release, which is a good sign that this idea actually works well in production.

The main idea behind mHC here is to modernize the design of the residual connections inside the transformer block, which is refreshing, because architecture tweaks are usually focused on the attention mechanism, normalization layer placement, and MoE parts.

Now, mHC is based on previous work on hyper-connections (see Hyper-connections by Zhu et al., 2024), which we should briefly discuss first. Hyper-connections essentially modify the single residual stream inside the transformer block by replacing it with several parallel residual streams and learned mappings between them.

(For those new to residual connections, I made a video on residual neural networks many years ago, where I explained the general mechanism.)

The idea behind hyper-connections is to widen the residual stream. We can think of this as keeping several parallel residual streams, with an additional Res Mapping linear transformation that mixes them across layers. Since the Attention or MoE layer itself still operates on the normal hidden size, hyper-connections also add a Pre Mapping that combines the parallel residual streams into one normal hidden vector for the layer, and a Post Mapping that distributes the layer output back across the parallel residual streams. This is visually summarized in the figure below.

Figure 18: Regular transformer block (top) vs transformer block with hyper-connections (bottom) using annotated figures from the mHC paper, https://arxiv.org/abs/2512.24880.

The figure below focuses on the attention-layer portion of the transformer block, but the same concept applies to the second residual branch around the MoE layer.

The purpose of hyper-connections is to make the residual pathway more expressive without making the actual Attention or MoE layer wider. This is only mildly more expensive in FLOPs because the extra mappings operate over the small residual-stream axis, for example, n = 4 in DeepSeek V4, not over a huge hidden dimension.

In the original hyper-connections paper, the 7B OLMo MoE experiment goes from 13.36G to 13.38G FLOPs per token, which is basically unchanged. In terms of reported gains, there were modest (but consistent) improvements, as shown in the figure below.

(However, only looking at FLOPs is a bit simplistic. The widened residual state still has to be stored, moved through memory, mixed, etc. So the practical overhead can come more from memory traffic and implementation complexity than from arithmetic, which is not explicitly measured. However, given that DeepSeek V4 is all about efficiency, it seems to be a worthwhile addition.)

Also, as shown in the figure above, metrics reached the baseline’s performance using roughly half the training tokens.

The main change from regular hyper-connections (HC) to manifold-constrained hyper-connections (mHC) is that the mappings are no longer left unconstrained. In regular HC, the Res Mapping is a learned matrix that mixes the parallel residual streams, but stacking many such matrices can amplify or shrink signals unpredictably.

In mHC, this residual mapping is projected onto the manifold of doubly stochastic matrices, meaning all entries are non-negative and each row and column sums to 1. This makes the residual mixing behave more like a stable redistribution of information across streams. The Pre Mapping and Post Mapping are also constrained to be non-negative and bounded, which avoids cancellation when reading from and writing back into the widened residual state. In short, mHC keeps the richer residual mixing of HC, but adds constraints so it scales more safely, which becomes more relevant for larger (deeper) models.

Otherwise, the main idea of using parallel residual streams remains, as shown in the figure below.

Figure 20: Transformer block with hyper-connections (HC) and manifold-constrained hyper-connections (mHC) using annotated figures from the mHC paper, https://arxiv.org/abs/2512.24880.

In the mHC paper, using a 27B parameter model for the experiments, the DeepSeek team’s optimized implementation (with fusion, recomputation, and pipeline scheduling) adds only 6.7% additional training time overhead for 4 residual streams (n = 4) throughout all transformer blocks compared to the single-stream baseline.

To sum up this section, HC/mHC changes how information is carried around these layers by replacing the single residual stream with several interacting residual streams, with the additional stability constraints added in mHC, while adding minimal compute overhead. Also, it pairs well with the CSA/HCA attention changes, which modify other parts of the transformer block, which I will discuss below.

The other major DeepSeek V4 architecture change is on the attention side. Again, the motivation is that at very long context lengths, attention becomes expensive not only because of the attention score computation, but also because the KV cache grows with the sequence length. DeepSeek V4 addresses this issue with a hybrid of two compressed-attention mechanisms, Compressed Sparse Attention (CSA) and Heavily Compressed Attention (HCA).

For a refresher, I recommend checking out my previous “A Visual Guide to Attention Variants in Modern LLMs” article, which covers Multi-head Latent Attention (MLA) and DeepSeek Sparse Attention (DSA), among others.

The first thing to note is that CSA/HCA in DeepSeek V4 is a different kind of compression than the MLA-style compression used in DeepSeek V2/V3. Where MLA mainly compresses the per-token KV representation, CSA and HCA compress along the sequence dimension. So, instead of keeping one full (or compressed) KV entry for every previous token, they summarize groups of tokens into fewer compressed KV entries. Consequently, the cache gets shorter. DeepSeek V4 also uses compact compressed entries and shared-KV attention, but the main distinction from MLA is the sequence-length compression. This is illustrated in the figure below.

Figure 21: Conceptual comparison of MLA-style per-token latent caching, CSA, and HCA. MLA compresses the stored KV representation but keeps one latent entry per token. CSA shortens the sequence more mildly with m=4 and sparse top-k selection, while HCA uses much heavier sequence compression with m’=128 and dense attention over the shorter cache.



The quality tradeoff for CSA/HCA is also different from MLA. As shown in the figure above, MLA compresses the representation stored for each token, but it still keeps one latent KV entry per token. CSA and especially HCA go further by reducing the number of sequence entries themselves, so the model gives up some token-level info in exchange for much lower long-context cost.

Again, it’s all about reducing long-context cost, but this trade-off can hurt modeling quality if the compression is too strong, which is why DeepSeek V4 does not rely on one compression scheme alone but alternates between CSA and HCA. CSA uses a milder compression rate and a DeepSeek Sparse Attention (DSA)-style selector, HCA uses much heavier compression for cheaper global coverage, and both keep a local sliding-window branch for recent uncompressed tokens. This sparse selection in CSA builds on DeepSeek Sparse Attention (DSA), which I discussed in more detail in my earlier DeepSeek V3.2 write-up.

HCA is the more aggressive variant of the two. It compresses every 128 tokens into one compressed KV entry, but then uses dense attention over those heavily compressed entries. In other words, CSA keeps more details but uses sparse selection, while HCA keeps far fewer entries and can afford dense attention over them, as illustrated in the figure below. This makes the two mechanisms somewhat complementary, which is why DeepSeek V4 interleaves CSA and HCA layers rather than using only one of them.

Figure 22: CSA selects a sparse set of compressed history blocks, while HCA attends densely over more heavily compressed blocks. Both paths also include recent uncompressed KV entries through a 128-token sliding-window branch.

The DeepSeek V4 paper reports that, at a 1M-token context length, DeepSeek V4-Pro uses only 27% of the single-token inference FLOPs and 10% of the KV cache size compared with DeepSeek V3.2, which uses MLA and DeepSeek Sparse Attention (DSA). DeepSeek V4-Flash is even smaller, at 10% of the FLOPs and 7% of the KV cache size relative to DeepSeek V3.2.

Figure 23. Reported 1M-context efficiency numbers from the DeepSeek V4 paper, relative to DeepSeek V3.2.

By the way, I would not describe CSA/HCA as “better” than MLA in a general sense. CSA/HCA is a more aggressive long-context design. And it’s also more complicated for sure. Unfortunately, there is no ablation study in the paper. But overall, the paper reports strong overall modeling results, including DeepSeek V4-Flash-Base outperforming DeepSeek V3.2-Base on a majority of base-model benchmarks and strong 1M-token retrieval results, but these results are for the full DeepSeek V4 recipe, which also includes better data, Muon-based optimization, mHC, precision/storage optimizations, and training/inference-system changes.

Personally, for now, I would treat CSA/HCA as an efficiency-focused long-context design that appears to preserve modeling quality well in their large flagship model(s) but not necessarily universally better than MLA.

Overall, the interesting pattern this year is that most new open-weight models try to make long-context inference cheaper without just shrinking the model in terms of total parameters. For instance,

  • Gemma 4 reduces KV-cache memory with cross-layer KV sharing and adds capacity via per-layer embeddings.

  • Laguna XS.2 tweaks how much attention capacity each layer gets.

  • ZAYA1-8B moves attention into a compressed latent space.

  • DeepSeek V4 adds constrained residual-stream mixing and compressed long-context attention.

All of these tweaks add more complexity, which seems to be where LLM architecture is going right now.

My main takeaway is that the transformer block is still changing, but in fairly targeted ways. The basic recipe is still based on the original GPT decoder-only transformer architecture, but many parts are upgraded or replaced, and they get more specialized for longer contexts and more efficient inference, whereas the qualitative modeling performance seems largely driven by data quality (and quantity) and training recipes.

The question many of you asked me in the past is centered on when (or if) transformers are being replaced with something else. Of course, there are other designs like diffusion models, but transformers remain the status quo for state-of-the-art architecture releases.

However, with each increasing yearly release quarter, we get more and more tweaks. While it was possible to implement a basic transformer block in perhaps 50-100 lines of PyTorch code, these tweaks (esp. around the attention variants) probably 10x the code complexity. This is not an inherently bad thing as these tweaks reduce (not increase) runtime costs. However, it’s becoming increasingly difficult to gain a clear understanding of the individual components and their interactions.

Figure 24: The evolution from GPT-2 (2019) to DeepSeek V4-Pro (2026)

For instance, I am fairly certain that someone who is diving into LLM architectures for the first time will be totally overwhelmed when seeing the DeepSeek V4 source code. However, by starting with the original decoder-style LLM (GPT/GPT-2) and then gradually adding / learning about these new components one at a time, we can keep the learning effort manageable. The moral of the story, I guess, is to keep learning, one architecture at a time :).


By the way, I am very excited to share that I finished writing Build A Reasoning Model (From Scratch) and all chapters are in early access now. The publisher and I worked hard on the final layouts in the past month, and it’s going to be send to the printer this week. (Good news: the print version will be in color this time!)

This is probably my most ambitious book so far. I spent about 1.5 years writing it, and a large number of experiments went into it. It is also probably the book I worked hardest on in terms of time, effort, and polish, and I hope you’ll enjoy it.

The main topics are

There is a lot of discussion around “reasoning” in LLMs, and I think the best way to understand what it really means in the context of LLMs is to implement one from scratch!

원문 보기 https://magazine.sebastianraschka.com/p/recent-developments-in-llm-architectures