Hugging Face Transformers ve QLoRA'yı kullanarak Gemma'yı Görsel Görevler için hassas ayarlama

Bu kılavuzda, Hugging Face Transformers ve TRL'yi kullanarak Gemma'yı bir görüntü görevi (ürün açıklamaları oluşturma) için özel bir resim ve metin veri kümesinde nasıl hassaslaştıracağınız açıklanmaktadır. Öğrenecekleriniz:

  • Quantized Low-Rank Adaptation (QLoRA) nedir?
  • Geliştirme ortamını kurma
  • Görsel görevler için hassas ayar veri kümesini oluşturun ve hazırlayın
  • TRL ve SFTTrainer'ı kullanarak Gemma'da ince ayar yapma
  • Model çıkarımını test edin ve resimler ile metinden ürün açıklamaları oluşturun.

Quantized Low-Rank Adaptation (QLoRA) nedir?

Bu kılavuzda, yüksek performansı korurken hesaplama kaynağı gereksinimlerini azalttığı için LLM'leri verimli bir şekilde hassas ayarlamak için popüler bir yöntem olarak ortaya çıkan Kantitatif Düşük Sıralı Uyarlama (QLoRA)'nın kullanımı gösterilmektedir. QloRA'da, önceden eğitilmiş model 4 bit olarak kesirli hale getirilir ve ağırlıklar dondurulur. Ardından, eğitilebilir adaptör katmanları (LoRA) eklenir ve yalnızca adaptör katmanları eğitilir. Daha sonra, adaptör ağırlıkları temel modelle birleştirilebilir veya ayrı bir adaptör olarak tutulabilir.

Geliştirme ortamını kurma

İlk adım, açık modelde ince ayar yapmak için TRL dahil Hugging Face kitaplıklarını ve veri kümelerini yüklemektir.

# Install Pytorch & other libraries
%pip install "torch>=2.4.0" tensorboard torchvision

# Install Gemma release branch from Hugging Face
%pip install "transformers>=4.51.3"

# Install Hugging Face libraries
%pip install  --upgrade \
  "datasets==3.3.2" \
  "accelerate==1.4.0" \
  "evaluate==0.4.3" \
  "bitsandbytes==0.45.3" \
  "trl==0.15.2" \
  "peft==0.14.0" \
  "pillow==11.1.0" \
  protobuf \
  sentencepiece

Eğitime başlamadan önce Gemma'nın kullanım şartlarını kabul ettiğinizden emin olmanız gerekir. Hugging Face'teki lisansı kabul etmek için http://huggingface.co/google/gemma-3-4b-pt adresindeki model sayfasındaki Kabul et ve depoya eriş düğmesini (veya kullandığınız görme yeteneğine sahip Gemma modeli için uygun model sayfasını) tıklayın.

Lisansı kabul ettikten sonra modele erişmek için geçerli bir Hugging Face jetonuna ihtiyacınız vardır. Google Colab'da çalışıyorsanız Colab gizli bilgilerini kullanarak Hugging Face jetonunuzu güvenli bir şekilde kullanabilirsiniz. Aksi takdirde, jetonu doğrudan login yönteminde ayarlayabilirsiniz. Eğitim sırasında modelinizi Hub'a gönderirken jetonunuzun yazma erişimine sahip olduğundan emin olun.

from google.colab import userdata
from huggingface_hub import login

# Login into Hugging Face Hub
hf_token = userdata.get('HF_TOKEN') # If you are running inside a Google Colab
login(hf_token)

İnce ayar veri kümesini oluşturun ve hazırlayın

LLM'leri hassaslaştırırken kullanım alanınızı ve çözmek istediğiniz görevi bilmeniz önemlidir. Bu sayede, modelinizde ince ayar yapmak için bir veri kümesi oluşturabilirsiniz. Henüz kullanım alanınızı tanımlamadıysanız sıfırdan başlamanız gerekebilir.

Bu rehberde örnek olarak aşağıdaki kullanım alanı ele alınmıştır:

  • Bir Gemma modelinde hassas ayar yaparak bir e-ticaret platformu için kısa ve SEO'ya optimize edilmiş ürün açıklamaları oluşturma (özellikle mobil aramaya göre uyarlanmış).

Bu kılavuzda, ürün resimleri ve kategorileri dahil olmak üzere Amazon ürün açıklamalarından oluşan bir veri kümesi olan philschmid/amazon-product-descriptions-vlm veri kümesi kullanılmaktadır.

Hugging Face TRL, çoklu biçimli sohbetleri destekler. Önemli olan, işleme sınıfına resmi yüklemesi gerektiğini söyleyen "image" rolüdür. Yapı şu şekilde olmalıdır:

{"messages": [{"role": "system", "content": [{"type": "text", "text":"You are..."}]}, {"role": "user", "content": [{"type": "text", "text": "..."}, {"type": "image"}]}, {"role": "assistant", "content": [{"type": "text", "text": "..."}]}]}
{"messages": [{"role": "system", "content": [{"type": "text", "text":"You are..."}]}, {"role": "user", "content": [{"type": "text", "text": "..."}, {"type": "image"}]}, {"role": "assistant", "content": [{"type": "text", "text": "..."}]}]}
{"messages": [{"role": "system", "content": [{"type": "text", "text":"You are..."}]}, {"role": "user", "content": [{"type": "text", "text": "..."}, {"type": "image"}]}, {"role": "assistant", "content": [{"type": "text", "text": "..."}]}]}

Artık veri kümesini yüklemek ve resmi, ürün adını ve kategoriyi birleştirecek bir istem şablonu oluşturmak ve sistem mesajı eklemek için Hugging Face Datasets kitaplığını kullanabilirsiniz. Veri kümesi, resimleri Pil.Image nesneleri olarak içerir.

from datasets import load_dataset
from PIL import Image

# System message for the assistant
system_message = "You are an expert product description writer for Amazon."

# User prompt that combines the user query and the schema
user_prompt = """Create a Short Product description based on the provided <PRODUCT> and <CATEGORY> and image.
Only return description. The description should be SEO optimized and for a better mobile search experience.

<PRODUCT>
{product}
</PRODUCT>

<CATEGORY>
{category}
</CATEGORY>
"""

# Convert dataset to OAI messages
def format_data(sample):
    return {
        "messages": [
            {
                "role": "system",
                "content": [{"type": "text", "text": system_message}],
            },
            {
                "role": "user",
                "content": [
                    {
                        "type": "text",
                        "text": user_prompt.format(
                            product=sample["Product Name"],
                            category=sample["Category"],
                        ),
                    },
                    {
                        "type": "image",
                        "image": sample["image"],
                    },
                ],
            },
            {
                "role": "assistant",
                "content": [{"type": "text", "text": sample["description"]}],
            },
        ],
    }

def process_vision_info(messages: list[dict]) -> list[Image.Image]:
    image_inputs = []
    # Iterate through each conversation
    for msg in messages:
        # Get content (ensure it's a list)
        content = msg.get("content", [])
        if not isinstance(content, list):
            content = [content]

        # Check each content element for images
        for element in content:
            if isinstance(element, dict) and (
                "image" in element or element.get("type") == "image"
            ):
                # Get the image and convert to RGB
                if "image" in element:
                    image = element["image"]
                else:
                    image = element
                image_inputs.append(image.convert("RGB"))
    return image_inputs

# Load dataset from the hub
dataset = load_dataset("philschmid/amazon-product-descriptions-vlm", split="train")

# Convert dataset to OAI messages
# need to use list comprehension to keep Pil.Image type, .mape convert image to bytes
dataset = [format_data(sample) for sample in dataset]

print(dataset[345]["messages"])

TRL ve SFTTrainer'ı kullanarak Gemma'da ince ayar yapma

Artık modelinizde ince ayar yapmaya hazırsınız. Hugging Face TRL SFTTrainer, açık LLM'lerde ince ayar yapmayı kolaylaştırır. SFTTrainer, transformers kitaplığındaki Trainer sınıfının alt sınıfıdır ve günlük kaydı, değerlendirme ve kontrol noktası oluşturma gibi tüm özellikleri destekler ancak aşağıdakiler gibi ek kullanım kolaylığı özellikleri ekler:

  • Sohbet ve talimat biçimleri dahil veri kümesi biçimlendirme
  • Yalnızca tamamlamalarla ilgili eğitim (istemler yoksayılır)
  • Daha verimli eğitim için veri kümelerini paketleme
  • QloRA dahil olmak üzere parametreleri verimli şekilde kullanma (PEFT) desteği
  • Modeli ve parçalayıcıyı sohbet ince ayarı için hazırlama (ör. özel jeton ekleme)

Aşağıdaki kod, Hugging Face'tan Gemma modelini ve tokenizörü yükler ve kesme işlemi yapılandırmasını başlatır.

import torch
from transformers import AutoProcessor, AutoModelForImageTextToText, BitsAndBytesConfig

# Hugging Face model id
model_id = "google/gemma-3-4b-pt" # or `google/gemma-3-12b-pt`, `google/gemma-3-27-pt`

# Check if GPU benefits from bfloat16
if torch.cuda.get_device_capability()[0] < 8:
    raise ValueError("GPU does not support bfloat16, please use a GPU that supports bfloat16.")

# Define model init arguments
model_kwargs = dict(
    attn_implementation="eager", # Use "flash_attention_2" when running on Ampere or newer GPU
    torch_dtype=torch.bfloat16, # What torch dtype to use, defaults to auto
    device_map="auto", # Let torch decide how to load the model
)

# BitsAndBytesConfig int-4 config
model_kwargs["quantization_config"] = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_use_double_quant=True,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_compute_dtype=model_kwargs["torch_dtype"],
    bnb_4bit_quant_storage=model_kwargs["torch_dtype"],
)

# Load model and tokenizer
model = AutoModelForImageTextToText.from_pretrained(model_id, **model_kwargs)
processor = AutoProcessor.from_pretrained("google/gemma-3-4b-it")

SFTTrainer, peft ile yerleşik entegrasyonu destekler. Bu sayede, QLoRA'yı kullanarak LLM'leri verimli bir şekilde ayarlamak kolaydır. Bunun için tek yapmanız gereken bir LoraConfig oluşturmak ve bunu eğitmene sağlamaktır.

from peft import LoraConfig

peft_config = LoraConfig(
    lora_alpha=16,
    lora_dropout=0.05,
    r=16,
    bias="none",
    target_modules="all-linear",
    task_type="CAUSAL_LM",
    modules_to_save=[
        "lm_head",
        "embed_tokens",
    ],
)

Eğitiminize başlamadan önce, SFTConfig içinde kullanmak istediğiniz hiper parametreyi ve görüntü işlemeyi yönetmek için özel bir collate_fn tanımlamanız gerekir. collate_fn, metin ve resim içeren iletileri modelin anlayabileceği bir biçime dönüştürür.

from trl import SFTConfig

args = SFTConfig(
    output_dir="gemma-product-description",     # directory to save and repository id
    num_train_epochs=1,                         # number of training epochs
    per_device_train_batch_size=1,              # batch size per device during training
    gradient_accumulation_steps=4,              # number of steps before performing a backward/update pass
    gradient_checkpointing=True,                # use gradient checkpointing to save memory
    optim="adamw_torch_fused",                  # use fused adamw optimizer
    logging_steps=5,                            # log every 5 steps
    save_strategy="epoch",                      # save checkpoint every epoch
    learning_rate=2e-4,                         # learning rate, based on QLoRA paper
    bf16=True,                                  # use bfloat16 precision
    max_grad_norm=0.3,                          # max gradient norm based on QLoRA paper
    warmup_ratio=0.03,                          # warmup ratio based on QLoRA paper
    lr_scheduler_type="constant",               # use constant learning rate scheduler
    push_to_hub=True,                           # push model to hub
    report_to="tensorboard",                    # report metrics to tensorboard
    gradient_checkpointing_kwargs={
        "use_reentrant": False
    },  # use reentrant checkpointing
    dataset_text_field="",                      # need a dummy field for collator
    dataset_kwargs={"skip_prepare_dataset": True},  # important for collator
)
args.remove_unused_columns = False # important for collator

# Create a data collator to encode text and image pairs
def collate_fn(examples):
    texts = []
    images = []
    for example in examples:
        image_inputs = process_vision_info(example["messages"])
        text = processor.apply_chat_template(
            example["messages"], add_generation_prompt=False, tokenize=False
        )
        texts.append(text.strip())
        images.append(image_inputs)

    # Tokenize the texts and process the images
    batch = processor(text=texts, images=images, return_tensors="pt", padding=True)

    # The labels are the input_ids, and we mask the padding tokens and image tokens in the loss computation
    labels = batch["input_ids"].clone()

    # Mask image tokens
    image_token_id = [
        processor.tokenizer.convert_tokens_to_ids(
            processor.tokenizer.special_tokens_map["boi_token"]
        )
    ]
    # Mask tokens for not being used in the loss computation
    labels[labels == processor.tokenizer.pad_token_id] = -100
    labels[labels == image_token_id] = -100
    labels[labels == 262144] = -100

    batch["labels"] = labels
    return batch

Artık modelinizin eğitimini başlatmak için SFTTrainer'inizi oluşturmak üzere ihtiyacınız olan tüm yapı taşlarına sahipsiniz.

from trl import SFTTrainer

trainer = SFTTrainer(
    model=model,
    args=args,
    train_dataset=dataset,
    peft_config=peft_config,
    processing_class=processor,
    data_collator=collate_fn,
)

train() yöntemini çağırarak eğitimi başlatın.

# Start training, the model will be automatically saved to the Hub and the output directory
trainer.train()

# Save the final model again to the Hugging Face Hub
trainer.save_model()

Modelinizi test etmeden önce belleği boşalttığınızdan emin olun.

# free the memory again
del model
del trainer
torch.cuda.empty_cache()

QLoRA'yı kullanırken modelin tamamını değil, yalnızca bağdaştırıcılar eğitilir. Bu, eğitim sırasında modeli kaydederken modelin tamamını değil, yalnızca adaptör ağırlıklarını kaydettiğiniz anlamına gelir. Modelin tamamını kaydetmek istiyorsanız (bu, vLLM veya TGI gibi yayınlama yığınlarıyla kullanımını kolaylaştırır) merge_and_unload yöntemini kullanarak bağdaştırıcıların ağırlıklarını model ağırlıklarıyla birleştirebilir ve ardından modeli save_pretrained yöntemiyle kaydedebilirsiniz. Bu işlem, çıkarım için kullanılabilecek bir varsayılan model kaydeder.

from peft import PeftModel

# Load Model base model
model = AutoModelForImageTextToText.from_pretrained(model_id, low_cpu_mem_usage=True)

# Merge LoRA and base model and save
peft_model = PeftModel.from_pretrained(model, args.output_dir)
merged_model = peft_model.merge_and_unload()
merged_model.save_pretrained("merged_model", safe_serialization=True, max_shard_size="2GB")

processor = AutoProcessor.from_pretrained(args.output_dir)
processor.save_pretrained("merged_model")

Model çıkarımlarını test etme ve ürün açıklamaları oluşturma

Eğitim tamamlandıktan sonra modelinizi değerlendirmek ve test etmek istersiniz. Test veri kümesinden farklı örnekler yükleyebilir ve modeli bu örnekler üzerinde değerlendirebilirsiniz.

import torch

# Load Model with PEFT adapter
model = AutoModelForImageTextToText.from_pretrained(
  args.output_dir,
  device_map="auto",
  torch_dtype=torch.bfloat16,
  attn_implementation="eager",
)
processor = AutoProcessor.from_pretrained(args.output_dir)

Ürün adı, kategori ve resim sağlayarak çıkarım yapma özelliğini test edebilirsiniz. sample, bir Marvel oyuncak figürü içeriyor.

import requests
from PIL import Image

# Test sample with Product Name, Category and Image
sample = {
  "product_name": "Hasbro Marvel Avengers-Serie Marvel Assemble Titan-Held, Iron Man, 30,5 cm Actionfigur",
  "category": "Toys & Games | Toy Figures & Playsets | Action Figures",
  "image": Image.open(requests.get("https://m.media-amazon.com/images/I/81+7Up7IWyL._AC_SY300_SX300_.jpg", stream=True).raw).convert("RGB")
}

def generate_description(sample, model, processor):
    # Convert sample into messages and then apply the chat template
    messages = [
        {"role": "system", "content": [{"type": "text", "text": system_message}]},
        {"role": "user", "content": [
            {"type": "image","image": sample["image"]},
            {"type": "text", "text": user_prompt.format(product=sample["product_name"], category=sample["category"])},
        ]},
    ]
    text = processor.apply_chat_template(
        messages, tokenize=False, add_generation_prompt=True
    )
    # Process the image and text
    image_inputs = process_vision_info(messages)
    # Tokenize the text and process the images
    inputs = processor(
        text=[text],
        images=image_inputs,
        padding=True,
        return_tensors="pt",
    )
    # Move the inputs to the device
    inputs = inputs.to(model.device)

    # Generate the output
    stop_token_ids = [processor.tokenizer.eos_token_id, processor.tokenizer.convert_tokens_to_ids("<end_of_turn>")]
    generated_ids = model.generate(**inputs, max_new_tokens=256, top_p=1.0, do_sample=True, temperature=0.8, eos_token_id=stop_token_ids, disable_compile=True)
    # Trim the generation and decode the output to text
    generated_ids_trimmed = [out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
    output_text = processor.batch_decode(
        generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
    )
    return output_text[0]

# generate the description
description = generate_description(sample, model, processor)
print(description)

Özet ve sonraki adımlar

Bu eğitimde, TRL ve QLoRA'yı kullanarak Gemma modelinde özellikle ürün açıklamaları oluşturmak için görüntü görevlerine yönelik ince ayar yapma hakkında bilgi verilmiştir. Ardından aşağıdaki dokümanlara göz atın: