AI-Master-Book
  • about AI-Master-Book
  • AI Master Book
    • 이상치 탐지 with Python
    • 베이지안 뉴럴네트워크 (BNN) with Python
    • 그래프 뉴럴네트워크 (GNN) with Python
    • 데이터 마케팅 분석 with Python
  • LLM MASTER BOOK
    • OpenAI API 쿡북 with Python
    • 기초부터 심화까지 RAG 쿡북 with Python
    • MCP 에이전트 쿡북 with Python
  • LLMs
    • OpenAI API
      • 1️⃣ChatCompletion
      • 2️⃣DALL-E
      • 3️⃣Text to Speech
      • 4️⃣Video to Transcripts
      • 5️⃣Assistants API
      • 6️⃣Prompt Engineering
      • 7️⃣OpenAI New GPT-4o
    • LangChain
      • LangChain Basic
        • 1️⃣Basic Modules
        • 2️⃣Model I/O
        • 3️⃣Prompts
        • 4️⃣Chains
        • 5️⃣Agents
        • 6️⃣Tools
        • 7️⃣Memory
      • LangChain Intermediate
        • 1️⃣OpenAI LLM
        • 2️⃣Prompt Template
        • 3️⃣Retrieval
        • 4️⃣RAG ChatBot
        • 5️⃣RAG with Gemini
        • 6️⃣New Huggingface-LangChain
        • 7️⃣Huggingface Hub
        • 8️⃣SQL Agent & Chain
        • 9️⃣Expression Language(LCEL)
        • 🔟Llama3-8B with LangChain
      • LangChain Advanced
        • 1️⃣LLM Evaluation
        • 2️⃣RAG Evaluation with RAGAS
        • 3️⃣LangChain with RAGAS
        • 4️⃣RAG Paradigms
        • 5️⃣LangChain: Advance Techniques
        • 6️⃣LangChain with NeMo-Guardrails
        • 7️⃣LangChain vs. LlamaIndex
        • 8️⃣LangChain LCEL vs. LangGraph
    • LlamaIndex
      • LlamaIndex Basic
        • 1️⃣Introduction
        • 2️⃣Customization
        • 3️⃣Data Connectors
        • 4️⃣Documents & Nodes
        • 5️⃣Naive RAG
        • 6️⃣Advanced RAG
        • 7️⃣Llama3-8B with LlamaIndex
        • 8️⃣LlmaPack
      • LlamaIndex Intermediate
        • 1️⃣QueryEngine
        • 2️⃣Agent
        • 3️⃣Evaluation
        • 4️⃣Evaluation-Driven Development
        • 5️⃣Fine-tuning
        • 6️⃣Prompt Compression with LLMLingua
      • LlamaIndex Advanced
        • 1️⃣Agentic RAG: Router Engine
        • 2️⃣Agentic RAG: Tool Calling
        • 3️⃣Building Agent Reasoning Loop
        • 4️⃣Building Multi-document Agent
    • Hugging Face
      • Huggingface Basic
        • 1️⃣Datasets
        • 2️⃣Tokenizer
        • 3️⃣Sentence Embeddings
        • 4️⃣Transformers
        • 5️⃣Sentence Transformers
        • 6️⃣Evaluate
        • 7️⃣Diffusers
      • Huggingface Tasks
        • NLP
          • 1️⃣Sentiment Analysis
          • 2️⃣Zero-shot Classification
          • 3️⃣Aspect-Based Sentiment Analysis
          • 4️⃣Feature Extraction
          • 5️⃣Intent Classification
          • 6️⃣Topic Modeling: BERTopic
          • 7️⃣NER: Token Classification
          • 8️⃣Summarization
          • 9️⃣Translation
          • 🔟Text Generation
        • Audio & Tabular
          • 1️⃣Text-to-Speech: TTS
          • 2️⃣Speech Recognition: Whisper
          • 3️⃣Audio Classification
          • 4️⃣Tabular Qustaion & Answering
        • Vision & Multimodal
          • 1️⃣Image-to-Text
          • 2️⃣Text to Image
          • 3️⃣Image to Image
          • 4️⃣Text or Image-to-Video
          • 5️⃣Depth Estimation
          • 6️⃣Image Classification
          • 7️⃣Object Detection
          • 8️⃣Segmentatio
      • Huggingface Optimization
        • 1️⃣Accelerator
        • 2️⃣Bitsandbytes
        • 3️⃣Flash Attention
        • 4️⃣Quantization
        • 5️⃣Safetensors
        • 6️⃣Optimum-ONNX
        • 7️⃣Optimum-NVIDIA
        • 8️⃣Optimum-Intel
      • Huggingface Fine-tuning
        • 1️⃣Transformer Fine-tuning
        • 2️⃣PEFT Fine-tuning
        • 3️⃣PEFT: Fine-tuning with QLoRA
        • 4️⃣PEFT: Fine-tuning Phi-2 with QLoRA
        • 5️⃣Axoltl Fine-tuning with QLoRA
        • 6️⃣TRL: RLHF Alignment Fine-tuning
        • 7️⃣TRL: DPO Fine-tuning with Phi-3-4k-instruct
        • 8️⃣TRL: ORPO Fine-tuning with Llama3-8B
        • 9️⃣Convert GGUF gemma-2b with llama.cpp
        • 🔟Apple Silicon Fine-tuning Gemma-2B with MLX
        • 🔢LLM Mergekit
    • Agentic LLM
      • Agentic LLM
        • 1️⃣Basic Agentic LLM
        • 2️⃣Multi-agent with CrewAI
        • 3️⃣LangGraph: Multi-agent Basic
        • 4️⃣LangGraph: Agentic RAG with LangChain
        • 5️⃣LangGraph: Agentic RAG with Llama3-8B by Groq
      • Autonomous Agent
        • 1️⃣LLM Autonomous Agent?
        • 2️⃣AutoGPT: Worldcup Winner Search with LangChain
        • 3️⃣BabyAGI: Weather Report with LangChain
        • 4️⃣AutoGen: Writing Blog Post with LangChain
        • 5️⃣LangChain: Autonomous-agent Debates with Tools
        • 6️⃣CAMEL Role-playing Autonomous Cooperative Agents
        • 7️⃣LangChain: Two-player Harry Potter D&D based CAMEL
        • 8️⃣LangChain: Multi-agent Bid for K-Pop Debate
        • 9️⃣LangChain: Multi-agent Authoritarian Speaker Selection
        • 🔟LangChain: Multi-Agent Simulated Environment with PettingZoo
    • Multimodal
      • 1️⃣PaliGemma: Open Vision LLM
      • 2️⃣FLUX.1: Generative Image
    • Building LLM
      • 1️⃣DSPy
      • 2️⃣DSPy RAG
      • 3️⃣DSPy with LangChain
      • 4️⃣Mamba
      • 5️⃣Mamba RAG with LangChain
      • 7️⃣PostgreSQL VectorDB with pgvorco.rs
Powered by GitBook
On this page
  • Parameter Training
  • Parameter Efficient Fine-tuning(PEFT)
  • PEFT 방법론
  • Benefits of PEFT
  • Supervised Fine-tuning: PEFT Fine-tuning
  • Train Dataset
  • Base Model Load
  • Evaluate Base Model
  • Training
  • Merge Model
  • Run Inference
  • Push to HF Hub
  1. LLMs
  2. Hugging Face
  3. Huggingface Fine-tuning

PEFT Fine-tuning

PreviousTransformer Fine-tuningNextPEFT: Fine-tuning with QLoRA

Last updated 1 year ago

Parameter Training

Fine-tuning을 하기 위하여 Retrain 시 매개변수 Parameter 선택이 Fine-tuning의 계산 비용에 영향을 끼칩니다. 이에 따라 세가지 방법의 유연성이 고려됩니다:

  1. 모든 파라미터 재학습(Retrain all parameters)

  • 이 직관적인 방법은 모든 내부 모델 매개변수를 훈련하는 것을 포함합니다 (전체 매개변수를 Fine-tune).

  • 계산적으로 가장 많은 비용이 소요되며, 가치 있는 초기 지식이 손실되는 catastrophic forgetting 문제에 직면할 수 있습니다.

  1. Transfer Learning(전이 학습)

  • 전이 학습(TL)은 모델을 새로운 작업에 적응시킬 때 과거 학습에서 유용한 모델 표현/특성을 보존하는 것을 목표로 합니다.

  • 이는 신경망의 "head"를 새로운 레이어로 대체함으로써 LLM을 훈련하는 계산 비용을 줄이는 것을 포함합니다..

  1. Parameter Efficient Fine-tuning(PEFT)

  • PEFT는 매개변수를 효율적으로 Fine-tuning하는 방법으로 현재 Transformer 기반 모델에서 가장 많이 사용하는 방법론 입니다.

Parameter Efficient Fine-tuning(PEFT)

PEFT는 전통적인 세세한 조정 접근 방식과 관련된 저장 요구 사항과 계산 비용을 최소화하여 자원 제약이 있는 기기에 배포할 수 있는 것을 목표로 합니다.

PEFT 전략은 사전 훈련된 언어 모델(LLM)의 대부분의 매개변수를 고정시키면서 추가적인 모델 매개변수를 제한적으로 조정하는 것을 포함합니다.

  1. 비용을 최소화하여 적은 자원으로 학습 가능

  2. 부분적인 Fine-tuning으로 Catastropic forgetting 문제에 대해서 해결

  3. 기존 모델은 그대로 사용하기 때문에 도메인 밖에 있는 것에 대해서도 일반화 능력 향상 가능

Feature

Trainer

SFTTrainer

PEFT

목적

일반적인 학습용

Supervised fine-tuning of pre-trained models 사전학습 된 supervised fine-tuning

사전 학습된 모델의 특징을 추출하여 다른 작업에 전이

사용자 지정

Custom 높음

더 적은 옵션으로 더 단순해진 인터페이스

더 적은 옵션으로 더 단순해진 인터페이스

학습 워크플로우

복잡한 워크플로 처리

간소화된 워크플로

간소화된 워크플로

학습데이터 요구

더 큰 데이터셋

더 작은 데이터셋

데이터가 적어도 기존 모델의 지식을 활용 가능

메모리 사용

높음

PEFT 및 패킹 최적화를 통해 더 낮음

8, 4 bit 양자화로 낮음

학습 속도

느림

더 작은 데이터 세트와 더 짧은 시간으로 더 빠름

더 작은 데이터 세트와 더 짧은 시간으로 더 빠름

  • Supervised Fine Tuning(SFT): 기존 모델을 특정 작업에 맞게 세밀하게 조정하여 해당 작업에 특화된 성능을 얻는 방법.

  • Pre-training with Extracted Feature-based Transfer(PEFT): 사전 학습된 모델에서 특징을 추출하여 다른 작업에 전이하는 방법.

SFT는 특정 작업에 모델을 최적화하는 데 집중하며, PEFT는 사전 학습된 모델의 특징을 새로운 작업에 적용하는 데 중점을 둡니다. 각각의 방법은 데이터의 양과 목표 작업의 특성에 따라 적절히 선택해야 합니다.

이 표는 두 방법론의 개념과 특징, 장단점 등을 비교하여 나타낸 것입니다. 각각의 방법론은 특정 상황에서 더 효과적일 수 있으며, 사용하려는 데이터의 양과 품질, 목표 작업의 특성에 따라 적절히 선택해야 합니다.

PEFT 방법론

PEFT로 fine-tuning은 Huggingface PEFT 라이브러리에서 아래의 Adaters를 지원합니다. https://huggingface.co/docs/peft/index

  • Adapters

  • LoRA (Low-Rank Adaptation)

  • QLoRA (Quantized Low-Rank Adaptation)

  • Prefix tuning

  • Prompt tuning

  • P-tuning

  • IA3

Adapters

Transformer의 특정 레이어 뒤에 위치한 Adapter는 나머지 모델을 고정시키면서 매개변수를 업데이트할 수 있게 합니다. 이 직관적인 채택은 각 Transformer 레이어에 어댑터를 삽입하고 사전 훈련된 모델 위에 분류기 레이어를 추가하는 것을 포함합니다.

LoRA

LoRA (Low-Rank Adaptation)은 어댑터와 유사한 방식으로 Transformer 아키텍처에 작은 학습 가능한 서브모듈을 도입하여 Pre-trained model의 가중치를 고정하고 각 레이어에 학습 가능한 순위 분해 행렬을 통합합니다.

하향식 작업을 위한 학습 가능한 매개변수를 크게 줄여줌으로써 많은 경우 10,000배 이상 줄이고 GPU 메모리 요구 사항을 3배로 줄입니다. Fine-tuning 모델의 품질을 유지하거나 뛰어넘으며, 하드웨어 장벽을 낮추고 추가 추론 지연 없이 효율적인 작업 전환을 보장합니다.

QLoRA

QLoRA (Quantized Low-Rank Adaptation)은 BERT와 같은 대규모 사전 훈련된 언어 모델을 Adaper에서 Parameter Efficient Finetuning (PEFT) 접근 방식의 확장입니다.

Pre-trained 모델을 고정한 상태에서 새로운 작업별 레이어를 추가하는 대신 기존 상위 레이어를 적응시킵니다. 이러한 레이어는 가중치 행렬을 양자화(Quantized)하고 Low-Rank 근사치로 분해함으로써 더 효율적으로 만들어집니다.

QLoRA 접근 방식에서는 원래 모델의 가중치가 4 bit presicion 으로 양자화됩니다. 새로 추가된 Low-rank Adapter (LoRA) 가중치는 양자화되지 않으며 더 높은 정밀도로 유지되며 훈련 과정에서 세세하게 조정됩니다. 이 전략을 통해 세세한 조정 중에도 대규모 언어 모델의 성능을 유지하면서 효율적으로 메모리를 사용할 수 있습니다.

Prefix Tuning

Prefix-tuning(접두사 조정)은 글쓰기와 같은 작업을 위해 대형 언어 모델을 훈련시키는 간단한 방법입니다. 비용이 많이 들 수 있는 모든 모델 부분을 조정하는 대신, prefix-tuning은 prefix라고 불리는 작은 작업별 부분에 집중합니다. 이 prefix는 모델이 특정 작업을 위해 특정 방식으로 글을 쓰도록 안내하는 데 도움이 됩니다.

Prefix-tuning은 각 작업에 대해 접두사만 저장하면 되므로 모듈화되고 공간 효율적입니다. 이 방법은 모델의 성능을 유지하면서도 저장 공간과 계산 비용을 절약할 수 있습니다.

Prompt Tuning

Prompt tuning은 특정 작업에 대해 사전 훈련된 언어 모델을 다르게 조정하는 PEFT 방법입니다. 모든 매개변수가 조정되는 모델 조정과 달리, prompt tuning은 Back-propagation를 통해 유연한 프롬프트를 학습하는 과정을 포함합니다.

Prompt tuning은 Domain Distillation에 대한 강건성을 향상시키고 효율적인 프롬프트 앙상블링을 가능하게 합니다. 이는 각 작업마다 작은 작업별 프롬프트만 저장하면 되므로, 모든 작업에 대해 작업별 모델 복사본이 필요한 모델 조정과 달리 단일 고정 모델을 여러 작업에 재사용하기가 더 간단합니다.

P-tuning

P-tuning은 GPT와 같은 언어 모델을 더 좋게 만들어주는 방법으로, 자연어 이해 작업에서 기존 방법보다 뛰어난 결과를 보여줍니다. 이 방법은 학습 가능한 연속형 프롬프트 임베딩을 사용하여 LLM의 성능을 크게 개선할 수 있습니다.

P-tuning은 프롬프트 엔지니어링의 필요성을 줄이고, 현재 방법들과 비교해서 적은 데이터로도 높은 성능을 보입니다. 연속형 프롬프트 최적화는 다양한 도전에 대응하기 위해 하류 손실 함수와 프롬프트 인코더의 도움을 받습니다.

IA3

IA3 (Infused Adapter by Inhibiting and Amplifying Inner Activations)는 LoRA 기술을 개선하기 위해 설계된 파라미터 효율적인 세세한 조정 기술로, 학습 가능한 매개변수를 줄이고 모델 성능을 유지합니다.

LoRA와 유사하게, IA3는 대규모 사전 훈련된 모델을 특정 작업에 적응시키는 데 유용하며, 계산 요구를 최소화합니다. 또한 어댑터 가중치를 병합하는 능력이 있으며 추론 지연을 추가하지 않으므로 실시간 응용 프로그램 및 다양한 하류 작업에 대한 다재 다능성을 향상시킵니다.

Benefits of PEFT

  1. Decreased computational and storage costs: PEFT는 사전 훈련된 대부분의 매개변수를 고정하면서 소수의 추가 모델 매개변수만 세세하게 조정하여 계산 및 저장 비용을 크게 줄입니다.

  2. Overcoming catastrophic forgetting: LLM의 전체 세세한 조정 과정에서 치명적인 잊혀짐이 발생할 수 있습니다. 이 문제를 PEFT는 소수의 매개변수만 업데이트함으로써 극복할 수 있습니다.

  3. Better performance in low-data regimes: PEFT 접근 방식은 소량 데이터 환경에서 전체 세세한 조정보다 우수한 성능을 발휘하며, 도메인 외의 시나리오에 대해 더 잘 일반화됩니다.

  4. 이식성(Portability): PEFT 방법을 사용하면 전체 세세한 조정의 대형 체크포인트 대신 몇 메가바이트의 작은 체크포인트를 얻을 수 있습니다. 이로써 PEFT 접근 방식에서 훈련된 가중치를 전체 모델을 교체하지 않고 여러 작업에 쉽게 배포하고 사용할 수 있습니다.

  5. Performance comparable to full fine-tuning: PEFT는 소수의 학습 가능한 매개변수로 전체 세세한 조정과 유사한 성능을 달성할 수 있도록 합니다.


Supervised Fine-tuning: PEFT Fine-tuning

LLM fine-tuning 시에 기본적으로 Huggingface의 PEFT 라이브러리를 사용합니다. Huggingface는 PEFT를 기반으로 Fine-tuning을 쉽게 실행할 수 있는 TRL을 출시했습니다.

이 라이브러리는 양자화를 지원하며 BitsAndBytes와 함께 작동합니다.

%pip install bitsandbytes accelerate
%pip install peft trl

작은 언어 모델을 사용하여 잘 작동하는지 확인합니다.

  • TinyLlama/TinyLlama-1.1B-Chat-v1.0을 사용하겠습니다.

  • LoRA PEFT를 사용합니다.

  • 4비트 양자화를 사용합니다.

from huggingface_hub import login

login()
VBox(children=(HTML(value='<center> <img\nsrc=https://huggingface.co/front/assets/huggingface_logo-noborder.sv…

Train Dataset

from datasets import load_dataset

def prepare_data():
 
    #Data mapping 사용자 함수
    def create_conversation(sample):
        return {
          "messages": [
            {"role": "system", "content": "Generate a prompt for Midjourney based on the sentence below"},
            {"role": "user", "content": sample["input"]},
            {"role": "assistant", "content": sample["output"]}
          ]
        }
 
    dataset = load_dataset(
        "TheBossLevel123/midjourney-prompt-enhancement", 
        split="train")
    
    #기본적으로 map() 함수는 새 열을 데이터 집합에 병합합니다.
    # "message" 컬럼만 필요해서 입력 및 출력 열을 삭제합니다.
    dataset = dataset.map(
        create_conversation, 
        remove_columns=["input", "output"])
     
    # Save dataset
    dataset.to_json("dataset/train_dataset.jsonl", orient="records")
prepare_data()
Creating json from Arrow format:   0%|          | 0/1 [00:00<?, ?ba/s]

load_dataset으로 local에 저장된 json 포맷 파일을 로드하고 trainset으로 지정합니다.

train_dataset = load_dataset(
    "json", 
    data_files="dataset/train_dataset.jsonl", 
    split="train"
)
Generating train split: 0 examples [00:00, ? examples/s]

Base Model Load

from transformers import AutoTokenizer, BitsAndBytesConfig, AutoModelForCausalLM, TextStreamer


bnb_config = BitsAndBytesConfig(load_in_4bit=True) # 4bit quantization 설정
 
model = AutoModelForCausalLM.from_pretrained(
    "TinyLlama/TinyLlama-1.1B-Chat-v1.0",
    quantization_config=bnb_config)
 
# Do not do this:
# model.to(device)
 
tokenizer = AutoTokenizer.from_pretrained(
    "TinyLlama/TinyLlama-1.1B-Chat-v1.0",
)
 
#tokenizer settings with chatml settings.
# model, tokenizer = setup_chat_format(model, tokenizer)
`low_cpu_mem_usage` was None, now set to True since model is quantized.

Evaluate Base Model

학습을 실행하기 전에 기본 모델이 문제를 잘 해결할 수 있는지 확인해야 합니다. 텍스트 생성을 수행하는 간단한 유틸리티를 작성합니다.

def generate(prompt):
    # TextStreamer를 사용하면 문장이 streaming 처럼 생성 됩니다.
    streamer = TextStreamer(tokenizer)
    messages = [
        {"role": "system", "content": "Generate a prompt for Midjourney based on the sentence below."},
        {"role": "user", "content": prompt}
    ]
    device = "cuda"
    encoded = tokenizer.apply_chat_template(
        messages, 
        add_generation_prompt=True, 
        return_tensors="pt").to(device)

    generated_ids = model.generate(
        encoded, 
        streamer=streamer, 
        max_new_tokens=2000
    )
generate("A red mobile phone against a bule moon.")
<|system|>
Generate a prompt for Midjourney based on the sentence below.</s> 
<|user|>
A red mobile phone against a bule moon.</s> 
<|assistant|>
"Amidst the shimmering stars, a red mobile phone glows in the dark. A mysterious and magical sight, a symbol of hope and possibility, a symbol of the unknown, a symbol of the unknown unknowns."</s>

Training

먼저 Train 매개변수를 구성합니다. 10개의 에포크에 대해 훈련을 실행합니다.

각 배치에는 3개의 훈련 데이터 샘플이 있습니다. 매우 작은 언어 모델을 사용하기 때문에 최대 시퀀스 길이를 2000으로 설정했습니다.

peft 라이브러리를 통해 LoraConfig를 설정합니다.

from peft import LoraConfig
    
peft_config = LoraConfig(
        lora_alpha=128,
        lora_dropout=0.05,
        r=256,
        bias="none",
        target_modules="all-linear",
        task_type="CAUSAL_LM",
)

TrainerArgument로 SFTTrainer의 매개변수를 설정합니다.

from transformers import TrainingArguments

args = TrainingArguments(
    output_dir="trained-model", # 저장할 디렉토리 및 리포지토리 ID
    num_train_epochs=10, # 트레이닝 에포크 수
    per_device_train_batch_size=3, # 훈련 중 디바이스당 배치 크기
    gradient_accumulation_steps=2, # 역방향/업데이트 패스를 수행하기 전 단계 수
    gradient_checkpointing=True, # 메모리 절약을 위해 그라데이션 체크포인팅 사용
    optim="adamw_torch_fused", # 융합된 adamw 옵티마이저 사용
    logging_steps=10, # 10단계마다 로그 기록
    save_strategy="epoch", # 매 에포크마다 체크포인트 저장
    learning_rate=2e-4, # 학습률, QLoRA 논문 기준
    bf16=False, # bfloat16 정밀도 사용
    tf32=False, # tf32 정밀도 사용
    max_grad_norm=0.3, # QLoRA 논문기준 max_grad_norm
    warmup_ratio=0.03, # QLoRA 논문기준 warmup_ratio
    lr_scheduler_type="constant", # 'constant' 학습률 스케줄러 사용
)

SFTTrainer 함수로 학습을 설정합니다.

from trl import SFTTrainer

trainer = SFTTrainer(
    model=model,
    args=args,
    train_dataset=train_dataset,
    peft_config=peft_config,
    max_seq_length=2000,
    tokenizer=tokenizer,
    packing=True,
    dataset_kwargs={
        "add_special_tokens": False,  # special token으로 템플릿을 작성합니다.
        "append_concat_token": False, # 추가적인 seperate token을 추가할 필요가 없습니다.
    }
)
Generating train split: 0 examples [00:00, ? examples/s]
trainer.train()
> TrainOutput(global_step=10, training_loss=0.4292164325714111, metrics={'train_runtime': 460.3927, 'train_samples_per_second': 0.434, 'train_steps_per_second': 0.022, 'total_flos': 2967271833600000.0, 'train_loss': 0.4292164325714111, 'epoch': 10.0})
trainer.save_model("Finetuned_adapter")
adapter_model = model

모델 가중치는 매 에포크마다 ./trained-model 폴더에 저장됩니다.

Merge Model

Base Model과 Fine-tuning한 LoRA Adapter를 병합해줍니다. 순서는 아래와 같습니다.

  1. Base Model을 로드 합니다.

  2. PeftModel.from_pretrained() 함수를 사용하여 Fine-tuning의 LoRA Adapter를 불러옵니다.

  3. merge_and_unload()메서드로 병합 합니다.

  4. 병합한 model과 tokenizer를 특정 디렉토리에 저장합니다.

repo_id = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
use_ram_optimized_load=False

base_model = AutoModelForCausalLM.from_pretrained(
    repo_id,
    device_map='auto',
    trust_remote_code=True,
)

base_model.config.use_cache = False
base_model.get_memory_footprint()
4400196352
from peft import PeftModel 

# Load Lora adapter
model = PeftModel.from_pretrained(
    base_model,
    "Finetuned_adapter",
)
merged_model = model.merge_and_unload()

merged_model.save_pretrained("Merged_model")
tokenizer.save_pretrained("Merged_model")
('Merged_model/tokenizer_config.json',
 'Merged_model/special_tokens_map.json',
 'Merged_model/tokenizer.model',
 'Merged_model/added_tokens.json',
 'Merged_model/tokenizer.json')

Run Inference

  1. 메모리 관리를 위하여 model과 trainer를 삭제합니다.

  2. 저장된 model과 tokenizer checkpoint를 Load 합니다.

  3. 프롬프트로 Inference를 합니다.

import torch

del model
del trainer
torch.cuda.empty_cache()
from transformers import AutoConfig

config = AutoConfig.from_pretrained("./Merged_model")
model = AutoModelForCausalLM.from_pretrained("./Merged_model")
 
device = "cuda"
model.to(device)
 
tokenizer = AutoTokenizer.from_pretrained("./Merged_model")
generate("A blue table against a red wall.")
<|system|>
Generate a prompt for Midjourney based on the sentence below.</s> 
<|user|>
A blue table against a red wall.</s> 
<|assistant|>
blue table, red wall, minimalist --ar 16:9 --v 5.1</s>

Push to HF Hub

Fine-tuned 완료된 모델을 Hugging Face Repository에 Push 합니다.

merged_model.push_to_hub("your_hg_id/name_fine_tuned_model")
2️⃣
Supervised Fine-tuning Trainerhuggingface
Logo