목록AI 일반/모델, 아키텍처, 구현 (15)
토니의 연습장

- Grouped Multi-Query Attention- KV Cache

ex) linear.py 의 내부 사용 method 내부는 C++ 로 아래와 같이 구현되어 있음
요약BatchNorm: 배치 전체 통계 기반, CNN에 특화, 큰 배치에서 최고의 성능LayerNorm: 샘플별 통계 기반, 시퀀스·토큰 모델에 필수, 작은 배치에도 안정이미지 분류·객체 검출(CNN 계열)배치 크기가 충분하다면 → BatchNorm배치가 매우 작거나 온라인 추론 위주라면 → GroupNorm 또는 LayerNorm 고려자연어 처리·시퀀스 모델Transformer, RNN 계열 → LayerNorm특히 auto-regressive 생성(decoding) 시 causal 구조와 잘 맞음일반 MLP배치 독립성이 필요하면 → LayerNorm배치 통계가 풍부하면 → BatchNorm 왜 LayerNorm을 쓰는가?배치 크기 독립성BatchNorm은 배치 전체의 통계량을 사용하지만, LayerN..

* 실제 사용은 하단 전체 코드 참고미래 토큰 차단용 마스크 (causal mask)self.register_buffer( 'mask', torch.triu(torch.ones(CONTEXT_LENGTH, CONTEXT_LENGTH), diagonal=1)) (L, L) 크기의 상삼각 행렬 생성 (L = CONTEXT_LENGTH).대각선 위쪽(미래 위치)에 1이 채워져 있고, 나머지는 0.register_buffer로 저장하면 파라미터가 아니지만 .to(device) 등 이동 시 함께 따라갑니다.이후 forward에서scores = scores.masked_fill(self.mask == 1, float('-inf'))처럼 사용해서 “미래 정보”가 보이지 않도록 막음. Transformer의..

1. Data (preparing and loading) 2. Build model3. Train model PyTorch training loop PyTorch testing loop 4. Inference# 1. Set the model in evaluation modemodel_0.eval()# 2. Setup the inference mode context managerwith torch.inference_mode(): # 3. Make sure the calculations are done with the model and data on the same device # in our case, we haven't setup device-agnostic code yet so our data a..
model 로 train 및 test 한 후에 train/test loss value 를 출력하고자 할 때, PyTorch 텐서(requires_grad=True) 상태에서 바로 NumPy 배열로 변환하려고 하기 때문에 발생합니다. Matplotlib에서 데이터를 플롯할 때는 numpy(), item(), 또는 해당 텐서를 분리(detach())해서 넘겨주어야 합니다. 이렇게 하면 텐서 자체를 유지하면서도 NumPy로 변환할 수 있습니다.loss_values.append(loss.detach().numpy())# 혹은 CPU로 먼저 보낼 경우loss_values.append(loss.detach().cpu().numpy()) 그런데 가장 출력 등의 용도로 사용하기 위해 간단하고 편리한 방법은, 스칼라 텐..
class CastOutputToFloat(nn.Sequential): def forward(self, x): return super().forward(x).to(torch.float32)model.lm_head = CastOutputToFloat(model.lm_head) 모델의 출력이 32비트 정밀도로 반환되도록 하기 위해 CastOutputToFloat 클래스를 정의하고, lm_head의 출력을 32비트로 변환하여 안정적인 출력이 가능하도록 합니다.이 코드를 통해 모델은 메모리 사용량을 최소화하면서 8비트 정밀도로 로드되고, 파라미터를 동결하여 일부 파라미터만 훈련이 가능하도록 설정되었습니다.위 코드에서 super().forward(x) 호출의 이유는 CastOutputToFloat 클래스가 ..

# For nn.Conv2d: (reduce the size of the image for prediction : Discriminator)output_size = (n + 2 * pad - ks) // stride + 1 # For nn.ConvTranspose2d: (grow from a value to full image for generation : Generator)output_size = (n - 1) * stride - 2 * padding + ks