Hugging Face Transformers और QLoRA का इस्तेमाल करके, विज़न टास्क के लिए Gemma को बेहतर बनाना

इस गाइड में, Hugging Face Transformers और TRL का इस्तेमाल करके, किसी कस्टम इमेज और टेक्स्ट डेटासेट पर Gemma को बेहतर बनाने का तरीका बताया गया है. ऐसा, विज़न टास्क (प्रॉडक्ट की जानकारी जनरेट करना) के लिए किया जाता है. आपको इनके बारे में जानकारी मिलेगी:

  • क्वांटाइज़्ड लो-रैंक अडैप्टेशन (QLoRA) क्या है
  • डेवलपमेंट एनवायरमेंट सेट अप करना
  • विज़न टास्क के लिए, फ़ाइन-ट्यूनिंग डेटासेट बनाना और तैयार करना
  • टीआरएल और SFTTrainer का इस्तेमाल करके, Gemma को बेहतर बनाना
  • मॉडल के अनुमान की जांच करें और इमेज और टेक्स्ट से प्रॉडक्ट की जानकारी जनरेट करें.

क्वांटाइज़्ड लो-रैंक अडैप्टेशन (QLoRA) क्या है

इस गाइड में, क्विंटाइज़्ड लो-रैंक अडैप्टेशन (QLoRA) का इस्तेमाल दिखाया गया है. यह एलएलएम को बेहतर तरीके से फ़ाइन-ट्यून करने का एक लोकप्रिय तरीका है. इसकी मदद से, बेहतर परफ़ॉर्मेंस बनाए रखते हुए, कंप्यूटिंग रिसॉर्स की ज़रूरत कम हो जाती है. QloRA में, पहले से ट्रेन किए गए मॉडल को 4-बिट में क्वांटाइज़ किया जाता है और वेट को फ़्रीज़ कर दिया जाता है. इसके बाद, ट्रेन की जा सकने वाली अडैप्टर लेयर (LoRA) जोड़ी जाती हैं और सिर्फ़ अडैप्टर लेयर को ट्रेन किया जाता है. इसके बाद, अडैप्टर के वेट को बेस मॉडल के साथ मर्ज किया जा सकता है या अलग अडैप्टर के तौर पर रखा जा सकता है.

डेवलपमेंट एनवायरमेंट सेट अप करना

सबसे पहले, ओपन मॉडल को बेहतर बनाने के लिए, TRL और डेटासेट के साथ-साथ Hugging Face लाइब्रेरी इंस्टॉल करें.

# 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 के इस्तेमाल की शर्तें स्वीकार कर ली हैं. Hugging Face पर लाइसेंस स्वीकार करने के लिए, मॉडल पेज पर मौजूद 'सहमति दें और रिपॉज़िटरी ऐक्सेस करें' बटन पर क्लिक करें. यह बटन, http://huggingface.co/google/gemma-3-4b-pt (या इस्तेमाल किए जा रहे विज़न की सुविधा वाले Gemma मॉडल के लिए सही मॉडल पेज) पर मौजूद है.

लाइसेंस स्वीकार करने के बाद, मॉडल को ऐक्सेस करने के लिए आपके पास मान्य Hugging Face टोकन होना चाहिए. अगर Google Colab में प्रोग्राम चलाया जा रहा है, तो Colab के पासवर्ड का इस्तेमाल करके, Hugging Face टोकन को सुरक्षित तरीके से इस्तेमाल किया जा सकता है. इसके अलावा, login तरीके में सीधे तौर पर टोकन सेट किया जा सकता है. पक्का करें कि आपके पास अपने टोकन में लिखने का ऐक्सेस भी हो, क्योंकि ट्रेनिंग के दौरान मॉडल को Hub में भेजा जाता है.

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)

फ़ाइन-ट्यूनिंग डेटासेट बनाना और उसे तैयार करना

एलएलएम को बेहतर बनाने के लिए, यह जानना ज़रूरी है कि आपको इसका इस्तेमाल किस काम के लिए करना है और आपको किस टास्क को हल करना है. इससे, अपने मॉडल को बेहतर बनाने के लिए डेटासेट बनाने में मदद मिलती है. अगर आपने अब तक इस्तेमाल के उदाहरण की जानकारी नहीं दी है, तो आपको फिर से शुरुआत करनी पड़ सकती है.

उदाहरण के लिए, इस गाइड में इस्तेमाल के इस उदाहरण पर फ़ोकस किया गया है:

  • किसी ई-कॉमर्स प्लैटफ़ॉर्म के लिए, कम शब्दों में और एसईओ के हिसाब से ऑप्टिमाइज़ किए गए प्रॉडक्ट के ब्यौरे जनरेट करने के लिए, Gemma मॉडल को बेहतर बनाना. खास तौर पर, मोबाइल पर खोज के लिए.

इस गाइड में philschmid/amazon-product-descriptions-vlm डेटासेट का इस्तेमाल किया गया है. यह Amazon पर मौजूद प्रॉडक्ट की जानकारी का डेटासेट है. इसमें प्रॉडक्ट की इमेज और कैटगरी भी शामिल हैं.

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 डेटासेट लाइब्रेरी का इस्तेमाल किया जा सकता है. साथ ही, इमेज, प्रॉडक्ट का नाम, और कैटगरी को जोड़ने के लिए प्रॉम्प्ट टेंप्लेट बनाया जा सकता है. इसके अलावा, सिस्टम मैसेज भी जोड़ा जा सकता है. डेटासेट में, इमेज को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"])

टीआरएल और SFTTrainer का इस्तेमाल करके, Gemma को बेहतर बनाना

अब आपके पास अपने मॉडल को बेहतर बनाने का विकल्प है. Hugging Face TRL SFTTrainer की मदद से, ओपन एलएलएम को बेहतर बनाने की प्रोसेस को आसानी से मॉनिटर किया जा सकता है. SFTTrainer, transformers लाइब्रेरी के Trainer का सबक्लास है. इसमें लॉगिंग, आकलन, और चेकपॉइंट जैसी सभी सुविधाएं काम करती हैं. साथ ही, इसमें कुछ और सुविधाएं भी शामिल हैं, जैसे:

  • डेटासेट को फ़ॉर्मैट करना. इसमें बातचीत और निर्देश के फ़ॉर्मैट भी शामिल हैं
  • सिर्फ़ पूरा होने पर ट्रेनिंग, प्रॉम्प्ट को अनदेखा करना
  • ज़्यादा असरदार ट्रेनिंग के लिए डेटासेट पैक करना
  • पैरामीटर-बेहतर बनाने की सुविधा (PEFT), जिसमें QloRA भी शामिल है
  • बातचीत को बेहतर बनाने के लिए, मॉडल और टोकनेटर को तैयार करना. जैसे, खास टोकन जोड़ना

यह कोड, Hugging Face से Gemma मॉडल और टोकनेटर को लोड करता है. साथ ही, क्वांटाइज़ेशन कॉन्फ़िगरेशन को शुरू करता है.

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 के साथ पहले से इंटिग्रेशन की सुविधा मौजूद होती है. इसकी मदद से, 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)

खास जानकारी और अगले चरण

इस ट्यूटोरियल में, TRL और QLoRA का इस्तेमाल करके, विज़न टास्क के लिए Gemma मॉडल को बेहतर बनाने का तरीका बताया गया है. खास तौर पर, प्रॉडक्ट के ब्यौरे जनरेट करने के लिए. इसके बाद, यहां दिए गए दस्तावेज़ देखें: