Share
Sign In
Lighthouse LLM
LLM 컨텍스트 길이 늘이기
E
Eunyoung Lee
👍🏻
1
😍
1
컨텍스트 길이 늘이기
컨텍스트 길이는 언어 모델이 한 번에 처리할 수 있는 토큰의 개수입니다.
LLM이 처리할 수 있는 토큰 개수는 한정적이기 때문에 요약 태스크와 같이 긴 텍스트를 다루는 태스크를 위해서는 컨텍스트 길이가 긴 모델을 사용해야 합니다. 예를 들어 LLaMA3의 경우, 컨텍스트 길이가 8192기 때문에 최대 8192개의 토큰까지 밖에 다루지 못하고 더 긴 텍스트가 들어갈 경우 아웃풋 출력을 제대로 하지 못합니다.
또한 트랜스포머 기반 LLM은 메모리 footprint와 계산 시간이 지수적으로 증가하기 때문에 기존 트랜스포머 아키텍처로는 긴 시퀀스를 처리하는 데 비용이 많이 소요됩니다.
컨텍스트 길이가 긴 한국어 LLM을 사용하고자 LLM의 컨텍스트 길이를 효율적으로 늘이기 위해 조사 및 시도해본 다양한 방법들에 대해 알아보겠습니다.
컨텍스트 길이 확장 정리 표
파인튜닝 필요 여부
확장 가능 범위
사용해봤는지 여부
LongLoRA
O
8배
파인튜닝 자원 부족
Position Interpolation
O
8배
파인 튜닝 자원 부족
Dynamic NTK
X
2배
llama.cpp에서 사용 가능
LongLM
X
4배
llama.cpp에서 사용 가능
ChunkLlama
X
4배
코드에서 적용 가능
Infini-attention
O
2M 까지
파인튜닝 자원 부족
LongLoRA
shifted sparse attention을 사용한 파인튜닝을 통하여 컨텍스트 길이를 늘이는 방법
shifted sparse attention($S^2$-Attn)과 LoRA 파인튜닝을 사용하여 효과적으로 컨텍스트 확장을 가능하게 함
1.
feature를 헤드 차원을 따라 두 개의 덩어리로 나눔
2.
둘 중 하나의 토큰이 그룹 사이즈의 반(1)만큼 옮겨짐(shift)
3.
토큰을 그룹(2개씩)으로 나누어 batch 차원으로 다시 구조함
어텐션은 각 그룹 내에서만 계산이 되고, shift를 통하여 정보가 흐름
# B: batch size; N: no. of batch; S: sequence length or number of tokens; G: group size; # H: number of attention heads; D: dimension of each attention head # qkv in shape (B, N, 3, H, D), projected queries, keys, and values # Key line 1: split qkv on H into 2 chunks, and shift G/2 on N qkv = cat((qkv.chunk(2, 3)[0], qkv.chunk(2, 3)[1].roll(-G/2, 1)), 3).view(B*N/G,G,3,H,D) # standard self-attention function out = self_attn(qkv)
두 줄의 코드만으로 구현 가능
Rope-based Position Interpolation
RoPE Embedding
RoPE는 시퀀스의 각 위치마다 고유한 값의 회전을 통하여 절대 위치 임베딩과 상대 위치 임베딩을 통합하는 방법
Llama와 Mistral 같은 모델에서 사용
Interpolation과 Extrapolation
Extrapolation(보외법): 알려진 값들 외부의 위치에 있는 값을 추정하는 것, 프리트레인 한 범위 밖을 예측
Interpolation(보간법): 알려진 지점의 값 사이에 위치한 값을 알려진 값들로부터 추정하는 것, 프리트레인 한 범위 내에 존재하도록 위치 인덱스를 강제로 다운스케일링
Position Interpolation
보간법을 사용해 위치 인덱스를 기존의 컨텍스트 윈도우 사이즈에 맞게 선형적으로 다운스케일링하여 컨텍스트 길이를 늘리는 방법
예를 들어, 컨텍스트 길이가 512 토큰인 모델을 1024 토큰까지 늘이기 위해서, 보간법을 통하여 512 토큰을 1024 토큰에 있을 위치로 바꾸어 계산함
Llama와 같이 RoPE 기반 임베딩을 사용하는 모델에 RoPE 임베딩을 수정하여 적용 가능하며 파인튜닝을 통하여 16배까지 컨텍스트 길이 확장
NTK-Aware Scaled RoPE - Dynamic NTK interpolation
파인튜닝 없이 NTK 이론을 적용하여 컨텍스트 길이를 두 배 이상 늘리는 방법
Neural Tangent Kernel(NTK)
경사 하강법 동안 신경망이 어떻게 진화하는지를 설명하는 커널로, 충분한 신경망의 층을 가진 신경망을 경험적 손실(train 데이터셋에서의 학습)을 최소화하도록 학습하면 일관되게 전역 최소값으로 수렴하는 이유에 대한 설명을 제공
한 샘플 데이터에서 모델 파라미터를 업데이트 하는 것이 다른 샘플에 어떻게 영향을 끼치는가?
NTK-Aware Scaled RoPE
NTK 이론에 따르면, 입력 차원(단어 임베딩 차원)이 낮고 해당 임베딩에 고주파 성능이 부족하면 심층 신경망이 고주파 정보를 학습하는 데 어려움을 겪음
RoPE의 경우 토큰의 위치 정보를 1차원에서 복잡한 다차원으로 확장하기 때문에 위와 같은 문제가 발생함
NTK-Aware interpolation은 고주파의 손실을 고려하는 방법으로, RoPE에 NTK 이론을 적용하면, 매우 가까운 토큰의 순서와 위치를 네트워크가 인지하지 못하도록 하여 RoPE의 푸리에 공간(위치 임베딩을 주파수로 변환한 것)을 선형적으로 interpolating할 수 있음
RoPE는 푸리에 공간과 여러 모로 비슷하기 때문에 주파수로 변형이 가능한데, RoPE 임베딩을 무분별하게 늘리면 네트워크가 매우 유사하면서도 매우 가까운 토큰을 해결하기 위해 필요한 중요한 고주파 세부 정보가 손실됨
RoPE 임베딩을 interpolating할 때 고주파 정보 손실 문제를 해결하기 위해, RoPE의 모든 차원을 동일하게 한 계수 s로 스케일링하는 대신, 고주파 성분은 덜 스케일링하고 저주파 성분은 더 많이 스케일링하여 여러 차원에 interpolation 압력을 분산시킴
예를 들어, 0.25로 scale down 한 경우에는 위치 2048이 512처럼 보이도록 할 수 있음
Dynamic NTK interpolation
스케일 계수 $s = L′/L$ 는 연장된 컨텍스트 길이와 기존 컨텍스트 길이 간의 비율, $l′$은 현재 컨텍스트 길이
신경망에서 계산을 할 때마다 위치 임베딩은 스케일 계수 s를 업데이트하는데, s는 $max⁡(1,l′/L)$로 계산되며, 이 방법은 모델이 학습된 컨텍스트 한계 L′에 도달했을 때 즉시 성능이 급격히 저하되는 대신, 점진적으로 성능이 저하되도록 함
→ 코드에서도 간단하게 적용이 가능하고 llama.cpp에서도 사용 가능
LongLM
변형된 어텐션을 사용하여 파인튜닝 없이 컨텍스트 길이를 4배까지 늘릴 수 있는 방법
입력 시퀀스가 컨텍스트 길이를 넘어서면 모델이 이전에 보지 못한 포지션(O.O.D, Out Of Distribution)을 마주하게 되고, 성능이 저하됨
O.O.D. 위치를 모델이 볼 수 있도록 학습된 범위 내로 변화하기 위해 floor division을 사용
Grouped attention
토큰을 그룹으로 묶어, 모델이 시퀀스를 학습한 범위보다 더 길게 처리할 수 있음
bi-level 어텐션 정보(grouped attention과 neighbour attention)를 활용한 SelfExtend를 사용하여 LLM의 컨텍스트 윈도우 늘리기, 두 단계의 어텐션은 추론 중에 기존 모델의 셀프 어텐션 매커니즘에 기반하여 계산됨
grouped attention: 멀리 있는 토큰 간의 의존성을 잡아냄
neighbour attention: 특정 범위 안의 가까운 토큰 간의 의존성을 잡아냄, 일반 어텐션 사용
SelfExtend
일반 어텐션과 그룹화된 어텐션 영역 사이의 부드러운 전환을 보장하기 위해 그룹화된 어텐션에 대한 상대적 위치에 wn - (wn // G) 의 이동을 도입 후 neighbour 토큰 윈도우 바깥의 어텐션 값은 그룹화된 어텐션의 값으로 대체함으로써 어텐션의 두 부분을 병합
L: context window size, 7
wn: Window size for neighbour tokens, 4
G: Group size for grouped attention, 2
ChunkLLaMA
텍스트를 Chunk로 분해하여 파인튜닝 없이 Llama 모델의 컨텍스트 길이를 4배로 늘일 수 있는 방법
DCA(Dual Chunk Attention): 긴 시퀀스의 어텐션 계산을 pretraining window 사이즈 보다 작은 chunk 기반 모듈로 분해하여 같은 chunk 내와 떨어져 있는 chunk의 토큰 간 상대적 위치 정보를 효과적으로 잡아냄, extrapolation 기술
intra-chunk attention: 같은 chunk 내의 토큰을 처리
inter-chunk attention: 떨어져 있는 chunk 간의 토큰 처리
successive chunk attention: 떨어져 있으면서 연속적인 토큰을 처리
NTK, Positional Interpolation 같은 방법과 직교하기 때문에 함께 사용이 가능
Infini-attention
적은 추가 메모리 사용으로 2M 까지 컨텍스트 길이 연장 가능하며 빠른 추론 가능, Gemini-Pro에 적용된 방법
compressive memory system
한정된 저장공간과 계산 비용으로 저장과 불러오기하는 데 있어 고정된 수의 파라미터 유지 가능
정보가 나중에 복원될 수 있도록 파라미터를 바꾸면서 새로운 정보가 메모리에 추가됨
Infini-attention
시퀀스의 세그먼트 단위로 동작하며, 매번 현재 세그먼트에서의 지역 어텐션 계산
모든 Query, Key, Value 값을 장기 메모리 통합과 회수에 사용
이전 Key와 Value 상태를 버리는 대신 압축 메모리에 저장하고, 다음 시퀀스를 처리할 때 Query로 Value를 검색
장기 메모리에서 가져온 Value와 로컬 어텐션 문맥을 종합하여 마지막 문맥 아웃풋을 계산
Continual Pre-training으로 학습
출처
Kp
Subscribe to 'kpmg-lighthouse'
Welcome to 'kpmg-lighthouse'!
By subscribing to my site, you'll be the first to receive notifications and emails about the latest updates, including new posts.
Join SlashPage and subscribe to 'kpmg-lighthouse'!
Subscribe
👍🏻
1
😍
1
Lighthouse
Improving Text Embeddings with Large Language Models
논문 개요 논문명: Improving Text Embeddings with Large Language Models 링크 : https://arxiv.org/pdf/2401.00368 출간일 : 2023.12 출간 학회 : ACL 저자 : Liang Wang, Nan Yang, Xiaolong Huang, Linjun Yang, Rangan Majumder, Furu Wei 소속 : Microsoft Corporation 인용 수 : 51 코드 : https://github.com/microsoft/unilm/tree/master/e5 Abstract 합성 데이터와 1K 학습 스텝보다 적은 스텝을 사용하여 높은 퀄리티의 텍스트 임베딩 얻는 방법 소개 기존 방법은 많은 양의 weakly-supervised text pair로 프리트레인을 하고 라벨링 된 데이터로 파인튜닝을 해야했음 proprietary(독자적) LLM을 활용하여 93개 언어에 걸쳐 임베딩 태스크를 위한 합성 데이터 생성 오픈 소스 디코더-only LLM을 합성 데이터로 standard contrastive loss로 파인튜닝 라벨링 데이터를 하나도 사용하지 않고 좋은 성능을 보임 합성 데이터와 라벨링 데이터를 섞어 파인튜닝을 더 진행하여 BEIR와 MTEB에서 sota 달성 Introduction 이전 연구들(Glove 등)에서 사전 학습된 단어 임베딩의 가중 평균이 semantic similarity를 측정하는 강력한 기준임을 보여줬지만, 이 방법들은 자연어의 풍부한 맥락 정보를 포착하지 못함(토큰 간의 관계 파악) 프리트레인 언어 모델 등장 이후 NLI 데이터셋에 BERT를 파인튜닝한 예시들: Sentence-BERT, SimCSE BGE, E5: multi-stage 학습 패러다임으로, 수십억 개의 weakly-supervised 텍스트 쌍에 대해 사전 학습 후 고품질 라벨 데이터셋에 대해 파인튜닝
Lighthouse
SELF-RAG: Learning to Retrieve, Generate and Critique Through Self-Reflection
안녕하세요! KPMG 라이트하우스 AI Engineer들은 매주 쏟아지는 LLM 및 모델관련 논문 스터디를 수행하고 실무에 적용해오고 있습니다. 그 중 일부를 발췌하여 여러분들께 공유드립니다. SELF-RAG: Learning to Retrieve, Generate and Critique Through Self-Reflection Abstract LLM은 자체 매개변수 지식에 의존하기 때문에 부정확한 답변을 생성하지만 RAG로 이런 문제를 줄일 수 있음 문서가 관련성이 있는지 확인하지 않은 무분별한 검색과 고정된 수의 검색 문서 통합은 성능을 저하시킴 Self-Reflective Retrieval-Augmented Generation 소개 LM을 on-demand로 상황에 맞게 검색할 수있게 학습시키고, ‘reflection token’을 사용하여 검색한 문서와 생성물을 성찰 reflection token 생성으로 추론 단계에서 LM을 제어하고 다양한 작업 요구사항에 맞춰 LM의 동작을 조정 가능 1. Introduction SELF-RAG: 온디맨드 검색과 self reflection을 통해 LLM의 생성 품질과 정확성 향상 임의의 LM을 end-to-end 방식으로 주어진 작업 입력에 대해 자체 생성 과정을 성찰하도록 학습, 태스크 아웃풋과 중간에 특별한 토큰(reflection token) 출력 Reflection 토큰은 retrieval과 critique 토큰으로 나뉘며 검색 필요성과 생성 성능을 표시
Lighthouse
Unlocking the Potential of LLMOps: A Practical Guide for Industry Application
In the ever-evolving landscape of artificial intelligence, Large Language Model Operations (LLM Ops) are emerging as a game-changer for businesses striving to harness the power of AI. Implementing LLM Ops effectively can propel your company to new heights, but it requires strategic planning and execution. Here are the key secrets to successfully applying LLM Ops in the industry. Understand Your Use Case: Before diving into LLM Ops, clearly define your business objectives and identify the specific problems you aim to solve. Whether it's customer service automation, content generation, or data analysis, a targeted approach ensures that the LLM's capabilities align with your needs. Data is King: Quality data is the backbone of any successful LLM application. Invest in curating, cleaning, and annotating your datasets. Ensure diversity and representativeness to avoid biases and enhance the model's performance across different scenarios. Infrastructure and Scalability: Deploying LLMs demands robust infrastructure. Leverage cloud platforms like AWS, Google Cloud, or Azure, which offer scalable resources tailored for high-computational tasks. This not only facilitates smooth operations but also accommodates future growth and increased workloads. Fine-Tuning and Customization: Generic models often fall short in specialized applications. Fine-tuning your LLM on domain-specific data can significantly improve accuracy and relevance. This step requires expertise but pays dividends in creating models that understand and predict user needs more precisely. Human-in-the-Loop: Integrate human oversight to ensure quality and reliability. Humans can provide critical feedback, correct errors, and introduce nuances that automated systems might miss. This collaborative approach enhances model trustworthiness and effectiveness. Continuous Monitoring and Iteration: LLM Ops is not a set-and-forget operation. Continuous monitoring for performance, biases, and anomalies is essential. Implement feedback loops and regularly update the model with new data to keep it relevant and accurate. Ethical Considerations: Ethics in AI cannot be overstated. Ensure transparency, fairness, and accountability in your LLM applications. Establish guidelines and frameworks to mitigate risks related to privacy, security, and societal impacts. By following these steps, businesses can unlock the full potential of LLM Ops, driving innovation and efficiency in their operations. Embrace the future of AI with confidence and transform your industry through smart, ethical, and effective LLM practices. Use Cases in the Finance Industry Automated Customer Support: LLMs can enhance customer service by providing instant, accurate responses to common inquiries. This reduces the burden on human agents and improves customer satisfaction. Fraud Detection: By analyzing transaction patterns and identifying anomalies, LLMs can help detect fraudulent activities in real-time, providing a layer of security and trust for financial institutions and their customers. Financial Forecasting: LLMs can process vast amounts of historical and real-time data to generate accurate financial forecasts. This aids in strategic planning, risk management, and decision-making.