Skip to content

Commit a41d8e8

Browse files
committed
added model loader
1 parent 97b00c2 commit a41d8e8

2 files changed

Lines changed: 53 additions & 0 deletions

File tree

src/models/__init__.py

Whitespace-only changes.

src/models/model_loader.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import torch
2+
from transformers import (
3+
AutoModelForCausalLM,
4+
AutoTokenizer,
5+
BitsAndBytesConfig
6+
)
7+
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
8+
from src.config import settings
9+
10+
def get_tokenizer(model_name: str = settings.BASE_MODEL_NAME):
11+
"""Loads and configures the tokenizer."""
12+
tokenizer = AutoTokenizer.from_pretrained(model_name)
13+
tokenizer.pad_token = tokenizer.eos_token
14+
tokenizer.padding_side = "right" # Recommended for Llama-based models
15+
return tokenizer
16+
17+
def load_quantized_model(model_name: str = settings.BASE_MODEL_NAME):
18+
"""Loads the base model with 4-bit quantization."""
19+
bnb_config = BitsAndBytesConfig(
20+
load_in_4bit=True,
21+
bnb_4bit_quant_type="nf4",
22+
bnb_4bit_compute_dtype=torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16,
23+
bnb_4bit_use_double_quant=True,
24+
)
25+
26+
model = AutoModelForCausalLM.from_pretrained(
27+
model_name,
28+
quantization_config=bnb_config,
29+
device_map="auto",
30+
trust_remote_code=True
31+
)
32+
33+
# Prepare for training
34+
model.gradient_checkpointing_enable()
35+
model = prepare_model_for_kbit_training(model)
36+
37+
return model
38+
39+
def setup_peft_model(model):
40+
"""Configures and wraps the model with LoRA adapters."""
41+
peft_config = LoraConfig(
42+
r=settings.LORA_R,
43+
lora_alpha=settings.LORA_ALPHA,
44+
target_modules=settings.TARGET_MODULES,
45+
lora_dropout=settings.LORA_DROPOUT,
46+
bias="none",
47+
task_type="CAUSAL_LM"
48+
)
49+
50+
model = get_peft_model(model, peft_config)
51+
model.print_trainable_parameters()
52+
53+
return model, peft_config

0 commit comments

Comments
 (0)