---
title: "Jonas Kim (@bits-bytes-nn) | Hashnode"
description: "♾️ Life is complex. It has both real and imaginary parts. Read the latest articles by Jonas Kim on Hashnode."
url: "https://hashnode.com/@bits-bytes-nn"
---

@bits-bytes-nn

# Jonas Kim

@bits-bytes-nn · Seoul · Joined March 2025

♾️ Life is complex. It has both real and imaginary parts.

## Comments

[\# xformers 기반의 메모리 효율적인 인과적 어텐션 구현 def memory\_efficient\_causal\_attention(q, k, v): # 필요한 어텐션 점수만 계산 (마스킹된 점수는 계산하지 않음) batch\_size, seq\_len, num\_heads, head\_dim = q.shape # 출력 텐서 초기화 output = torch.zeros\_like(q) # 누적 소프트맥스 상태 추적 softmax\_scale = 1.0 / math.sqrt(head\_dim) m\_prev = torch.zeros((batch\_size, num\_heads, 1), device=q.device) # 최대값 저장 p\_sum = torch.zeros((batch\_size, num\_heads, 1), device=q.device) # 합 저장 o\_acc = torch.zeros((batch\_size, num\_heads, head\_dim), device=q.device) # 가중합 저장 # 순차적 처리로 메모리 사용 최소화 for i in range(seq\_len): # 현재 위치의 쿼리 qi = q\[:, i:i+1\] # \[B, 1, H, D\] # 현재 위치까지의 키와 값만 처리 (인과성) ki = k\[:, :i+1\] # \[B, i+1, H, D\] vi = v\[:, :i+1\] # \[B, i+1, H, D\] # 어텐션 점수 계산 (스케일링 포함) si = torch.matmul(qi, ki.transpose(-1, -2)) \* softmax\_scale # \[B, 1, H, i+1\] # Rabe & Staats 방식: 소프트맥스 최적화 mi = torch.max(si, dim=-1, keepdim=True)\[0\] m\_curr = torch.maximum(m\_prev, mi) # 이전 누적값 스케일 조정 scale\_factor = torch.exp(m\_prev - m\_curr) p\_sum = p\_sum \* scale\_factor o\_acc = o\_acc \* scale\_factor.unsqueeze(-1) # 새로운 어텐션 가중치 계산 pi = torch.exp(si - m\_curr) p\_sum = p\_sum + pi.sum(dim=-1, keepdim=True) # 출력 누적 (중간 어텐션 행렬 저장 없이) o\_acc = o\_acc + torch.matmul(pi, vi).squeeze(1) # 현재 위치 출력 계산 output\[:, i\] = o\_acc / p\_sum # 상태 업데이트 m\_prev = m\_curr return output](https://hashnode.com/posts/llama-open-and-efficient-foundation-language-models/67d994dd734a9902c7d34dfb/comment/67d99a4ff851bfc98f2e5a7e)

Comment · Article · Mar 18, 2025 · [LLaMA: Open and Efficient Foundation Language Models 논문 리뷰](https://hashnode.com/posts/llama-open-and-efficient-foundation-language-models/67d994dd734a9902c7d34dfb)
