Vast.ai + Unsloth + Gemma 4로 저비용 LLM 파인튜닝하기

생성형 AI를 실제 서비스에 적용하려고 하면 곧바로 한 가지 문제가 생긴다. 바로 GPU 비용이다.
Gemma 4와 같은 오픈 웨이트 LLM을 직접 실행하는 것은 가능하지만, 파인튜닝까지 하려면 상당한 GPU 메모리가 필요하다. 그렇다고 A100이나 H100 서버를 직접 구축하는 것도 개인 개발자나 소규모 팀에게는 부담이 크다.
이때 꽤 현실적인 조합이 있다.
Vast.ai + Unsloth + Gemma 4다.
각각의 역할을 단순하게 표현하면 다음과 같다.
- Gemma 4: 학습할 기반 LLM
- Unsloth: LLM 파인튜닝에 필요한 VRAM과 학습 시간을 줄여주는 프레임워크
- Vast.ai: 필요한 시간만 GPU를 빌려 사용하는 GPU 마켓플레이스
특히 2026년 4월 공개된 Gemma 4는 텍스트뿐 아니라 이미지 입력을 지원하며, 일부 모델은 오디오까지 처리한다. 최대 256K 컨텍스트, 140개 이상의 언어 지원, reasoning과 function calling 등을 제공하는 것이 특징이다. Google은 E2B, E4B, 26B A4B, 31B를 먼저 공개한 뒤 2026년 6월 12B 모델을 추가했다.
이번 글에서는 이 세 가지를 조합해 개인용 또는 서비스용 Gemma 4 모델을 파인튜닝하는 전체 과정을 살펴본다.
1. 왜 Vast.ai + Unsloth + Gemma 4인가?
먼저 세 기술의 역할을 정확히 이해할 필요가 있다.
Gemma 4
Gemma 4는 Google DeepMind가 개발한 오픈 웨이트 모델이다.
2026년 공개된 Gemma 4 계열에는 여러 크기의 모델이 존재한다. 대표적으로 다음과 같다.
| 모델 | 특징 |
|---|---|
| Gemma 4 E2B | 모바일·엣지 환경을 고려한 소형 모델 |
| Gemma 4 E4B | 비교적 가볍게 사용할 수 있는 모델 |
| Gemma 4 12B | 멀티모달 작업을 고려한 중형 모델 |
| Gemma 4 26B A4B | 26B MoE이지만 약 4B 파라미터를 활성화하는 구조 |
| Gemma 4 31B | 고성능 Dense 모델 |
특히 Gemma 4는 이전 세대보다 reasoning, coding, agentic workflow에 초점을 맞추고 있으며 native system prompt도 지원한다.
따라서 단순한 챗봇뿐 아니라 다음과 같은 모델을 만드는 데 사용할 수 있다.
- 한국어 고객 상담 모델
- 특정 분야 전문 QA 모델
- 사내 문서 답변 모델
- 코딩 어시스턴트
- 특정 문체를 사용하는 콘텐츠 생성 모델
- 이미지까지 이해하는 멀티모달 모델
- Tool Calling 기반 AI Agent
2. Unsloth란?
일반적인 Hugging Face Transformers 환경에서도 Gemma 4를 파인튜닝할 수 있다.
문제는 메모리와 속도다.
LLM 전체 파라미터를 학습하는 Full Fine-tuning은 GPU 메모리를 상당히 많이 사용한다. 그래서 개인 개발자가 사용하는 환경에서는 보통 LoRA 또는 QLoRA를 사용한다.
Unsloth는 이런 Parameter-Efficient Fine-Tuning 과정을 최적화해주는 프레임워크다.
Vast.ai의 공식 Unsloth Studio 가이드에서는 Unsloth 기반 학습을 일반적인 방식 대비 최대 약 2배 빠른 학습 및 최대 70% VRAM 절감을 목표로 하는 방식으로 설명하고 있다. 실제 절감률은 모델, GPU, context length, batch size 등에 따라 달라진다.
즉,
일반적인 Fine-tuning
Gemma 4
↓
Transformers
↓
높은 VRAM
↓
높은 GPU 비용
에서
Gemma 4
↓
Unsloth
↓
QLoRA
↓
낮은 VRAM 사용
↓
GPU 비용 감소
구조를 만들 수 있다.
3. Vast.ai는 무엇인가?
Vast.ai는 GPU를 제공하는 클라우드 마켓플레이스다.
일반적인 클라우드 서비스와 조금 다른 점은 GPU 공급자가 다양한 서버를 등록하고 사용자가 가격, GPU 종류, VRAM, 신뢰도 등을 비교해 인스턴스를 선택한다는 것이다.
따라서
RTX 3090
RTX 4090
RTX 5090
A6000
A100
H100
H200
등의 GPU를 필요할 때만 임대해 사용할 수 있다.
Vast.ai는 현재 공식 Unsloth Studio 템플릿도 제공하고 있다. 해당 템플릿을 선택하면 별도의 복잡한 CUDA 환경 구성 없이 브라우저에서 Unsloth Studio를 실행할 수 있다.
4. 세 가지를 조합하면 어떻게 되는가?
전체 구조는 상당히 단순하다.
Vast.ai
↓
GPU 서버 임대
↓
Unsloth
↓
Gemma 4 로드
↓
Dataset
↓
QLoRA Fine-tuning
↓
Custom Gemma 4
↓
LoRA / GGUF / Hugging Face
↓
Ollama / LM Studio / vLLM / API Server
이 구조의 장점은 GPU를 보유할 필요가 없다는 것이다.
학습할 때만 Vast.ai 서버를 사용하고 학습이 끝난 후 모델을 Hugging Face나 로컬 PC로 옮긴 다음 인스턴스를 삭제하면 된다.
5. 가장 쉬운 방법: Vast.ai + Unsloth Studio
처음 시도한다면 Python 코드를 직접 작성하는 것보다 Unsloth Studio를 사용하는 것이 편하다.
Vast.ai는 현재 공식적으로 Unsloth Studio용 템플릿을 제공한다.
Step 1. Vast.ai 가입
Vast.ai 계정을 만든 후 GPU 사용을 위한 크레딧을 충전한다.
그다음 Instance 검색 화면으로 이동한다.
Step 2. Unsloth Studio Template 선택
Vast.ai의 Unsloth Studio 템플릿을 선택한다.
공식 가이드에서는 GPU 선택 시 다음과 같은 요소를 확인할 것을 권장한다.
- GPU VRAM
- 시간당 가격
- 서버 Reliability
- Disk 용량
특히 Reliability는 가능하면 95% 이상의 인스턴스를 선택하는 것이 좋다.
6. GPU는 무엇을 선택해야 할까?
처음부터 Gemma 4 31B를 선택할 필요는 없다.
개인적으로 테스트하는 단계라면 작은 모델부터 시작하는 것이 훨씬 효율적이다.
예를 들어 QLoRA 기반 학습에서는 작은 모델의 VRAM 요구량이 크게 감소한다. 다만 Unsloth가 공개한 Gemma 4 메모리 표는 GGUF 추론 기준이므로 파인튜닝 최소 VRAM으로 읽으면 안 된다. 학습 메모리는 context length, batch size, gradient checkpointing, LoRA 대상 모듈과 quantization 방식에 따라 크게 달라진다.
따라서 Gemma 4를 처음 실험한다면 실무적으로 다음과 같이 접근할 수 있다.
입문
Gemma 4 E2B / E4B
+
RTX 3090 / 4090급 24GB
↓
중급
Gemma 4 12B
+
24~48GB급 GPU
↓
고성능 실험
Gemma 4 26B A4B / 31B
+
48GB GPU 또는 Multi-GPU
이는 고정된 최소 요구사항이라기보다 안정적인 실험을 위한 보수적인 출발점으로 보는 것이 좋다. 실제 VRAM은 sequence length, batch size, 학습 대상 layer, quantization 방식에 크게 좌우된다. 처음에는 Vast.ai 가이드처럼 24GB급 GPU를 기준으로 작은 모델과 짧은 context에서 시작하고, 실행 직후 GPU 메모리를 확인해 값을 조정하는 편이 안전하다.
7. Unsloth Studio 실행
Vast.ai에서 Instance를 생성하고 Running 상태가 되면 Open을 선택한다.
Applications 화면에서
Unsloth Studio
를 실행하면 된다.
현재 Vast.ai 템플릿에서는 브라우저 기반 UI를 통해 모델 실행과 파인튜닝 작업을 수행할 수 있다.
즉 Jupyter Notebook을 직접 작성하지 않아도 된다.
8. Gemma 4 다운로드
Gemma 계열 모델은 Hugging Face에서 가져올 수 있다.
Unsloth는 현재 Gemma 4를 직접 지원하며 공식 예제에는 다음 모델들이 포함되어 있다.
unsloth/gemma-4-E2B-it
unsloth/gemma-4-E4B-it
unsloth/gemma-4-12b-it
unsloth/gemma-4-31B-it
unsloth/gemma-4-26B-A4B-it
그리고 Base Model도 제공한다.
unsloth/gemma-4-E2B
unsloth/gemma-4-E4B
unsloth/gemma-4-12b
unsloth/gemma-4-31B
unsloth/gemma-4-26B-A4B
보통 챗봇이나 서비스용 모델을 만들고 싶다면 -it, 즉 instruction-tuned 모델에서 시작하는 것이 편하다.
예를 들어
unsloth/gemma-4-E4B-it
를 사용할 수 있다.
9. GGUF와 Safetensors를 혼동하면 안 된다
여기서 상당히 중요한 부분이 있다.
GGUF는 주로 추론용이다.
예를 들어
Ollama
LM Studio
llama.cpp
에서 모델을 실행할 때 사용하기 좋다.
하지만 Fine-tuning을 할 계획이라면 일반적으로 학습 가능한 모델 체크포인트를 가져와야 한다.
Vast.ai의 Unsloth Studio 문서 역시 GGUF 모델은 inference 용도로 사용하고 파인튜닝에는 safetensors 기반 모델을 사용해야 한다고 설명한다.
10. Dataset 준비하기
파인튜닝에서 실제로 가장 중요한 것은 GPU도 아니고 모델도 아니다.
Dataset이다.
예를 들어 다음과 같은 고객 상담 모델을 만든다고 가정하자.
{
"messages": [
{
"role": "user",
"content": "회원가입은 어떻게 하나요?"
},
{
"role": "assistant",
"content": "홈페이지 오른쪽 상단의 회원가입 버튼을 선택한 후 이메일 인증을 진행해 주세요."
}
]
}
이런 데이터가 수백~수천 개 존재하면 특정 서비스에 맞는 답변 패턴을 모델에 학습시킬 수 있다.
Unsloth Studio는 현재 다음과 같은 파일 포맷을 지원한다.
JSON
JSONL
CSV
Parquet
PDF
DOCX
TXT
그리고 ChatML, Alpaca, ShareGPT 계열의 대화 포맷을 인식한다.
11. QLoRA로 학습하기
개인 개발자라면 대부분 QLoRA부터 시작하는 것이 합리적이다.
Unsloth Studio에서는 대략 다음 세 가지 방식을 선택할 수 있다.
| 방식 | VRAM | 특징 |
|---|---|---|
| QLoRA 4bit | 낮음 | 일반적으로 첫 번째 선택 |
| LoRA 16bit | 중간 | VRAM 여유가 있을 때 |
| Full Fine-tuning | 매우 높음 | 제한적인 상황에서 사용 |
처음에는
QLoRA 4bit
를 선택하면 된다.
12. 기본 Training Parameter
처음 학습한다면 지나치게 많은 값을 변경하지 않는 것이 좋다.
Vast.ai의 Unsloth Studio 가이드가 제시하는 시작값은 다음과 같다.
Epochs: 1~3
Learning Rate: 2e-4
Batch Size: 2~4
Context Length: 2048
LoRA Rank: 16
다만 이것은 어디까지나 시작점이다.
예를 들어 긴 문서 학습에서는
Context Length
2048
↓
4096
↓
8192
로 증가시킬 수 있다.
하지만 context length가 증가하면 GPU 메모리 사용량도 증가한다.
따라서 Out Of Memory가 발생한다면 우선 다음 순서로 줄이는 것이 현실적이다.
Batch Size 감소
↓
Context Length 감소
↓
LoRA Rank 감소
↓
더 큰 VRAM GPU 사용
13. Python으로 직접 Gemma 4 Fine-tuning하기
UI가 아니라 Python으로 제어하고 싶다면 Unsloth의 FastModel을 사용할 수 있다. Gemma 4 통합은 빠르게 업데이트되고 있으므로 실제 학습 전에는 Unsloth의 최신 Gemma 4 가이드와 notebook의 설치 셀을 우선 확인하자.
Unsloth의 공식 Gemma 4 notebook은 현재 FastModel을 사용해 Gemma 4를 로딩한다.
개념적으로는 다음과 같은 형태다.
from unsloth import FastModel
model, tokenizer = FastModel.from_pretrained(
model_name="unsloth/gemma-4-E4B-it",
max_seq_length=8192,
load_in_4bit=True,
full_finetuning=False,
)
여기서 가장 중요한 부분은
load_in_4bit=True
다.
4bit quantization을 이용하여 메모리 사용량을 줄인다. Unsloth 공식 Gemma 4 예제 역시 동일한 방식으로 모델을 로드한다.
14. LoRA Adapter 추가하기
다음 단계는 학습할 부분을 선택하는 것이다.
Unsloth의 Gemma 4 공식 예제에서는 FastModel.get_peft_model()을 이용한다.
예를 들어 텍스트 중심 모델이라면 다음처럼 구성할 수 있다. 이미지·오디오까지 학습하는 멀티모달 파인튜닝은 전처리와 학습 대상이 달라지므로 Unsloth의 최신 멀티모달 예제를 별도로 따라야 한다.
model = FastModel.get_peft_model(
model,
finetune_vision_layers=False,
finetune_language_layers=True,
finetune_attention_modules=True,
finetune_mlp_modules=True,
r=8,
lora_alpha=8,
lora_dropout=0,
bias="none",
)
여기서
r
은 LoRA rank다.
높이면 모델이 학습할 수 있는 표현력이 증가할 수 있지만 메모리 사용량과 overfitting 가능성도 함께 증가한다.
15. Gemma 4 Chat Template 적용
LLM 파인튜닝에서 자주 발생하는 실수가 있다.
단순히 질문과 답변 문자열을 붙여 학습하는 것이다.
Instruction model은 모델마다 대화 포맷이 다르기 때문에 해당 모델의 chat template을 사용하는 것이 중요하다.
Unsloth의 Gemma 4 예제에서는 Gemma 4용 chat template을 사용한다.
예를 들면 다음과 같다.
from unsloth.chat_templates import get_chat_template
tokenizer = get_chat_template(
tokenizer,
chat_template="gemma-4-thinking",
)
특히 reasoning 모델이나 multi-turn conversation 모델을 학습할 경우 chat template 오류는 학습 품질에 직접적인 영향을 줄 수 있다.
16. Trainer 구성
Unsloth는 Hugging Face TRL의 SFTTrainer와 함께 사용할 수 있다.
Gemma 4 공식 Unsloth 예제 역시 SFTTrainer와 SFTConfig를 사용한다.
간단한 형태로 작성하면 다음과 같다.
from trl import SFTTrainer, SFTConfig
trainer = SFTTrainer(
model=model,
tokenizer=tokenizer,
train_dataset=dataset,
args=SFTConfig(
dataset_text_field="text",
per_device_train_batch_size=1,
gradient_accumulation_steps=4,
learning_rate=2e-4,
max_steps=60,
logging_steps=1,
optim="adamw_8bit",
weight_decay=0.001,
lr_scheduler_type="linear",
report_to="none",
),
)
그리고
trainer.train()
을 실행하면 학습이 시작된다.
공식 notebook은 빠른 테스트를 위해 max_steps=60을 사용하고 있으며 전체 학습에서는 epoch 기반 설정으로 변경할 수 있다고 설명한다.
17. Fine-tuning 모델 저장하기
학습이 끝났다면 결과를 저장해야 한다.
LoRA Adapter만 저장하려면 다음처럼 할 수 있다.
model.save_pretrained("gemma_4_lora")
tokenizer.save_pretrained("gemma_4_lora")
이 경우 저장되는 것은 전체 Gemma 4 모델이 아니라 LoRA Adapter다.
따라서 용량이 훨씬 작다.
구조는 다음과 같다.
Gemma 4 Base Model
+
LoRA Adapter
=
Fine-tuned Gemma 4
18. Hugging Face에 업로드하기
클라우드에서 학습한 모델을 보관하는 가장 편한 방법 중 하나는 Hugging Face Hub이다.
예를 들어
model.push_to_hub(
"username/gemma4-custom",
token="HF_TOKEN"
)
tokenizer.push_to_hub(
"username/gemma4-custom",
token="HF_TOKEN"
)
형태로 저장할 수 있다. Unsloth의 Gemma 4 notebook 역시 local save_pretrained와 Hugging Face Hub 업로드 방식을 모두 예시로 제공한다.
토큰을 notebook에 직접 적어 공유하거나 이미지에 포함하지 말고 환경 변수나 Hugging Face의 로그인 기능으로 관리하자. 업로드가 끝난 뒤에는 저장소가 공개인지 비공개인지도 반드시 확인해야 한다.
이렇게 하면 Vast.ai 인스턴스를 삭제해도 모델을 다시 사용할 수 있다.
19. GGUF로 변환해서 로컬에서 실행하기
학습은 클라우드에서 하고 실제 실행은 로컬 PC에서 하는 구조도 상당히 유용하다.
예를 들어
Vast.ai
RTX 4090 / A6000
↓
Gemma 4 Fine-tuning
↓
GGUF Export
↓
Mac / Windows
↓
Ollama / LM Studio / llama.cpp
구조다.
Vast.ai의 Unsloth Studio는 현재 학습 결과를 다음과 같은 형태로 export할 수 있다.
Merged Model
LoRA Only
GGUF / llama.cpp
Vast.ai 문서에서는 로컬 실행 용도에서 Q4_K_M GGUF를 품질과 파일 크기의 균형을 위한 선택지로 제시한다.
20. 이 조합의 가장 큰 효과
그렇다면 Vast.ai + Unsloth + Gemma 4 조합의 가장 큰 장점은 무엇일까?
첫 번째: GPU를 구매하지 않아도 된다
LLM 개발을 위해 수백만 원짜리 GPU를 구매할 필요가 없다.
필요한 시간만 GPU를 임대한다.
개발
↓
GPU Rent
↓
Fine-tuning
↓
Model 저장
↓
Instance 삭제
형태로 사용할 수 있다.
두 번째: QLoRA로 VRAM 요구량을 줄일 수 있다
Full Fine-tuning 대신 QLoRA를 사용하면 전체 파라미터를 업데이트하지 않고 상대적으로 작은 adapter를 학습한다.
따라서 consumer GPU에서도 상당수 모델의 fine-tuning 실험이 가능해진다.
Vast.ai의 공식 Unsloth 가이드도 QLoRA를 VRAM 사용량이 가장 낮은 기본 선택지로 안내한다.
세 번째: Fine-tuning 실험 비용을 낮출 수 있다
LLM fine-tuning은 한 번으로 끝나는 경우가 거의 없다.
보통
Dataset v1
↓
Training
↓
Evaluation
↓
Dataset 수정
↓
Training
↓
Evaluation
과정을 반복한다.
따라서 GPU를 소유하는 것보다 필요할 때마다 다양한 GPU 인스턴스를 선택할 수 있는 방식이 연구나 PoC 단계에서는 유리할 수 있다.
21. Fine-tuning을 하면 무엇이 좋아질까?
여기에서 중요한 오해가 있다.
Fine-tuning을 한다고 모델이 무조건 더 똑똑해지는 것은 아니다.
예를 들어 Gemma 4를 회사 데이터로 fine-tuning한다고 해서 모델이 갑자기 모든 회사 문서를 정확하게 기억하는 것은 아니다.
Fine-tuning은 특히 다음 영역에 효과적이다.
답변 형식 학습
예:
사용자:
환불 가능한가요?
기본 Gemma:
환불 정책에 따라 다를 수 있습니다...
Fine-tuned Gemma:
결제일 기준 7일 이내이며 서비스 이용 이력이 없는 경우 마이페이지 → 결제관리 → 환불신청 메뉴에서 신청할 수 있습니다.
특정 문체 학습
일반적인 답변
↓
회사 공식 상담 문체
또는
일반적인 글
↓
블로그 스타일
출력 구조 학습
예를 들어 항상 JSON으로 출력하도록 학습할 수도 있다.
{
"category": "refund",
"priority": "normal",
"answer": "..."
}
API 시스템을 만들 때 특히 유용하다.
22. 하지만 지식 주입 목적이라면 RAG도 고려해야 한다
Fine-tuning과 RAG를 혼동해서는 안 된다.
예를 들어 매일 변경되는 상품 가격이나 사내 규정을 모델에게 알려줘야 한다면 Fine-tuning만으로 해결하는 것은 적절하지 않을 수 있다.
이런 경우에는
Gemma 4
+
Vector DB
+
RAG
구조가 더 적합하다.
반대로
답변 스타일
응답 포맷
업무 패턴
분류 방식
특정 행동
을 학습시키고 싶다면 Fine-tuning의 가치가 크다.
실제로 서비스에서는
Gemma 4
+
Fine-tuning
+
RAG
를 동시에 사용하는 경우가 가장 실용적인 구조가 될 수 있다.
23. 좋은 Dataset이 좋은 모델을 만든다
Fine-tuning에서 가장 흔한 실수는 Dataset 양만 늘리는 것이다.
예를 들어
10,000개 저품질 데이터
보다
1,000개 고품질 데이터
가 더 유용할 수도 있다.
특히 다음을 확인해야 한다.
중복 데이터 제거
잘못된 답변 제거
문체 통일
질문 형식 다양화
지나치게 긴 답변 제거
잘못된 hallucination 제거
그리고 가능한 경우 train dataset과 별도로 evaluation dataset을 만들어야 한다.
24. Base Model과 Fine-tuned Model을 반드시 비교하자
학습 loss가 감소했다고 모델이 좋아졌다고 판단하면 안 된다.
실제 질문을 넣어 비교해야 한다.
Vast.ai의 Unsloth Studio에는 두 모델에 동일한 prompt를 전달해 비교하는 Model Arena 기능도 제공된다.
예를 들어
Gemma 4 Original
VS
Gemma 4 Fine-tuned
형태로 비교한다.
평가 기준도 미리 만들어두는 것이 좋다.
정확성
형식 준수
Hallucination
답변 길이
전문 용어 사용
한국어 자연스러움
25. Vast.ai 사용 시 가장 중요한 주의점
Vast.ai를 사용할 때 한 가지는 반드시 기억해야 한다.
작업이 끝나면 Instance를 Destroy해야 한다.
Vast.ai 공식 문서에 따르면 Stop 상태에서는 compute 비용은 중단할 수 있지만 storage 비용은 계속 발생할 수 있다. 모든 비용을 중단하려면 Instance를 Destroy해야 한다. 단, Destroy하면 인스턴스 내부 데이터도 삭제되므로 모델을 먼저 export해야 한다.
또한 Vast.ai는 여러 공급자의 장비를 연결하는 마켓플레이스다. 고객 정보나 사내 문서처럼 민감한 데이터를 올릴 때는 공급자 유형과 보안 요구사항을 먼저 검토하고, 가능하면 비식별화·암호화된 데이터와 검증된 데이터센터 인스턴스를 사용하자.
따라서 다음 순서를 습관화하는 것이 좋다.
Training 완료
↓
Inference Test
↓
LoRA 저장
↓
Hugging Face Upload
↓
필요하면 GGUF Export
↓
파일 확인
↓
Vast.ai Instance Destroy
26. 추천하는 첫 번째 실험
처음부터 거대한 Dataset이나 31B 모델을 사용할 필요는 없다.
다음 정도로 시작하는 것을 추천한다.
GPU
RTX 4090 24GB급
Model
Gemma 4 E4B IT
Fine-tuning
QLoRA 4bit
Dataset
500~2,000 samples
Epoch
1
Context
2048
LoRA Rank
8~16
목표도 단순하게 잡는다.
예를 들어
“한국어 IT 기술 블로그 작성 모델”
을 만든다고 하자.
Dataset은 다음처럼 구성할 수 있다.
{
"messages": [
{
"role": "user",
"content": "React Server Components를 설명하는 블로그 글을 작성해 주세요."
},
{
"role": "assistant",
"content": "React Server Components란..."
}
]
}
이런 고품질 데이터를 일정량 학습시키면 Gemma 4가 원하는 콘텐츠 구조와 문체를 더 안정적으로 따르도록 조정할 수 있다.
27. 조금 더 발전시키면
첫 번째 Fine-tuning이 성공하면 다음 단계로 확장할 수 있다.
Stage 1
Gemma 4 E4B
+
QLoRA
+
Text Dataset
다음에는
Stage 2
Gemma 4 12B
+
더 많은 Dataset
+
Evaluation Dataset
그리고
Stage 3
Fine-tuned Gemma 4
+
RAG
+
Vector DB
+
Function Calling
마지막으로
Stage 4
Frontend
+
FastAPI / Node.js
+
vLLM
+
Fine-tuned Gemma 4
구조로 실제 AI 서비스를 만들 수 있다.
28. 전체 구조 정리
결국 세 기술은 다음과 같은 관계다.
┌───────────────┐
│ Vast.ai │
│ GPU Cloud │
└───────┬───────┘
│
▼
┌───────────────┐
│ Unsloth │
│ Fine-tuning │
└───────┬───────┘
│
▼
┌───────────────┐
│ Gemma 4 │
│ Base Model │
└───────┬───────┘
│
▼
Dataset
│
▼
QLoRA
│
▼
Custom Gemma 4
│ │
▼ ▼
GGUF LoRA Adapter
│ │
▼ ▼
Ollama/LM Hugging Face
마무리
과거에는 LLM을 직접 fine-tuning하려면 고가의 GPU 서버와 상당한 머신러닝 지식이 필요했다.
하지만 현재는 상황이 많이 달라졌다.
Vast.ai에서 필요한 시간만 GPU를 임대하고, Unsloth를 이용해 QLoRA 방식으로 VRAM 사용량을 줄이며, Gemma 4와 같은 강력한 오픈 웨이트 모델을 자신의 데이터에 맞게 조정할 수 있다. Vast.ai는 Unsloth Studio용 공식 템플릿까지 제공하고 있어 코드 없이 fine-tuning을 시작하는 것도 가능하다.
특히 Gemma 4는 2026년 공개된 모델답게 reasoning, coding, multimodal input, function calling, 긴 context 등을 지원하고 있어 단순한 개인 챗봇보다는 전문 업무 모델이나 로컬 AI Agent를 만들기 위한 기반 모델로 활용 가치가 크다.
다만 핵심은 모델 크기가 아니다.
좋은 Base Model
+
좋은 Dataset
+
적절한 Fine-tuning
+
정확한 Evaluation
이 네 가지가 더 중요하다.
처음 시도한다면 거대한 31B 모델을 학습하기보다 Gemma 4 E4B + Vast.ai의 24GB급 GPU + Unsloth QLoRA 정도의 구성으로 작은 Dataset부터 실험하는 것이 합리적이다.
그리고 Fine-tuning이 실제로 효과가 있다는 것을 확인한 뒤 12B나 31B 모델, RAG, Tool Calling, AI Agent로 단계적으로 확장하는 것이 비용과 개발 난이도 측면에서 가장 효율적인 접근이다.

When you try to put generative AI into a real product, one problem appears immediately: GPU cost.
Open-weight LLMs such as Gemma 4 can run on your own infrastructure, but fine-tuning them requires substantially more GPU memory. Buying an A100 or H100 server is rarely realistic for an independent developer or a small team.
A practical alternative is Vast.ai + Unsloth + Gemma 4:
- Gemma 4: the base LLM to adapt
- Unsloth: a framework that reduces fine-tuning time and VRAM use
- Vast.ai: a marketplace where you rent a GPU only for the time you need it
Gemma 4 launched in April 2026 with text and image input, audio on selected variants, up to a 256K context window, 140+ languages, reasoning, and function calling. Google first released E2B, E4B, 26B A4B, and 31B, then added the 12B model in June 2026.
This guide walks through the complete workflow for adapting Gemma 4 for a personal project or production prototype.
1. Why combine Vast.ai, Unsloth, and Gemma 4?
Gemma 4
Gemma 4 is Google DeepMind's open-weight model family.
| Model | Positioning |
|---|---|
| Gemma 4 E2B | Small model designed with mobile and edge use in mind |
| Gemma 4 E4B | Lightweight model for local experiments |
| Gemma 4 12B | Mid-size unified multimodal model |
| Gemma 4 26B A4B | 26B MoE architecture with about 4B active parameters |
| Gemma 4 31B | High-capability dense model |
The family targets reasoning, coding, agentic workflows, and native system prompts. Possible applications include Korean customer support, domain-specific QA, internal-document assistants, coding assistants, controlled writing styles, multimodal systems, and tool-calling agents.
2. What is Unsloth?
You can fine-tune Gemma 4 with the standard Hugging Face Transformers stack, but full fine-tuning uses a great deal of memory. Most individual developers therefore begin with LoRA or QLoRA.
Unsloth optimizes this parameter-efficient workflow. Vast.ai's official Unsloth Studio guide describes a target of up to roughly 2× faster training and up to 70% less VRAM than conventional approaches. Actual savings vary with the model, GPU, context length, and batch size.
Gemma 4
↓
Unsloth
↓
QLoRA
↓
Lower VRAM use
↓
Lower GPU cost
3. What is Vast.ai?
Vast.ai is a GPU marketplace. Multiple providers list machines, and renters compare GPU type, VRAM, hourly price, reliability, storage, and network characteristics.
You can rent hardware such as RTX 3090, RTX 4090, RTX 5090, A6000, A100, H100, or H200 only when you need it. Vast.ai also provides an official Unsloth Studio template, which removes much of the CUDA setup and exposes a browser UI.
4. How the three pieces fit together
Vast.ai GPU
↓
Unsloth
↓
Load Gemma 4
↓
Dataset + QLoRA
↓
Custom Gemma 4
↓
LoRA / GGUF / Hugging Face
↓
Ollama / LM Studio / vLLM / API server
You do not need to own the GPU. Rent it for training, export the result to Hugging Face or your computer, verify the files, and destroy the instance.
5. The easiest route: Vast.ai + Unsloth Studio
For a first attempt, the graphical Studio workflow is easier than writing the entire Python training stack.
Step 1. Create a Vast.ai account
Create an account, add credit, and open the instance search page.
Step 2. Choose the Unsloth Studio template
Select the Unsloth Studio template and compare:
- GPU VRAM
- Hourly price
- Host reliability
- Disk capacity and cost
Vast.ai recommends choosing reliability above 95% where possible.
6. Which GPU should you choose?
Do not begin with Gemma 4 31B by default. Start small and validate the workflow first.
Beginner
Gemma 4 E2B / E4B + 24 GB RTX 3090 / 4090 class
Intermediate
Gemma 4 12B + 24–48 GB GPU
Larger experiment
Gemma 4 26B A4B / 31B + 48 GB or multi-GPU
Treat this as a conservative starting matrix, not a guaranteed minimum. Published Gemma 4 GGUF memory tables describe inference, not fine-tuning. Training memory changes with sequence length, batch size, gradient checkpointing, LoRA targets, and quantization. Begin with a small model and short context, then watch GPU memory before increasing settings.
7. Launch Unsloth Studio
After the Vast.ai instance reaches Running, choose Open, then launch Unsloth Studio from the Applications page. The current template provides browser-based model management and fine-tuning, so a notebook is optional.
8. Download Gemma 4
Unsloth publishes instruction-tuned checkpoints such as:
unsloth/gemma-4-E2B-it
unsloth/gemma-4-E4B-it
unsloth/gemma-4-12b-it
unsloth/gemma-4-26B-A4B-it
unsloth/gemma-4-31B-it
Base checkpoints are also available without -it. For a chatbot or instruction-following service, starting from an instruction-tuned checkpoint is usually easier.
9. Do not confuse GGUF with safetensors
GGUF is primarily an inference format, commonly used by Ollama, LM Studio, and llama.cpp. For fine-tuning, load a trainable safetensors checkpoint. The Vast.ai Unsloth Studio documentation explicitly separates GGUF inference from safetensors-based training.
10. Prepare the dataset
The dataset matters more than the GPU brand.
{
"messages": [
{"role": "user", "content": "How do I create an account?"},
{"role": "assistant", "content": "Choose Sign up in the upper-right corner, then verify your email."}
]
}
Hundreds or thousands of carefully reviewed examples can teach a service-specific response pattern. Unsloth Studio accepts JSON, JSONL, CSV, Parquet, PDF, DOCX, and TXT, and recognizes common conversational formats such as ChatML, Alpaca, and ShareGPT.
11. Train with QLoRA
| Method | VRAM | When to use it |
|---|---|---|
| QLoRA 4-bit | Low | Best default for a first experiment |
| LoRA 16-bit | Medium | When more VRAM is available |
| Full fine-tuning | Very high | Only for constrained, well-justified cases |
For most individual developers, QLoRA 4-bit is the sensible starting point.
12. Initial training parameters
A practical first configuration is:
Epochs: 1–3
Learning rate: 2e-4
Batch size: 2–4
Context length: 2048
LoRA rank: 16
These are starting values, not universal defaults. Longer context consumes more memory. If you encounter an out-of-memory error, reduce batch size first, then context length and LoRA rank; rent a larger GPU only after those checks.
13. Fine-tune Gemma 4 directly with Python
For programmatic control, use Unsloth's FastModel. Gemma 4 integration changes quickly, so check the current Unsloth Gemma 4 guide and its notebook installation cell before training.
from unsloth import FastModel
model, tokenizer = FastModel.from_pretrained(
model_name="unsloth/gemma-4-E4B-it",
max_seq_length=8192,
load_in_4bit=True,
full_finetuning=False,
)
load_in_4bit=True reduces model memory use through 4-bit quantization.
14. Add a LoRA adapter
model = FastModel.get_peft_model(
model,
finetune_vision_layers=False,
finetune_language_layers=True,
finetune_attention_modules=True,
finetune_mlp_modules=True,
r=8,
lora_alpha=8,
lora_dropout=0,
bias="none",
)
For a text-focused project, vision layers can remain frozen. Multimodal image or audio fine-tuning requires different preprocessing and should follow the latest official example. A higher LoRA rank can increase adaptation capacity, but it also increases memory use and overfitting risk.
15. Apply the Gemma 4 chat template
Instruction models expect a model-specific conversation format. Concatenating raw questions and answers can damage training quality.
from unsloth.chat_templates import get_chat_template
tokenizer = get_chat_template(
tokenizer,
chat_template="gemma-4-thinking",
)
This is especially important for reasoning and multi-turn data. Keep only the final visible answer in later chat history unless the current model guide explicitly says otherwise.
16. Configure the trainer
Unsloth works with TRL's SFTTrainer and SFTConfig.
from trl import SFTTrainer, SFTConfig
trainer = SFTTrainer(
model=model,
tokenizer=tokenizer,
train_dataset=dataset,
args=SFTConfig(
dataset_text_field="text",
per_device_train_batch_size=1,
gradient_accumulation_steps=4,
learning_rate=2e-4,
max_steps=60,
logging_steps=1,
optim="adamw_8bit",
weight_decay=0.001,
lr_scheduler_type="linear",
report_to="none",
),
)
trainer.train()
The official notebook uses max_steps=60 for a quick test. Switch to an epoch-based plan for a real run and evaluate between experiments.
17. Save the fine-tuned result
model.save_pretrained("gemma_4_lora")
tokenizer.save_pretrained("gemma_4_lora")
This saves the small LoRA adapter rather than another full copy of Gemma 4:
Gemma 4 base model + LoRA adapter = fine-tuned Gemma 4
18. Upload it to Hugging Face
model.push_to_hub("username/gemma4-custom", token="HF_TOKEN")
tokenizer.push_to_hub("username/gemma4-custom", token="HF_TOKEN")
Do not hard-code a real token in a shared notebook or screenshot. Use environment-based authentication, and confirm whether the target repository is public or private. Uploading the result before deleting the rental protects you from losing the training output.
19. Export GGUF for local inference
You can train in the cloud and run locally:
Vast.ai training → GGUF export → Mac / Windows → Ollama / LM Studio / llama.cpp
Unsloth Studio can export a merged model, LoRA-only files, or GGUF/llama.cpp artifacts. Q4_K_M is a common starting point when balancing size and quality, but compare quantizations against your own evaluation set.
20. The main benefits
First: no need to buy a GPU
Rent compute for the training window, save the model, and destroy the instance.
Second: QLoRA lowers the VRAM requirement
QLoRA trains a relatively small adapter rather than updating every parameter, making many experiments possible on consumer-class GPUs.
Third: lower iteration cost
Fine-tuning is iterative: dataset v1, training, evaluation, dataset revision, and another run. A marketplace lets a prototype team choose a different GPU for each stage rather than owning idle hardware.
21. What does fine-tuning improve?
Fine-tuning does not automatically make a model more intelligent or turn it into a perfect database of company documents. It is especially effective for:
Response format
Teaching a support model to return an approved answer structure.
Tone and style
Converting a generic response into the organization's official service tone or a consistent editorial style.
Output schema
For example, always returning machine-readable JSON:
{"category": "refund", "priority": "normal", "answer": "..."}
22. Consider RAG when the goal is knowledge injection
Frequently changing prices, policies, and internal documents are usually a better fit for retrieval-augmented generation:
Gemma 4 + vector database + RAG
Fine-tuning is better for behavior, format, style, classification, and task patterns. In production, fine-tuning + RAG is often the practical combination.
23. A good dataset makes a good model
Ten thousand low-quality examples can be less useful than one thousand carefully reviewed examples. Remove duplicates, incorrect answers, inconsistent tone, unnecessary length, and hallucinated claims. Vary the phrasing of questions and keep a separate evaluation set.
24. Always compare the base and fine-tuned models
A lower training loss does not prove that the model improved. Send the same prompts to the original and adapted models. Unsloth Studio's Model Arena can help with side-by-side comparison.
Define criteria before the run: factual accuracy, format compliance, hallucination rate, answer length, terminology, and natural language quality.
25. The most important Vast.ai precautions
When the work is complete, destroy the instance. Stopping it can pause compute charges while storage charges continue. Destroying removes instance data, so export and verify the model first.
Train → test → save LoRA → upload → export GGUF if needed → verify → destroy
Vast.ai is a marketplace of multiple providers. Before uploading customer data or internal documents, review the provider type and security requirements. Prefer de-identified or encrypted data and an appropriately verified data-center host for sensitive workloads.
26. A recommended first experiment
GPU: RTX 4090-class, 24 GB
Model: Gemma 4 E4B IT
Method: QLoRA 4-bit
Dataset: 500–2,000 reviewed samples
Epochs: 1
Context: 2048
LoRA rank: 8–16
Choose one narrow goal, such as a Korean IT blog-writing model. A compact, high-quality conversational dataset is enough to test whether the model follows the intended structure and tone more reliably.
27. How to expand after the first success
Stage 1: Gemma 4 E4B + QLoRA + text dataset
Stage 2: Gemma 4 12B + larger dataset + evaluation set
Stage 3: fine-tuned Gemma 4 + RAG + vector DB + function calling
Stage 4: frontend + FastAPI / Node.js + vLLM + fine-tuned Gemma 4
Expand only after each stage demonstrates measurable improvement.
28. Architecture summary
Vast.ai GPU cloud
↓
Unsloth fine-tuning
↓
Gemma 4 base model
↓
Dataset → QLoRA → custom Gemma 4
├→ GGUF → Ollama / LM Studio
└→ LoRA adapter → Hugging Face
Conclusion
Fine-tuning an LLM once required expensive owned hardware and extensive machine-learning infrastructure. Today, you can rent a GPU by the hour on Vast.ai, reduce memory use with Unsloth QLoRA, and adapt an open-weight Gemma 4 model to your own task. The official Studio template even makes a code-free first run possible.
The model size is not the deciding factor. What matters is the combination of a suitable base model, clean data, appropriate training settings, and rigorous evaluation.
Start with Gemma 4 E4B + a 24 GB Vast.ai GPU + Unsloth QLoRA and a small, high-quality dataset. Once the comparison proves that fine-tuning helps, expand deliberately to 12B or 31B, RAG, tool calling, and a production agent.

当生成式 AI 真正进入产品开发时,首先遇到的问题往往是 GPU 成本。
Gemma 4 这类开放权重模型可以自行部署,但微调需要更多显存。对个人开发者和小团队来说,购买 A100 或 H100 服务器通常并不现实。
一个更务实的组合是 Vast.ai + Unsloth + Gemma 4:
- **Gemma 4:**需要微调的基础大语言模型
- **Unsloth:**减少训练时间与显存占用的微调框架
- **Vast.ai:**按需租用 GPU 的算力市场
Gemma 4 于 2026 年 4 月发布,支持文本与图像输入,部分型号还支持音频,并提供最高 256K 上下文、140 多种语言、推理和函数调用能力。Google 先推出 E2B、E4B、26B A4B 与 31B,随后在 2026 年 6 月增加了 12B 型号。
本文将介绍如何用这三项技术,以较低成本完成个人或服务型 Gemma 4 的微调、评估与导出。
1. 为什么选择 Vast.ai + Unsloth + Gemma 4?
Gemma 4
Gemma 4 是 Google DeepMind 的开放权重模型家族。
| 模型 | 定位 |
|---|---|
| Gemma 4 E2B | 面向移动端与边缘设备的小模型 |
| Gemma 4 E4B | 适合本地实验的轻量模型 |
| Gemma 4 12B | 统一多模态中型模型 |
| Gemma 4 26B A4B | 约激活 4B 参数的 26B MoE 模型 |
| Gemma 4 31B | 高能力 Dense 模型 |
它适用于推理、编程和 Agent 工作流,并支持原生 system prompt。应用包括客服、领域问答、企业文档助手、代码助手、固定文风生成、多模态理解和工具调用 Agent。
2. 什么是 Unsloth?
标准 Hugging Face Transformers 也能微调 Gemma 4,但全参数微调非常消耗显存。因此个人开发者通常从 LoRA 或 QLoRA 开始。
Unsloth 对参数高效微调流程进行了优化。Vast.ai 的官方指南将其描述为相对传统流程最高约 2 倍训练速度、最多节省 70% 显存的方案;实际结果会随模型、GPU、上下文长度和 batch size 而变化。
Gemma 4 → Unsloth → QLoRA → 更低显存 → 更低 GPU 成本
3. 什么是 Vast.ai?
Vast.ai 是 GPU 算力市场。不同供应商发布机器,用户可以比较 GPU 型号、显存、时价、可靠性、存储和网络条件。
RTX 3090、4090、5090、A6000、A100、H100、H200 等设备都可以按需租用。Vast.ai 还提供官方 Unsloth Studio 模板,省去大量 CUDA 配置,并通过浏览器操作。
4. 三者如何协作?
Vast.ai GPU
↓
Unsloth
↓
加载 Gemma 4
↓
数据集 + QLoRA
↓
自定义 Gemma 4
↓
LoRA / GGUF / Hugging Face
↓
Ollama / LM Studio / vLLM / API
训练时租用 GPU,完成后将模型上传或下载并验证文件,最后销毁实例即可。
5. 最简单的方法:Vast.ai + Unsloth Studio
第一次尝试时,Studio 图形界面比从零编写 Python 训练代码更容易。
Step 1. 注册 Vast.ai
创建账户、充值,然后进入实例搜索页面。
Step 2. 选择 Unsloth Studio 模板
比较 GPU 显存、每小时价格、主机可靠性以及磁盘容量和费用。条件允许时,建议选择 95% 以上可靠性的实例。
6. 应该选择哪种 GPU?
不要一开始就选择 Gemma 4 31B。先用小模型验证流程。
入门:Gemma 4 E2B / E4B + 24GB RTX 3090 / 4090 级
进阶:Gemma 4 12B + 24–48GB GPU
大型实验:Gemma 4 26B A4B / 31B + 48GB 或多 GPU
这只是保守起点,并非保证的最低要求。Gemma 4 的 GGUF 内存表是推理数据,不能当成微调显存要求。训练显存取决于序列长度、batch size、gradient checkpointing、LoRA 目标模块与量化方式。建议从短上下文开始,观察显存后再逐步增加。
7. 启动 Unsloth Studio
Vast.ai 实例进入 Running 后选择 Open,再从 Applications 页面打开 Unsloth Studio。当前模板已提供浏览器端的模型管理与微调界面,不一定需要 Jupyter Notebook。
8. 下载 Gemma 4
Unsloth 提供以下 instruction-tuned 检查点:
unsloth/gemma-4-E2B-it
unsloth/gemma-4-E4B-it
unsloth/gemma-4-12b-it
unsloth/gemma-4-26B-A4B-it
unsloth/gemma-4-31B-it
不带 -it 的 Base 模型也可用。制作聊天机器人或指令型服务时,从 instruction-tuned 模型开始通常更方便。
9. 不要混淆 GGUF 与 safetensors
GGUF 主要用于 Ollama、LM Studio、llama.cpp 等推理环境。微调时应加载可训练的 safetensors 检查点。Vast.ai 的 Unsloth Studio 文档也明确区分 GGUF 推理与 safetensors 训练。
10. 准备数据集
数据质量比 GPU 品牌更重要。
{
"messages": [
{"role": "user", "content": "如何注册会员?"},
{"role": "assistant", "content": "请选择网站右上角的注册按钮,然后完成邮箱验证。"}
]
}
数百到数千条经过审核的样本可以教会模型特定服务的回答方式。Unsloth Studio 支持 JSON、JSONL、CSV、Parquet、PDF、DOCX、TXT,以及 ChatML、Alpaca、ShareGPT 等常见会话格式。
11. 使用 QLoRA 训练
| 方法 | 显存 | 适用场景 |
|---|---|---|
| QLoRA 4-bit | 低 | 首次实验的默认选择 |
| LoRA 16-bit | 中 | 显存较充足时 |
| 全参数微调 | 很高 | 仅在必要且资源充足时 |
多数个人开发者应先选择 QLoRA 4-bit。
12. 初始训练参数
Epochs: 1–3
Learning rate: 2e-4
Batch size: 2–4
Context length: 2048
LoRA rank: 16
这些只是起点。上下文越长,显存消耗越高。如果出现 OOM,依次减少 batch size、context length 和 LoRA rank,最后再考虑更大显存的 GPU。
13. 使用 Python 直接微调 Gemma 4
需要程序化控制时,可以使用 Unsloth 的 FastModel。Gemma 4 集成更新很快,训练前应先查看最新官方指南和 notebook 的安装单元。
from unsloth import FastModel
model, tokenizer = FastModel.from_pretrained(
model_name="unsloth/gemma-4-E4B-it",
max_seq_length=8192,
load_in_4bit=True,
full_finetuning=False,
)
load_in_4bit=True 通过 4-bit 量化降低模型加载的显存需求。
14. 添加 LoRA Adapter
model = FastModel.get_peft_model(
model,
finetune_vision_layers=False,
finetune_language_layers=True,
finetune_attention_modules=True,
finetune_mlp_modules=True,
r=8,
lora_alpha=8,
lora_dropout=0,
bias="none",
)
纯文本任务可以冻结视觉层。图像或音频微调需要不同的预处理,应参考最新多模态示例。LoRA rank 越高,适配能力可能越强,但显存与过拟合风险也会增加。
15. 应用 Gemma 4 Chat Template
Instruction 模型需要特定对话格式,简单拼接问题和回答可能降低训练质量。
from unsloth.chat_templates import get_chat_template
tokenizer = get_chat_template(
tokenizer,
chat_template="gemma-4-thinking",
)
这对推理数据和多轮对话尤其重要。除非当前官方指南另有说明,后续对话历史中只保留可见的最终答案。
16. 配置 Trainer
Unsloth 可与 TRL 的 SFTTrainer 和 SFTConfig 配合使用。
from trl import SFTTrainer, SFTConfig
trainer = SFTTrainer(
model=model,
tokenizer=tokenizer,
train_dataset=dataset,
args=SFTConfig(
dataset_text_field="text",
per_device_train_batch_size=1,
gradient_accumulation_steps=4,
learning_rate=2e-4,
max_steps=60,
logging_steps=1,
optim="adamw_8bit",
weight_decay=0.001,
lr_scheduler_type="linear",
report_to="none",
),
)
trainer.train()
官方 notebook 用 max_steps=60 快速验证。正式训练应改为基于 epoch 的计划,并在多次实验之间进行评估。
17. 保存微调结果
model.save_pretrained("gemma_4_lora")
tokenizer.save_pretrained("gemma_4_lora")
这里保存的是较小的 LoRA Adapter,而不是完整模型副本:
Gemma 4 Base Model + LoRA Adapter = 微调后的 Gemma 4
18. 上传到 Hugging Face
model.push_to_hub("username/gemma4-custom", token="HF_TOKEN")
tokenizer.push_to_hub("username/gemma4-custom", token="HF_TOKEN")
不要把真实 Token 写进共享 notebook 或截图。使用环境变量或登录功能,并确认仓库是公开还是私有。删除租用实例前上传结果,可以避免训练文件丢失。
19. 导出 GGUF 并在本地运行
Vast.ai 训练 → 导出 GGUF → Mac / Windows → Ollama / LM Studio / llama.cpp
Unsloth Studio 可以导出合并模型、仅 LoRA 文件或 GGUF/llama.cpp 文件。Q4_K_M 常被用作体积与质量的平衡起点,但仍应使用自己的评估集比较不同量化版本。
20. 这个组合的主要优势
第一:无需购买 GPU
只为训练时段付费,保存模型后销毁实例。
第二:QLoRA 降低显存需求
QLoRA 只训练较小的 Adapter,而不是更新全部参数,使消费级 GPU 也能承担许多实验。
第三:降低迭代成本
微调通常要经历数据集 v1、训练、评估、修订和再次训练。算力市场允许团队按阶段更换 GPU,无需让自有硬件长期闲置。
21. 微调能改善什么?
微调不会自动让模型更聪明,也不会使它完整记住所有企业文档。它更适合学习:
回答格式
例如客服系统的固定回答结构。
语气与文风
将通用回复转换为正式客服语气或稳定的编辑风格。
输出结构
例如始终返回 JSON:
{"category": "refund", "priority": "normal", "answer": "..."}
22. 如果目标是注入知识,请考虑 RAG
经常变化的价格、政策和内部文档更适合:
Gemma 4 + Vector DB + RAG
微调更适合行为、格式、文风、分类和任务模式。生产环境常将 微调与 RAG 结合使用。
23. 好数据集决定好模型
一万条低质量数据可能不如一千条高质量数据。应删除重复项、错误回答、文风不一致、过长内容与幻觉信息,并增加问题表达的多样性。训练集之外还要保留独立评估集。
24. 必须比较 Base 与微调模型
训练 loss 下降不代表实际效果变好。应把相同 prompt 同时发送给原始模型与微调模型;Unsloth Studio 的 Model Arena 可以辅助并排比较。
训练前定义准确性、格式遵守、幻觉、回答长度、术语和语言自然度等评价标准。
25. 使用 Vast.ai 时最重要的注意事项
工作完成后要 Destroy 实例。Stop 可能停止计算费,但存储费仍会继续。Destroy 会删除实例数据,因此必须先导出并验证模型。
训练 → 测试 → 保存 LoRA → 上传 → 必要时导出 GGUF → 验证 → Destroy
Vast.ai 连接多个供应商。上传客户资料或内部文档前,应检查供应商类型与安全要求。敏感任务尽量使用去标识化或加密数据,并选择适当验证的数据中心主机。
26. 推荐的第一次实验
GPU: RTX 4090 级 24GB
Model: Gemma 4 E4B IT
Method: QLoRA 4-bit
Dataset: 500–2,000 条审核样本
Epochs: 1
Context: 2048
LoRA rank: 8–16
先设定一个狭窄目标,例如“韩语 IT 技术博客写作模型”,验证模型是否更稳定地遵循目标结构与语气。
27. 第一次成功后如何扩展?
Stage 1: Gemma 4 E4B + QLoRA + 文本数据集
Stage 2: Gemma 4 12B + 更大数据集 + 评估集
Stage 3: 微调 Gemma 4 + RAG + Vector DB + Function Calling
Stage 4: Frontend + FastAPI / Node.js + vLLM + 微调模型
每个阶段都确认有可测量的改善后,再继续扩展。
28. 整体架构
Vast.ai GPU Cloud
↓
Unsloth Fine-tuning
↓
Gemma 4 Base Model
↓
Dataset → QLoRA → Custom Gemma 4
├→ GGUF → Ollama / LM Studio
└→ LoRA Adapter → Hugging Face
总结
过去,微调大语言模型需要昂贵的自有 GPU 与复杂的机器学习基础设施。现在可以在 Vast.ai 按小时租用 GPU,用 Unsloth QLoRA 降低显存占用,再把 Gemma 4 调整为适合自己的模型。官方 Studio 模板还允许用户先从无代码流程开始。
决定结果的并不是模型越大越好,而是合适的基础模型、干净的数据、合理的训练设置和严格的评估。
第一次尝试可从 Gemma 4 E4B + Vast.ai 24GB GPU + Unsloth QLoRA 和小型高质量数据集开始。确认微调确实有效后,再逐步扩展到 12B 或 31B、RAG、工具调用与生产级 Agent。

生成AIを実際のサービスに導入すると、すぐに直面するのが GPUコストです。
Gemma 4のようなオープンウェイトLLMは自前で実行できますが、ファインチューニングにはさらに多くのGPUメモリが必要です。個人開発者や小規模チームがA100やH100サーバーを購入するのは現実的ではありません。
そこで有効なのが Vast.ai + Unsloth + Gemma 4 の組み合わせです。
- Gemma 4: 調整するベースLLM
- Unsloth: 学習時間とVRAM使用量を抑えるフレームワーク
- Vast.ai: 必要な時間だけGPUを借りるマーケットプレイス
Gemma 4は2026年4月に公開され、テキストと画像入力、一部モデルでは音声、最大256Kコンテキスト、140以上の言語、reasoning、function callingをサポートします。E2B、E4B、26B A4B、31Bに続き、2026年6月には12Bモデルも追加されました。
この記事では、3つを組み合わせて低コストでGemma 4を学習・評価・保存・配備する流れを解説します。
1. なぜVast.ai・Unsloth・Gemma 4なのか
Gemma 4
Gemma 4はGoogle DeepMindのオープンウェイトモデル群です。
| モデル | 位置づけ |
|---|---|
| Gemma 4 E2B | モバイル・エッジ向け小型モデル |
| Gemma 4 E4B | ローカル実験向け軽量モデル |
| Gemma 4 12B | 統合マルチモーダル中型モデル |
| Gemma 4 26B A4B | 約4Bを有効化する26B MoE |
| Gemma 4 31B | 高性能Denseモデル |
reasoning、coding、agentic workflow、native system promptに対応し、カスタマーサポート、専門QA、社内文書アシスタント、コーディング支援、文体制御、マルチモーダル処理、Tool Calling Agentなどに利用できます。
2. Unslothとは
通常のHugging Face Transformersでも学習できますが、Full Fine-tuningは大量のVRAMを消費します。個人開発では LoRAまたはQLoRA から始めるのが一般的です。
UnslothはこのParameter-Efficient Fine-Tuningを最適化します。Vast.aiの公式ガイドは、従来手法に対して最大およそ 2倍の学習速度、最大70%のVRAM削減を目標として説明しています。実際の差はモデル、GPU、コンテキスト長、バッチサイズによって変わります。
Gemma 4 → Unsloth → QLoRA → VRAM削減 → GPU費用削減
3. Vast.aiとは
Vast.aiは複数のプロバイダーがマシンを提供するGPUマーケットプレイスです。GPU、VRAM、時間単価、信頼性、ストレージ、ネットワークを比較して借りられます。
RTX 3090、4090、5090、A6000、A100、H100、H200などを必要な時間だけ利用できます。公式Unsloth Studioテンプレートもあり、複雑なCUDA設定を減らしてブラウザから操作できます。
4. 3つを組み合わせた構成
Vast.ai GPU → Unsloth → Gemma 4
↓
Dataset + QLoRA
↓
Custom Gemma 4
↓
LoRA / GGUF / Hugging Face
↓
Ollama / LM Studio / vLLM / API
学習時だけGPUを借り、結果をHugging Faceやローカルへ保存・確認してからインスタンスを破棄します。
5. 最も簡単な方法:Vast.ai + Unsloth Studio
初回はPython環境をすべて組むより、StudioのUIが簡単です。
Step 1. Vast.aiへ登録
アカウントを作成し、クレジットを追加してインスタンス検索画面を開きます。
Step 2. Unsloth Studioテンプレートを選択
GPU VRAM、時間単価、Reliability、ディスク容量と費用を比較します。可能なら Reliability 95%以上を選びます。
6. どのGPUを選ぶべきか
最初から31Bを選ばず、小型モデルで一連の流れを確認します。
入門:Gemma 4 E2B / E4B + 24GB RTX 3090 / 4090級
中級:Gemma 4 12B + 24〜48GB GPU
大型実験:Gemma 4 26B A4B / 31B + 48GBまたはMulti-GPU
これは最低要件ではなく、保守的な出発点です。Gemma 4のGGUFメモリ表は推論用であり、学習VRAMではありません。必要量はsequence length、batch size、gradient checkpointing、LoRA対象、量子化で変わります。短いcontextから始め、実測しながら増やしましょう。
7. Unsloth Studioを起動
インスタンスがRunningになったら Open を選び、Applicationsから Unsloth Studio を起動します。モデル管理とファインチューニングはブラウザUIで行えるため、Notebookは必須ではありません。
8. Gemma 4をダウンロード
Instruction-tunedモデルの例は次の通りです。
unsloth/gemma-4-E2B-it
unsloth/gemma-4-E4B-it
unsloth/gemma-4-12b-it
unsloth/gemma-4-26B-A4B-it
unsloth/gemma-4-31B-it
-itなしのBase Modelもあります。チャットボットや指示追従サービスならinstruction-tunedから始めると扱いやすくなります。
9. GGUFとsafetensorsを混同しない
GGUFは主にOllama、LM Studio、llama.cppで使う推論形式です。学習にはtrainableなsafetensors checkpointを読み込みます。Vast.aiのStudio文書もGGUF推論とsafetensors学習を区別しています。
10. Datasetを準備
GPUのブランド以上に重要なのがDatasetです。
{
"messages": [
{"role": "user", "content": "会員登録はどうすればよいですか?"},
{"role": "assistant", "content": "右上の登録ボタンを選び、メール認証を完了してください。"}
]
}
数百〜数千件のレビュー済み例から、サービス固有の応答パターンを学習できます。StudioはJSON、JSONL、CSV、Parquet、PDF、DOCX、TXTと、ChatML、Alpaca、ShareGPT系の形式を扱えます。
11. QLoRAで学習
| 方式 | VRAM | 用途 |
|---|---|---|
| QLoRA 4-bit | 低 | 最初の標準選択 |
| LoRA 16-bit | 中 | VRAMに余裕がある場合 |
| Full Fine-tuning | 非常に高い | 明確な必要性がある場合のみ |
個人開発では QLoRA 4-bit が現実的です。
12. 最初のTraining Parameter
Epochs: 1〜3
Learning rate: 2e-4
Batch size: 2〜4
Context length: 2048
LoRA rank: 16
これは出発点です。OOMが起きたらbatch size、context length、LoRA rankの順に下げ、それでも必要ならより大きなGPUを検討します。
13. Pythonで直接Gemma 4を学習
細かく制御する場合はUnslothの FastModel を使います。統合は頻繁に更新されるため、実行前に最新Gemma 4ガイドとNotebookのインストールセルを確認してください。
from unsloth import FastModel
model, tokenizer = FastModel.from_pretrained(
model_name="unsloth/gemma-4-E4B-it",
max_seq_length=8192,
load_in_4bit=True,
full_finetuning=False,
)
load_in_4bit=True で4-bit量子化を使い、読み込み時のメモリを抑えます。
14. LoRA Adapterを追加
model = FastModel.get_peft_model(
model,
finetune_vision_layers=False,
finetune_language_layers=True,
finetune_attention_modules=True,
finetune_mlp_modules=True,
r=8,
lora_alpha=8,
lora_dropout=0,
bias="none",
)
テキスト用途ではvision layerを固定できます。画像や音声を学習する場合は前処理が異なるため、最新のマルチモーダル例に従います。rankを上げると表現力が増える可能性がある一方、VRAMと過学習リスクも増えます。
15. Gemma 4 Chat Templateを適用
Instruction Modelには固有の会話形式があります。質問と回答を単純連結すると品質が落ちる可能性があります。
from unsloth.chat_templates import get_chat_template
tokenizer = get_chat_template(
tokenizer,
chat_template="gemma-4-thinking",
)
reasoningやmulti-turnデータでは特に重要です。最新ガイドに別の指示がない限り、次の会話履歴には可視の最終回答だけを残します。
16. Trainerを構成
UnslothはTRLの SFTTrainer と SFTConfig を利用できます。
from trl import SFTTrainer, SFTConfig
trainer = SFTTrainer(
model=model,
tokenizer=tokenizer,
train_dataset=dataset,
args=SFTConfig(
dataset_text_field="text",
per_device_train_batch_size=1,
gradient_accumulation_steps=4,
learning_rate=2e-4,
max_steps=60,
logging_steps=1,
optim="adamw_8bit",
weight_decay=0.001,
lr_scheduler_type="linear",
report_to="none",
),
)
trainer.train()
max_steps=60 は動作確認向けです。本学習ではepochベースへ切り替え、各実験を評価します。
17. 学習結果を保存
model.save_pretrained("gemma_4_lora")
tokenizer.save_pretrained("gemma_4_lora")
保存されるのは小さなLoRA Adapterです。
Gemma 4 Base Model + LoRA Adapter = Fine-tuned Gemma 4
18. Hugging Faceへアップロード
model.push_to_hub("username/gemma4-custom", token="HF_TOKEN")
tokenizer.push_to_hub("username/gemma4-custom", token="HF_TOKEN")
実Tokenを共有Notebookや画面に直書きせず、環境変数やログイン機能で管理します。リポジトリの公開範囲も確認してください。インスタンス削除前にアップロードしておけば成果を失いません。
19. GGUFへ変換してローカル実行
Vast.aiで学習 → GGUF Export → Mac / Windows → Ollama / LM Studio / llama.cpp
StudioはMerged Model、LoRA Only、GGUF/llama.cppを出力できます。Q4_K_M は容量と品質のバランスを取る出発点ですが、自分の評価セットで各量子化を比較しましょう。
20. この構成の主な効果
1つ目:GPUを買わなくてよい
学習時間だけ借り、モデルを保存したらインスタンスを破棄できます。
2つ目:QLoRAでVRAMを抑えられる
全パラメータではなく小さなAdapterを学習するため、consumer GPUでも多くの実験が可能です。
3つ目:反復コストを下げられる
Dataset v1、Training、Evaluation、修正、再学習という反復ごとに、適切なGPUを選べます。
21. Fine-tuningで何が良くなるのか
Fine-tuningはモデルを自動的に賢くしたり、社内文書を完全に記憶させたりする手段ではありません。主に次を学ばせるのに向きます。
回答形式
承認済みのサポート回答構造などです。
文体
一般的な回答を会社の正式な応対文や一貫した記事スタイルへ変えます。
出力構造
常にJSONを返すようにできます。
{"category": "refund", "priority": "normal", "answer": "..."}
22. 知識注入ならRAGも検討
頻繁に変わる価格、規程、社内文書には次の構成が適します。
Gemma 4 + Vector DB + RAG
Fine-tuningは行動、形式、文体、分類、タスクパターンに向いています。本番では Fine-tuning + RAG が実用的です。
23. 良いDatasetが良いモデルを作る
低品質な1万件より、レビュー済みの1,000件が有効な場合があります。重複、誤答、文体の不統一、冗長さ、hallucinationを除き、質問表現を多様化します。独立したevaluation datasetも用意します。
24. Base Modelと必ず比較する
loss低下だけでは改善を証明できません。同じpromptを元モデルと学習後モデルへ送り、正確性、形式遵守、hallucination、長さ、用語、自然さを比較します。StudioのModel Arenaも利用できます。
25. Vast.ai利用時の重要な注意点
完了したらインスタンスを Destroy します。Stopでcompute料金が止まってもstorage料金は続く場合があります。Destroyはデータも削除するため、先にexportと検証を行います。
Training → Test → LoRA保存 → Upload → 必要ならGGUF → 確認 → Destroy
Vast.aiは複数プロバイダーの市場です。顧客情報や社内文書を扱う場合は、プロバイダーとセキュリティ要件を確認し、匿名化・暗号化したデータと適切に検証されたデータセンターを選びます。
26. おすすめの最初の実験
GPU: RTX 4090級 24GB
Model: Gemma 4 E4B IT
Method: QLoRA 4-bit
Dataset: 500〜2,000件
Epochs: 1
Context: 2048
LoRA rank: 8〜16
「韓国語ITブログ作成モデル」のように目標を1つに絞り、構成と文体の追従性が改善するか確認します。
27. 成功後の拡張
Stage 1: Gemma 4 E4B + QLoRA + Text Dataset
Stage 2: Gemma 4 12B + 大規模Dataset + Evaluation Dataset
Stage 3: Fine-tuned Gemma 4 + RAG + Vector DB + Function Calling
Stage 4: Frontend + FastAPI / Node.js + vLLM + Fine-tuned Model
各段階で測定可能な改善を確認してから次へ進みます。
28. 全体構成
Vast.ai GPU Cloud
↓
Unsloth Fine-tuning
↓
Gemma 4 Base Model
↓
Dataset → QLoRA → Custom Gemma 4
├→ GGUF → Ollama / LM Studio
└→ LoRA Adapter → Hugging Face
まとめ
以前はLLMのファインチューニングに高価なGPUと複雑な基盤が必要でした。現在はVast.aiで時間単位のGPUを借り、Unsloth QLoRAでVRAMを抑え、Gemma 4を目的に合わせて調整できます。公式Studioテンプレートならコードなしでも始められます。
重要なのはモデルの大きさではなく、適切なBase Model、質の高いDataset、妥当なTraining設定、正確なEvaluationです。
まずは Gemma 4 E4B + Vast.aiの24GB GPU + Unsloth QLoRA と小さな高品質Datasetで効果を確認し、その後12Bや31B、RAG、Tool Calling、実運用Agentへ段階的に広げるのが合理的です。

Al llevar la IA generativa a un producto real aparece enseguida un problema: el coste de la GPU.
Los LLM de pesos abiertos como Gemma 4 pueden ejecutarse en infraestructura propia, pero su fine-tuning exige bastante más memoria. Comprar un servidor A100 o H100 rara vez es viable para una persona o un equipo pequeño.
Una alternativa práctica es Vast.ai + Unsloth + Gemma 4:
- Gemma 4: el LLM base que se va a adaptar
- Unsloth: el framework que reduce tiempo de entrenamiento y consumo de VRAM
- Vast.ai: el marketplace donde se alquila una GPU solo durante el tiempo necesario
Gemma 4 se presentó en abril de 2026 con entrada de texto e imagen, audio en algunas variantes, hasta 256K de contexto, más de 140 idiomas, razonamiento y function calling. Google lanzó primero E2B, E4B, 26B A4B y 31B, y añadió el modelo 12B en junio de 2026.
Esta guía recorre el proceso completo para ajustar, evaluar, guardar y desplegar Gemma 4 con un presupuesto razonable.
1. ¿Por qué Vast.ai, Unsloth y Gemma 4?
Gemma 4
Gemma 4 es la familia de modelos de pesos abiertos de Google DeepMind.
| Modelo | Enfoque |
|---|---|
| Gemma 4 E2B | Modelo pequeño para móvil y edge |
| Gemma 4 E4B | Modelo ligero para experimentos locales |
| Gemma 4 12B | Modelo multimodal unificado de tamaño medio |
| Gemma 4 26B A4B | MoE de 26B con unos 4B parámetros activos |
| Gemma 4 31B | Modelo Dense de alta capacidad |
La familia está orientada a razonamiento, código, flujos de agentes y system prompts nativos. Puede servir para atención al cliente, QA especializado, asistentes documentales, ayuda de programación, escritura con estilo controlado, sistemas multimodales y agentes con herramientas.
2. ¿Qué es Unsloth?
Gemma 4 puede ajustarse con Hugging Face Transformers, pero el full fine-tuning consume mucha memoria. Por eso, la mayoría de proyectos pequeños comienza con LoRA o QLoRA.
Unsloth optimiza este entrenamiento eficiente en parámetros. La guía oficial de Vast.ai lo presenta como una vía que aspira a entrenar hasta aproximadamente 2 veces más rápido y usar hasta un 70% menos de VRAM. El ahorro real depende del modelo, la GPU, el contexto y el batch size.
Gemma 4 → Unsloth → QLoRA → menos VRAM → menor coste de GPU
3. ¿Qué es Vast.ai?
Vast.ai es un marketplace de GPU. Varios proveedores publican sus máquinas y el usuario compara GPU, VRAM, precio por hora, fiabilidad, almacenamiento y red.
Es posible alquilar RTX 3090, 4090, 5090, A6000, A100, H100 o H200 solo cuando hacen falta. Vast.ai también ofrece una plantilla oficial de Unsloth Studio que evita gran parte de la configuración de CUDA y se maneja desde el navegador.
4. Cómo encajan las tres piezas
GPU de Vast.ai → Unsloth → Gemma 4
↓
Dataset + QLoRA
↓
Gemma 4 adaptado
↓
LoRA / GGUF / Hugging Face
↓
Ollama / LM Studio / vLLM / API
Se alquila la GPU para entrenar, se exporta y verifica el resultado, y luego se destruye la instancia.
5. La vía más sencilla: Vast.ai + Unsloth Studio
Para una primera prueba, la interfaz de Studio es más accesible que construir todo el entorno de Python.
Paso 1. Crear una cuenta de Vast.ai
Crea la cuenta, añade crédito y abre la búsqueda de instancias.
Paso 2. Elegir la plantilla de Unsloth Studio
Compara VRAM, precio por hora, fiabilidad del host y coste/capacidad del disco. Cuando sea posible, elige una fiabilidad superior al 95%.
6. ¿Qué GPU conviene elegir?
No empieces por 31B. Comprueba primero el proceso con un modelo pequeño.
Inicio: Gemma 4 E2B / E4B + RTX 3090 / 4090 de 24 GB
Intermedio: Gemma 4 12B + GPU de 24–48 GB
Experimento grande: Gemma 4 26B A4B / 31B + 48 GB o varias GPU
Es un punto de partida conservador, no un mínimo garantizado. Las tablas de memoria GGUF de Gemma 4 describen inferencia, no fine-tuning. La memoria de entrenamiento cambia con la secuencia, batch size, gradient checkpointing, módulos LoRA y cuantización. Empieza con poco contexto y mide antes de subir valores.
7. Abrir Unsloth Studio
Cuando la instancia figure como Running, selecciona Open y abre Unsloth Studio desde Applications. La plantilla actual permite administrar y ajustar modelos desde el navegador; Jupyter no es obligatorio.
8. Descargar Gemma 4
Algunos checkpoints instruction-tuned de Unsloth son:
unsloth/gemma-4-E2B-it
unsloth/gemma-4-E4B-it
unsloth/gemma-4-12b-it
unsloth/gemma-4-26B-A4B-it
unsloth/gemma-4-31B-it
También existen modelos base sin -it. Para un chatbot o servicio de instrucciones suele ser más fácil comenzar por el modelo instruction-tuned.
9. No confundir GGUF con safetensors
GGUF es sobre todo un formato de inferencia para Ollama, LM Studio y llama.cpp. Para entrenar se necesita un checkpoint de safetensors que admita fine-tuning. La documentación de Studio separa explícitamente ambos usos.
10. Preparar el dataset
La calidad de los datos importa más que la marca de la GPU.
{
"messages": [
{"role": "user", "content": "¿Cómo creo una cuenta?"},
{"role": "assistant", "content": "Pulsa Registrarse arriba a la derecha y verifica tu correo."}
]
}
Cientos o miles de ejemplos revisados pueden enseñar el patrón de respuesta de un servicio. Studio acepta JSON, JSONL, CSV, Parquet, PDF, DOCX y TXT, además de formatos conversacionales como ChatML, Alpaca y ShareGPT.
11. Entrenar con QLoRA
| Método | VRAM | Uso |
|---|---|---|
| QLoRA 4-bit | Baja | Primera opción recomendada |
| LoRA 16-bit | Media | Cuando hay más VRAM |
| Full fine-tuning | Muy alta | Solo con una necesidad clara |
Para la mayoría de desarrolladores, QLoRA 4-bit es el comienzo razonable.
12. Parámetros iniciales
Epochs: 1–3
Learning rate: 2e-4
Batch size: 2–4
Context length: 2048
LoRA rank: 16
Son valores iniciales, no reglas universales. Ante un error OOM, reduce primero batch size, después context length y LoRA rank; solo entonces valora una GPU mayor.
13. Fine-tuning de Gemma 4 con Python
Para controlar el proceso por código se usa FastModel. La integración cambia con rapidez: antes de entrenar consulta la guía actual de Gemma 4 en Unsloth y la celda de instalación del notebook.
from unsloth import FastModel
model, tokenizer = FastModel.from_pretrained(
model_name="unsloth/gemma-4-E4B-it",
max_seq_length=8192,
load_in_4bit=True,
full_finetuning=False,
)
load_in_4bit=True reduce la memoria de carga mediante cuantización de 4 bits.
14. Añadir un adaptador LoRA
model = FastModel.get_peft_model(
model,
finetune_vision_layers=False,
finetune_language_layers=True,
finetune_attention_modules=True,
finetune_mlp_modules=True,
r=8,
lora_alpha=8,
lora_dropout=0,
bias="none",
)
En un proyecto de texto se pueden congelar las capas de visión. El ajuste multimodal de imagen o audio requiere otro preprocesado y debe seguir el ejemplo oficial más reciente. Un rank mayor puede dar más capacidad, pero también consume más memoria y aumenta el riesgo de sobreajuste.
15. Aplicar el chat template de Gemma 4
Los modelos de instrucciones esperan su propio formato conversacional. Unir preguntas y respuestas sin plantilla puede perjudicar la calidad.
from unsloth.chat_templates import get_chat_template
tokenizer = get_chat_template(
tokenizer,
chat_template="gemma-4-thinking",
)
Es especialmente importante con razonamiento y conversaciones multivuelta. Salvo que la guía vigente diga otra cosa, conserva solo la respuesta final visible en el historial posterior.
16. Configurar el trainer
Unsloth funciona con SFTTrainer y SFTConfig de TRL.
from trl import SFTTrainer, SFTConfig
trainer = SFTTrainer(
model=model,
tokenizer=tokenizer,
train_dataset=dataset,
args=SFTConfig(
dataset_text_field="text",
per_device_train_batch_size=1,
gradient_accumulation_steps=4,
learning_rate=2e-4,
max_steps=60,
logging_steps=1,
optim="adamw_8bit",
weight_decay=0.001,
lr_scheduler_type="linear",
report_to="none",
),
)
trainer.train()
max_steps=60 sirve para una prueba rápida. En un entrenamiento real conviene usar epochs y evaluar cada iteración.
17. Guardar el resultado
model.save_pretrained("gemma_4_lora")
tokenizer.save_pretrained("gemma_4_lora")
Se guarda el adaptador LoRA, mucho menor que otra copia completa del modelo:
Gemma 4 base + adaptador LoRA = Gemma 4 ajustado
18. Subirlo a Hugging Face
model.push_to_hub("username/gemma4-custom", token="HF_TOKEN")
tokenizer.push_to_hub("username/gemma4-custom", token="HF_TOKEN")
No escribas el token real en notebooks compartidos ni capturas. Usa autenticación por entorno y comprueba si el repositorio es público o privado. Sube el resultado antes de eliminar la instancia.
19. Exportar GGUF para inferencia local
Entrenamiento en Vast.ai → GGUF → Mac / Windows → Ollama / LM Studio / llama.cpp
Studio puede exportar el modelo fusionado, solo LoRA o archivos GGUF/llama.cpp. Q4_K_M es un punto de partida habitual para equilibrar tamaño y calidad, pero compara cuantizaciones con tu propio conjunto de evaluación.
20. Ventajas principales
Primera: no hay que comprar una GPU
Se alquila durante el entrenamiento, se guarda el modelo y se destruye la instancia.
Segunda: QLoRA reduce la VRAM
Entrena un adaptador pequeño en lugar de todos los parámetros, por lo que muchas pruebas caben en GPU de consumo.
Tercera: baja el coste de iteración
El ciclo dataset v1, entrenamiento, evaluación, corrección y nuevo entrenamiento puede usar la GPU más adecuada en cada fase.
21. ¿Qué mejora el fine-tuning?
No vuelve al modelo automáticamente más inteligente ni convierte los documentos internos en una memoria perfecta. Es especialmente útil para aprender:
Formato de respuesta
Por ejemplo, una estructura aprobada para soporte.
Tono y estilo
Transformar respuestas genéricas en el tono oficial de una empresa o en un estilo editorial coherente.
Estructura de salida
Por ejemplo, devolver siempre JSON:
{"category": "refund", "priority": "normal", "answer": "..."}
22. Si el objetivo es aportar conocimiento, considera RAG
Precios, políticas y documentos que cambian con frecuencia encajan mejor en:
Gemma 4 + base vectorial + RAG
El fine-tuning es mejor para conducta, formato, estilo, clasificación y patrones de tarea. En producción suele resultar práctico combinar fine-tuning + RAG.
23. Un buen dataset crea un buen modelo
Mil ejemplos bien revisados pueden superar a diez mil de baja calidad. Elimina duplicados, respuestas erróneas, tono inconsistente, contenido innecesariamente largo y alucinaciones. Varía las preguntas y conserva un conjunto de evaluación independiente.
24. Comparar siempre el modelo base y el ajustado
Que baje el loss no demuestra una mejora real. Envía los mismos prompts a ambos modelos; Model Arena de Studio puede ayudar. Define antes criterios como exactitud, formato, alucinaciones, longitud, terminología y naturalidad.
25. Precauciones esenciales en Vast.ai
Al terminar, hay que destruir la instancia. Stop puede detener el cómputo mientras el almacenamiento continúa cobrando. Destroy borra los datos, así que exporta y verifica primero.
Entrenar → probar → guardar LoRA → subir → exportar GGUF → verificar → Destroy
Vast.ai reúne varios proveedores. Antes de subir datos de clientes o documentos internos, revisa el tipo de host y los requisitos de seguridad. Para cargas sensibles, usa datos desidentificados o cifrados y un centro de datos debidamente verificado.
26. Primera prueba recomendada
GPU: RTX 4090 de 24 GB
Modelo: Gemma 4 E4B IT
Método: QLoRA 4-bit
Dataset: 500–2.000 ejemplos revisados
Epochs: 1
Context: 2048
LoRA rank: 8–16
Define un objetivo estrecho, como un modelo para redactar artículos técnicos en coreano, y comprueba si sigue mejor la estructura y el tono.
27. Cómo ampliar tras el primer éxito
Etapa 1: Gemma 4 E4B + QLoRA + dataset de texto
Etapa 2: Gemma 4 12B + más datos + evaluación
Etapa 3: Gemma 4 ajustado + RAG + base vectorial + function calling
Etapa 4: frontend + FastAPI / Node.js + vLLM + modelo ajustado
Avanza solo cuando cada etapa muestre una mejora medible.
28. Resumen de arquitectura
Vast.ai GPU Cloud
↓
Unsloth Fine-tuning
↓
Gemma 4 Base Model
↓
Dataset → QLoRA → Custom Gemma 4
├→ GGUF → Ollama / LM Studio
└→ LoRA Adapter → Hugging Face
Conclusión
Antes, ajustar un LLM exigía hardware propio costoso y una infraestructura compleja. Hoy se puede alquilar una GPU por horas en Vast.ai, reducir la memoria con QLoRA de Unsloth y adaptar Gemma 4 a una tarea concreta. La plantilla oficial de Studio permite incluso una primera prueba sin código.
El tamaño del modelo no es lo decisivo. Importan un modelo base adecuado, datos limpios, parámetros sensatos y una evaluación rigurosa.
Empieza con Gemma 4 E4B + una GPU de 24 GB en Vast.ai + QLoRA de Unsloth y un dataset pequeño de alta calidad. Cuando la comparación demuestre que el ajuste aporta valor, amplía gradualmente a 12B o 31B, RAG, herramientas y un agente de producción.