대규모 언어 모델(LLM, Large Language Model)은 사전 학습된 범용 모델을 특정 목적에 맞게 Fine-tuning (미세 조정)하여 성능을 극대화할 수 있습니다. 특히 LoRA (Low-Rank Adaptation)는 전체 파라미터 대신 일부 핵심 파라미터만 학습해 메모리 효율과 속도를 동시에 확보할 수 있는 대표적인 경량화 기법입니다. 본 예시는 Meta (메타)의 LlamaForCausalLM뿐 아니라, Open-Source LLM 실험에 널리 사용되는 MistralForCausalLM, FalconForCausalLM 등 다양한 트랜스포머 기반 모델을 LoRA로 Fine-tuning하는 구조를 포함하여, 데이터셋 준비, Dataset 객체 생성, 학습 실행, Ollama (올라마)로의 변환과 로컬(Local) 실행 예시까지 전체 흐름을 안내합니다.

1. 사전 학습 모델과 토크나이저 불러오기

python
from transformers import (
    LlamaForCausalLM,
    MistralForCausalLM,
    FalconForCausalLM,
    QwenForCausalLM,
    LlamaTokenizer
)

model_name = "meta-llama/Llama-2-7b-chat-hf"
tokenizer = LlamaTokenizer.from_pretrained(model_name)
model = LlamaForCausalLM.from_pretrained(model_name, load_in_8bit=True)
  • Meta (메타): LlamaForCausalLM – 대표적인 오픈소스 트랜스포머 모델로 범용 NLP 연구에 적합.
  • Mistral AI (미스트랄 AI): MistralForCausalLM – MoE (Mixture of Experts) 구조로 고효율 대안.
  • TII (Technology Innovation Institute): FalconForCausalLM – 대규모 학습 데이터 기반 고성능 LLM.
  • Alibaba Cloud (알리바바 클라우드): QwenForCausalLM – 멀티모달 입력과 코드 생성에도 최적화.

이처럼 Hugging Face (허깅 페이스)의 transformers 라이브러리는 다양한 사전 학습 모델을 LoRA 실험에 바로 적용할 수 있도록 모듈화되어 있습니다.

2. 학습 데이터셋 준비 (JSON 예시)

./data/train_data.json 파일:

json
[
  {"instruction": "What is Newton's Second Law?", "input": "", "output": "Force equals mass times acceleration (F = ma)."},
  {"instruction": "Translate 'Hello' to French", "input": "", "output": "Bonjour"}
]

3. Dataset 객체로 데이터 불러오기

python
from datasets import load_dataset

dataset = load_dataset(
    'json',
    data_files='./data/train_data.json'
)

4. LoRA 구성으로 모델 경량화

python
from peft import get_peft_model, LoraConfig

lora_config = LoraConfig(
    r=8,
    lora_alpha=32,
    target_modules=["q_proj", "v_proj"],
    lora_dropout=0.05
)
model = get_peft_model(model, lora_config)

5. Trainer 설정 및 Fine-tuning 실행

python
from transformers import Trainer, TrainingArguments

training_args = TrainingArguments(
    output_dir="./results",
    per_device_train_batch_size=2,
    logging_steps=10,
    num_train_epochs=3,
)

trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=dataset['train']
)

trainer.train()

6. Fine-tuning된 모델 저장

python
model.save_pretrained("./fine_tuned_model")

7. Ollama 실행용 모델 변환

  1. ./fine_tuned_model/의 출력 파일을 gguf 등으로 변환.
  2. 변환된 모델을 Ollama 모델 디렉토리에 배치.
shell
# 예시: llama.cpp로 변환
python convert.py --model ./fine_tuned_model --output ./fine_tuned_model.gguf

8. Ollama 로컬 실행 예시

shell
ollama create my-finetune -f ./fine_tuned_model.gguf
ollama run my-finetune

이와 같은 흐름을 통해 Llama, Mistral, Falcon, Qwen 등 다양한 Open-Source LLM을 LoRA로 Fine-tuning하고, Ollama 같은 로컬 실행 환경에서 안전하고 효율적으로 배포할 수 있습니다.