Views
No views yet
Qwen/Qwen2-VL-7B-Instruct 모델에 LoRA(QLoRA)를 적용해 미세조정한 어댑터 가중치입니다.Qwen/Qwen2-VL-7B-Instructtransformers와 peft 라이브러리를 사용하여 베이스 모델에 본 어댑터를 로드하는 방법입니다.1from transformers import AutoProcessor, AutoModelForCausalLM
2from peft import PeftModel
3import torch
4
5base_id = "Qwen/Qwen2-VL-7B-Instruct"
6adapter_id = "dohoon0508/Dohoon_Qwen2-VL-7B-Instruct_ForAju"
7
8# 프로세서 및 4-bit 양자화된 베이스 모델 로드
9processor = AutoProcessor.from_pretrained(base_id, trust_remote_code=True)
10base_model = AutoModelForCausalLM.from_pretrained(
11 base_id,
12 device_map="auto",
13 trust_remote_code=True,
14 torch_dtype=torch.bfloat16, # or torch.float16
15 load_in_4bit=True
16)
17
18# 어댑터(LoRA) 가중치 적용
19model = PeftModel.from_pretrained(base_model, adapter_id)
20model.eval()
21
22# 추론 예시 (VQA)
23# from PIL import Image
24# import requests
25
26# image_url = "[https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/bee.JPG](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/bee.JPG)"
27# image = Image.open(requests.get(image_url, stream=True).raw).convert("RGB")
28# question = "Question: What is the main subject in this image?"
29
30# messages = [
31# {"role": "system", "content": [{"type": "text", "text": "You are a multimodal assistant..."}]}, # 실제 사용하는 시스템 프롬프트 적용
32# {"role": "user", "content": [{"type": "image"}, {"type": "text", "text": question}]}
33# ]
34
35# prompt = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
36# enc = processor(text=prompt, images=[image], return_tensors="pt")
37
38# out = model.generate(**{k: v.to(model.device) for k, v in enc.items()}, max_new_tokens=128)
39# generated_text = processor.batch_decode(out, skip_special_tokens=True)[0]
40# print(generated_text)
41📁 파일 구성
42adapter_model.safetensors: LoRA 어댑터 가중치 파일
43
44adapter_config.json: 어댑터 설정 파일
45
46README.md: 모델 카드
47
48tokenizer.json, tokenizer.model, tokenizer_config.json, processor_config.json 등 기타 설정 파일
49
50🔬 학습 개요
51튜닝 방식: QLoRA (4-bit NormalFloat) + LoRA
52
53LoRA 대상 모듈: q_proj, k_proj, v_proj, o_proj, gate_proj, up_proj, down_proj
54
55LoRA 하이퍼파라미터:
56
57r = 32
58
59lora_alpha = 16
60
61lora_dropout = 0.05
62
63비전 타워: 완전 동결 (Frozen)
64
65학습 하이퍼파라미터:
66
67per_device_train_batch_size = 1
68
69gradient_accumulation_steps = 16
70
71learning_rate = 1e-4 (Cosine 스케줄러)
72
73warmup_ratio = 0.03
74
75정밀도: bf16 (사용 가능 시) / fp16
76
77데이터: 대회 제공 멀티태스크 데이터 (.parquet)
78
79프롬프트: 고정된 단일 시스템 프롬프트 + (이미지/텍스트 + 질문) 형태로 구성하여 태스크 분기 없음
80
81라벨링: 손실 계산 시 프롬프트에 해당하는 토큰은 -100으로 마스킹하여 정답 토큰에만 loss 반영
82
83🧠 추론 메모
84디코딩:
85
86Greedy Search (do_sample=False, num_beams=1)
87
88no_repeat_ngram_size = 4
89
90repetition_penalty = 1.05
91
92동적 생성 제어:
93
94태스크 종류(Captioning, Summarization 등)에 따라 최대 생성 토큰 수를 동적으로 조절
95
96문장 부호(., !, ?) 개수를 감지하여 지정된 문장 수에 도달하면 생성을 조기 중단하는 StopOnSentenceCount 기준 적용
97
98후처리:
99
100금칙어("I'm sorry", "As an AI" 등) 제거
101
102수학 문제의 경우, 정답을 #### {answer} 형식으로 추출/강제
103
104VQA 응답은 간결성을 위해 첫 문장만 사용
105
106✅ 권장 사용 범위
107이미지 캡셔닝, VQA, 텍스트 요약 등 다양한 멀티모달 지시(Instruction)를 단일 모델로 처리하는 연구/실험
108
109별도의 라우팅 로직 없이 프롬프트만으로 태스크를 구분하는 모델의 능력 분석
110
111LoRA/QLoRA를 활용한 대규모 언어 모델(LLM)의 효율적 파인튜닝 사례 연구
112
113⚠️ 제한 및 주의사항
114생성 모델의 특성상 사실과 다른 정보(Hallucination)나 오해의 소지가 있는 내용을 생성할 수 있습니다.
115
116민감하거나 안전/윤리적 요구사항이 중요한 도메인에 적용할 경우, 반드시 추가적인 필터링 또는 가드레일 장치가 필요합니다.
117
118베이스 모델(Qwen/Qwen2-VL-7B-Instruct) 및 학습 데이터의 원본 라이선스와 약관을 준수해야 합니다.
119
120🔗 참고
121Base model: Qwen/Qwen2-VL-7B-Instruct
122
123프로젝트 저장소: https://github.com/dohoon0508/ajukaggle