Gemma را برای کارهای Vision با استفاده از ترانسفورماتورهای Hugging Face و QLoRA تنظیم کنید

این راهنما شما را با نحوه تنظیم دقیق Gemma روی مجموعه داده های تصویر و متن سفارشی برای یک کار بینایی (ایجاد توضیحات محصول) با استفاده از Transformers Hugging Face و TRL آشنا می کند. یاد خواهید گرفت:

  • سازگاری با رتبه پایین کوانتیزه (QLoRA) چیست؟
  • راه اندازی محیط توسعه
  • مجموعه داده تنظیم دقیق را برای وظایف بینایی ایجاد و آماده کنید
  • Gemma را با استفاده از TRL و SFTTrainer تنظیم کنید
  • استنتاج مدل را تست کنید و توضیحات محصول را از روی تصاویر و متن تولید کنید.

سازگاری با رتبه پایین کوانتیزه (QLoRA) چیست؟

این راهنما استفاده از انطباق با رتبه پایین کوانتیزه شده (QLoRA) را نشان می‌دهد که به عنوان یک روش محبوب برای تنظیم دقیق LLMها ظاهر شد زیرا نیاز به منابع محاسباتی را کاهش می‌دهد و در عین حال عملکرد بالا را حفظ می‌کند. در QloRA، مدل از پیش آموزش دیده به 4 بیت کوانتیزه می شود و وزن ها منجمد می شوند. سپس لایه های آداپتور قابل آموزش (LoRA) متصل می شوند و فقط لایه های آداپتور آموزش داده می شوند. پس از آن، وزن آداپتور را می توان با مدل پایه ادغام کرد یا به عنوان یک آداپتور جداگانه نگهداری کرد.

راه اندازی محیط توسعه

اولین قدم، نصب کتابخانه‌های Hugging Face، از جمله TRL، و مجموعه داده‌ها برای تنظیم دقیق مدل باز است.

# 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

قبل از شروع آموزش، باید مطمئن شوید که شرایط استفاده از Gemma را پذیرفته اید. می‌توانید با کلیک بر روی دکمه Agree and Access Repository در صفحه مدل در آدرس: http://huggingface.co/google/gemma-3-4b-pt، مجوز را در Hugging Face (یا صفحه مدل مناسب برای مدل Gemma با قابلیت دید که استفاده می‌کنید) بپذیرید.

بعد از اینکه مجوز را پذیرفتید، برای دسترسی به مدل به یک نشانه معتبر Hugging Face نیاز دارید. اگر در داخل یک Google Colab در حال اجرا هستید، می توانید با استفاده از Secrets Colab به طور ایمن از نشانه Hugging Face خود استفاده کنید. در غیر این صورت، می توانید توکن را مستقیماً در روش login تنظیم کنید. مطمئن شوید که توکن شما نیز دسترسی نوشتن دارد، زیرا در طول آموزش مدل خود را به هاب فشار می دهید.

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)

مجموعه داده تنظیم دقیق را ایجاد و آماده کنید

هنگام تنظیم دقیق LLM ها، دانستن موارد استفاده و وظیفه ای که می خواهید حل کنید بسیار مهم است. این به شما کمک می کند یک مجموعه داده برای تنظیم دقیق مدل خود ایجاد کنید. اگر هنوز مورد استفاده خود را تعریف نکرده اید، ممکن است بخواهید به صفحه طراحی برگردید.

به عنوان مثال، این راهنما بر موارد استفاده زیر تمرکز دارد:

  • تنظیم دقیق یک مدل Gemma برای ایجاد توضیحات محصول مختصر و بهینه شده با سئو برای یک پلتفرم تجارت الکترونیک، به طور خاص برای جستجوی تلفن همراه.

این راهنما از مجموعه داده philschmid/amazon-product-descriptions-vlm ، مجموعه داده ای از توضیحات محصول آمازون، از جمله تصاویر محصول و دسته ها استفاده می کند.

Hugging Face TRL از مکالمات چندوجهی پشتیبانی می کند. قطعه مهم نقش "تصویر" است که به کلاس پردازش می گوید که باید تصویر را بارگذاری کند. ساختار باید به شرح زیر باشد:

{"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": "..."}]}]}

اکنون می‌توانید از کتابخانه Hugging Face Datasets برای بارگیری مجموعه داده و ایجاد یک الگوی درخواستی برای ترکیب تصویر، نام محصول و دسته استفاده کنید و یک پیام سیستمی اضافه کنید. مجموعه داده شامل تصاویر به عنوان اشیاء Pil.Image است.

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"])

Gemma را با استفاده از TRL و SFTTrainer تنظیم کنید

اکنون آماده تنظیم دقیق مدل خود هستید. Hugging Face TRL SFTTrainer نظارت بر تنظیم دقیق LLM های باز را آسان می کند. SFTTrainer یک زیر کلاس از Trainer از کتابخانه transformers است و از همه ویژگی‌های یکسان، از جمله ورود به سیستم، ارزیابی، و چک پوینت پشتیبانی می‌کند، اما ویژگی‌های کیفیت زندگی اضافی را اضافه می‌کند، از جمله:

  • قالب‌بندی مجموعه داده، از جمله فرمت‌های مکالمه و دستورالعمل
  • آموزش فقط در مورد تکمیل، نادیده گرفتن دستورات
  • بسته بندی مجموعه داده ها برای آموزش کارآمدتر
  • پشتیبانی از تنظیم دقیق پارامترها (PEFT) از جمله QloRA
  • آماده سازی مدل و توکنایزر برای تنظیم دقیق مکالمه (مانند افزودن نشانه های خاص)

کد زیر مدل و توکنایزر Gemma را از Hugging Face بارگیری می کند و پیکربندی کوانتیزاسیون را اولیه می کند.

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 پشتیبانی می کند، که تنظیم کارآمد LLM ها را با استفاده از QLoRA آسان می کند. شما فقط باید یک LoraConfig ایجاد کنید و آن را در اختیار مربی قرار دهید.

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",
    ],
)

قبل از اینکه بتوانید آموزش خود را شروع کنید، باید هایپرپارامتری را که می خواهید در یک SFTConfig و یک collate_fn سفارشی برای مدیریت پردازش بینایی استفاده کنید، تعریف کنید. collate_fn پیام ها را با متن و تصاویر به قالبی تبدیل می کند که مدل بتواند آن را درک کند.

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

شما اکنون هر بلوک ساختمانی را که برای ایجاد SFTTrainer برای شروع آموزش مدل خود نیاز دارید، در اختیار دارید.

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() شروع کنید.

# 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()

قبل از اینکه بتوانید مدل خود را آزمایش کنید، مطمئن شوید که حافظه را آزاد کرده اید.

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

هنگام استفاده از QLoRA، فقط آداپتورها را آموزش می دهید و نه مدل کامل. این بدان معناست که هنگام ذخیره مدل در طول تمرین، فقط وزن آداپتور را ذخیره می کنید و نه مدل کامل را. اگر می‌خواهید مدل کامل را ذخیره کنید، که استفاده از آن را با پشته‌های سرویس مانند vLLM یا TGI آسان‌تر می‌کند، می‌توانید وزن‌های آداپتور را با استفاده از روش merge_and_unload در وزن‌های مدل ادغام کنید و سپس مدل را با روش save_pretrained ذخیره کنید. این یک مدل پیش فرض را ذخیره می کند که می تواند برای استنتاج استفاده شود.

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")

استنتاج مدل را آزمایش کنید و توضیحات محصول را تولید کنید

پس از پایان آموزش، می خواهید مدل خود را ارزیابی و آزمایش کنید. می‌توانید نمونه‌های مختلف را از مجموعه داده آزمایشی بارگیری کنید و مدل را روی آن نمونه‌ها ارزیابی کنید.

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)

شما می توانید استنباط را با ارائه نام محصول، دسته بندی و تصویر آزمایش کنید. sample شامل یک اکشن فیگور شگفت انگیز است.

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)

خلاصه و مراحل بعدی

این آموزش نحوه تنظیم دقیق یک مدل Gemma را برای وظایف بینایی با استفاده از TRL و QLoRA، به‌ویژه برای تولید توضیحات محصول، شرح می‌دهد. در ادامه اسناد زیر را بررسی کنید: