|
|
Google Colab में चलाएं
|
|
|
GitHub पर सोर्स देखें
|
इस गाइड में, Hugging Face Transformers और TRL का इस्तेमाल करके, विज़न टास्क (प्रॉडक्ट की जानकारी जनरेट करना) के लिए, कस्टम इमेज और टेक्स्ट डेटासेट पर Gemma को बेहतर बनाने का तरीका बताया गया है. आपको इनके बारे में जानकारी मिलेगी:
- क्वांटाइज़्ड लो-रैंक अडैप्टेशन (QLoRA) क्या है
- डेवलपमेंट एनवायरमेंट सेट अप करना
- फ़ाइन-ट्यूनिंग के लिए डेटासेट बनाना और उसे तैयार करना
- TRL और SFTTrainer का इस्तेमाल करके, Gemma को और बेहतर तरीके से ट्रेन करना
- मॉडल इन्फ़रेंस की जांच करें. साथ ही, इमेज और टेक्स्ट से प्रॉडक्ट की जानकारी जनरेट करें.
क्वांटाइज़्ड लो-रैंक अडैप्टेशन (QLoRA) क्या है
इस गाइड में, क्वांटाइज़्ड लो-रैंक अडैप्टेशन (क्यूएलओआरए) के इस्तेमाल के बारे में बताया गया है. यह एलएलएम को बेहतर बनाने का एक लोकप्रिय तरीका है. इससे कंप्यूटेशनल रिसॉर्स की ज़रूरत कम हो जाती है और परफ़ॉर्मेंस भी अच्छी बनी रहती है. QloRA में, प्रीट्रेन किए गए मॉडल को 4-बिट में क्वांटाइज़ किया जाता है और वज़न को फ़्रीज़ किया जाता है. इसके बाद, ट्रेन की जा सकने वाली अडैप्टर लेयर (LoRA) अटैच की जाती हैं और सिर्फ़ अडैप्टर लेयर को ट्रेन किया जाता है. इसके बाद, अडैप्टर के वेट को बेस मॉडल के साथ मर्ज किया जा सकता है या इसे अलग अडैप्टर के तौर पर रखा जा सकता है.
डेवलपमेंट एनवायरमेंट सेट अप करना
सबसे पहले, Hugging Face Libraries इंस्टॉल करें. इनमें TRL और डेटासेट शामिल हैं, ताकि ओपन मॉडल को बेहतर बनाया जा सके.
# Install Pytorch & other libraries
%pip install torch tensorboard torchvision
# Install Transformers
%pip install transformers
# Install Hugging Face libraries
%pip install datasets accelerate evaluate bitsandbytes trl peft protobuf pillow sentencepiece
# COMMENT IN: if you are running on a GPU that supports BF16 data type and flash attn, such as NVIDIA L4 or NVIDIA A100
#%pip install flash-attn
ध्यान दें: अगर Ampere आर्किटेक्चर (जैसे कि NVIDIA L4) या इसके नए वर्शन वाले जीपीयू का इस्तेमाल किया जा रहा है, तो फ़्लैश अटेंशन का इस्तेमाल किया जा सकता है. फ़्लैश अटेंशन एक ऐसा तरीका है जिससे कंप्यूटेशन की स्पीड काफ़ी बढ़ जाती है. साथ ही, यह मेमोरी के इस्तेमाल को सीक्वेंस की लंबाई में क्वाड्रेटिक से लीनियर तक कम कर देता है. इससे ट्रेनिंग की स्पीड तीन गुना तक बढ़ जाती है. ज़्यादा जानने के लिए, FlashAttention पर जाएं.
अपने मॉडल को पब्लिश करने के लिए, आपके पास Hugging Face का मान्य टोकन होना चाहिए. अगर Google Colab का इस्तेमाल किया जा रहा है, तो Colab के सीक्रेट का इस्तेमाल करके, Hugging Face टोकन को सुरक्षित तरीके से इस्तेमाल किया जा सकता है. इसके अलावा, टोकन को सीधे तौर पर login तरीके में सेट किया जा सकता है. पक्का करें कि आपके टोकन के पास लिखने का ऐक्सेस भी हो, क्योंकि ट्रेनिंग के दौरान आपको अपने मॉडल को Hub पर पुश करना होगा.
# Login into Hugging Face Hub
from huggingface_hub import login
login()
फ़ाइन-ट्यूनिंग के लिए डेटासेट बनाना और उसे तैयार करना
एलएलएम को फ़ाइन-ट्यून करते समय, यह जानना ज़रूरी है कि आपको इसका इस्तेमाल किस काम के लिए करना है और आपको कौनसी समस्या हल करनी है. इससे आपको अपने मॉडल को बेहतर बनाने के लिए डेटासेट बनाने में मदद मिलती है. अगर आपने अब तक इस्तेमाल का उदाहरण तय नहीं किया है, तो आपको फिर से शुरुआत करनी पड़ सकती है.
उदाहरण के तौर पर, यह गाइड इस्तेमाल के इस उदाहरण पर फ़ोकस करती है:
- किसी ई-कॉमर्स प्लैटफ़ॉर्म के लिए, कम शब्दों में एसईओ के हिसाब से ऑप्टिमाइज़ किए गए प्रॉडक्ट के ब्यौरे जनरेट करने के लिए, Gemma मॉडल को फ़ाइन-ट्यून करना. यह खास तौर पर मोबाइल पर की जाने वाली खोज के लिए तैयार किया गया है.
इस गाइड में, philschmid/amazon-product-descriptions-vlm डेटासेट का इस्तेमाल किया गया है. यह Amazon पर मौजूद प्रॉडक्ट की जानकारी का डेटासेट है. इसमें प्रॉडक्ट की इमेज और कैटगरी भी शामिल हैं.
Hugging Face TRL, मल्टीमॉडल बातचीत की सुविधा के साथ काम करता है. इसमें सबसे अहम भूमिका "image" की होती है. इससे प्रोसेसिंग क्लास को पता चलता है कि उसे इमेज लोड करनी है. स्ट्रक्चर इस तरह होना चाहिए:
{"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}],
"content": 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")
dataset = dataset.train_test_split(test_size=0.1)
# Convert dataset to OAI messages
# need to use list comprehension to keep Pil.Image type, .mape convert image to bytes
dataset_train = [format_data(sample) for sample in dataset["train"]]
dataset_test = [format_data(sample) for sample in dataset["test"]]
print(dataset_train[345]["messages"])
README.md: 0.00B [00:00, ?B/s]
data/train-00000-of-00001.parquet: 0%| | 0.00/47.6M [00:00<?, ?B/s]
Generating train split: 0%| | 0/1345 [00:00<?, ? examples/s]
[{'role': 'system', 'content': 'You are an expert product description writer for Amazon.'}, {'role': 'user', 'content': [{'type': 'text', 'text': "Create a Short Product description based on the provided <PRODUCT> and <CATEGORY> and image.\nOnly return description. The description should be SEO optimized and for a better mobile search experience.\n\n<PRODUCT>\nRazor Agitator BMX/Freestyle Bike, 20-Inch\n</PRODUCT>\n\n<CATEGORY>\nSports & Outdoors | Outdoor Recreation | Cycling | Kids' Bikes & Accessories | Kids' Bikes\n</CATEGORY>\n"}, {'type': 'image', 'image': <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=500x413 at 0x7B7250181790>}]}, {'role': 'assistant', 'content': [{'type': 'text', 'text': 'Conquer the streets with the Razor Agitator BMX Bike! This 20-inch freestyle bike is built for young riders ready to take on any challenge. Durable frame, responsive handling – perfect for tricks and cruising. Get yours today!'}]}]
TRL और SFTTrainer का इस्तेमाल करके, Gemma को और बेहतर तरीके से ट्रेन करना
अब आपके पास अपने मॉडल को बेहतर बनाने का विकल्प है. Hugging Face TRL SFTTrainer की मदद से, ओपन एलएलएम को आसानी से फ़ाइन-ट्यून किया जा सकता है. SFTTrainer, transformers लाइब्रेरी के Trainer की सबक्लास है. इसमें लॉगिंग, आकलन, और चेकपॉइंटिंग जैसी सभी सुविधाएं काम करती हैं. हालांकि, इसमें कुछ और सुविधाएं भी जोड़ी गई हैं, जैसे:
- डेटासेट फ़ॉर्मैट करना. इसमें बातचीत और निर्देश वाले फ़ॉर्मैट शामिल हैं
- सिर्फ़ जवाब पूरे करने की ट्रेनिंग दी गई है, प्रॉम्प्ट को अनदेखा किया गया है
- बेहतर ट्रेनिंग के लिए डेटासेट को पैक करना
- पैरामीटर-इफ़िशिएंट फ़ाइन-ट्यूनिंग (पीईएफ़टी) की सुविधा, जिसमें QloRA भी शामिल है
- बातचीत के हिसाब से फ़ाइन-ट्यून करने के लिए, मॉडल और टोकनाइज़र तैयार करना. जैसे, खास टोकन जोड़ना
यहां दिए गए कोड में, Hugging Face से Gemma मॉडल और टोकनाइज़र को लोड किया जाता है. साथ ही, क्वानटाइज़ेशन कॉन्फ़िगरेशन को शुरू किया जाता है.
import torch
from transformers import AutoProcessor, AutoModelForImageTextToText, BitsAndBytesConfig
# Hugging Face model id
model_id = "google/gemma-4-E2B" # @param ["google/gemma-4-E2B","google/gemma-4-E4B"] {"allow-input":true}
# 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(
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["dtype"],
bnb_4bit_quant_storage=model_kwargs["dtype"],
)
# Load model and tokenizer
model = AutoModelForImageTextToText.from_pretrained(model_id, **model_kwargs)
processor = AutoProcessor.from_pretrained("google/gemma-4-E2B-it") # Load the Instruction Tokenizer to use the official Gemma template
config.json: 0.00B [00:00, ?B/s] model.safetensors: 0%| | 0.00/10.2G [00:00<?, ?B/s] Loading weights: 0%| | 0/2011 [00:00<?, ?it/s] generation_config.json: 0%| | 0.00/149 [00:00<?, ?B/s] processor_config.json: 0.00B [00:00, ?B/s] chat_template.jinja: 0.00B [00:00, ?B/s] config.json: 0.00B [00:00, ?B/s] tokenizer_config.json: 0.00B [00:00, ?B/s] tokenizer.json: 0%| | 0.00/32.2M [00:00<?, ?B/s]
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"], # make sure to save the lm_head and embed_tokens as you train the special tokens
ensure_weight_tying=True,
)
ट्रेनिंग शुरू करने से पहले, आपको 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=3, # number of training epochs
per_device_train_batch_size=1, # batch size per device during training
optim="adamw_torch_fused", # use fused adamw optimizer
logging_steps=5, # log every 5 steps
save_strategy="epoch", # save checkpoint every epoch
eval_strategy="epoch", # evaluate 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
lr_scheduler_type="constant", # use constant learning rate scheduler
push_to_hub=True, # push model to hub
report_to="tensorboard", # report metrics to tensorboard
dataset_text_field="", # need a dummy field for collator
dataset_kwargs={"skip_prepare_dataset": True}, # important for collator
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 tokens for not being used in the loss computation
labels[labels == processor.tokenizer.pad_token_id] = -100
labels[labels == processor.tokenizer.boi_token_id] = -100
labels[labels == processor.tokenizer.image_token_id] = -100
labels[labels == processor.tokenizer.eoi_token_id] = -100
batch["labels"] = labels
return batch
अब आपके पास SFTTrainer बनाने के लिए, हर ज़रूरी कॉम्पोनेंट है. इससे मॉडल को ट्रेनिंग दी जा सकती है.
from trl import SFTTrainer
# Create Trainer object
trainer = SFTTrainer(
model=model,
args=args,
train_dataset=dataset_train,
eval_dataset=dataset_test,
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()
The tokenizer has new PAD/BOS/EOS tokens that differ from the model config and generation config. The model config and generation config were aligned accordingly, being updated with the tokenizer's values. Updated tokens: {'eos_token_id': 1, 'bos_token_id': 2, 'pad_token_id': 0}.
अपने मॉडल की जांच करने से पहले, पक्का करें कि आपने मेमोरी खाली कर दी हो.
# free the memory again
del model
del trainer
torch.cuda.empty_cache()
QLoRA का इस्तेमाल करते समय, सिर्फ़ अडैप्टर को ट्रेन किया जाता है, न कि पूरे मॉडल को. इसका मतलब है कि ट्रेनिंग के दौरान मॉडल को सेव करते समय, सिर्फ़ अडैप्टर के वेट सेव किए जाते हैं, न कि पूरा मॉडल. अगर आपको पूरे मॉडल को सेव करना है, तो merge_and_unload तरीके का इस्तेमाल करके, अडैप्टर के वेट को मॉडल के वेट में मर्ज करें. इससे vLLM या TGI जैसे सर्विंग स्टैक के साथ मॉडल का इस्तेमाल करना आसान हो जाता है. इसके बाद, 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")
Loading weights: 0%| | 0/2011 [00:00<?, ?it/s] Writing model shards: 0%| | 0/5 [00:00<?, ?it/s] ['merged_model/processor_config.json']
मॉडल इन्फ़रेंस की जांच करना और प्रॉडक्ट के ब्यौरे जनरेट करना
ट्रेनिंग पूरी होने के बाद, आपको अपने मॉडल का आकलन और उसकी जांच करनी होगी. टेस्ट डेटासेट से अलग-अलग सैंपल लोड किए जा सकते हैं. साथ ही, उन सैंपल के आधार पर मॉडल का आकलन किया जा सकता है.
model_id = "merged_model"
# Load Model with PEFT adapter
model = AutoModelForImageTextToText.from_pretrained(
model_id,
device_map="auto",
dtype="auto",
)
processor = AutoProcessor.from_pretrained(model_id)
Loading weights: 0%| | 0/2012 [00:00<?, ?it/s] The tied weights mapping and config for this model specifies to tie model.language_model.embed_tokens.weight to lm_head.weight, but both are present in the checkpoints with different values, so we will NOT tie them. You should update the config with `tie_word_embeddings=False` to silence this warning.
प्रॉडक्ट का नाम, कैटगरी, और इमेज देकर, अनुमान लगाने की सुविधा को आज़माया जा सकता है. 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": 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
)
print(text)
# 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("<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("MODEL OUTPUT>> \n")
print(description)
<bos><|turn>system You are an expert product description writer for Amazon.<turn|> <|turn>user <|image|> 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> Hasbro Marvel Avengers-Serie Marvel Assemble Titan-Held, Iron Man, 30,5 cm Actionfigur </PRODUCT> <CATEGORY> Toys & Games | Toy Figures & Playsets | Action Figures </CATEGORY><turn|> <|turn>model MODEL OUTPUT>> Enhance your collection with the Marvel Avengers - Avengers Assemble Ultron-Comforter Set! This soft and cuddly blanket and pillowcase feature everyone's favorite Avengers, Iron Man, and his loyal companion War Machine. Officially licensed by Marvel. Bring home the heroic team!
खास जानकारी और अगले चरण
इस ट्यूटोरियल में, टीआरएल और QLoRA का इस्तेमाल करके, विज़न टास्क के लिए Gemma मॉडल को फ़ाइन-ट्यून करने का तरीका बताया गया है. खास तौर पर, प्रॉडक्ट के ब्यौरे जनरेट करने के लिए. इसके बाद, यहां दिए गए दस्तावेज़ पढ़ें:
- Gemma मॉडल की मदद से टेक्स्ट जनरेट करने का तरीका जानें.
- Hugging Face Transformers का इस्तेमाल करके, टेक्स्ट से जुड़े टास्क के लिए Gemma को बेहतर बनाने का तरीका जानें.
- Hugging Face Transformers का इस्तेमाल करके, पूरे मॉडल को फ़ाइन-ट्यून करने का तरीका जानें.
- Gemma मॉडल पर डिस्ट्रिब्यूटेड फ़ाइन-ट्यूनिंग और अनुमान लगाने की प्रोसेस करने का तरीका जानें.
- Vertex AI के साथ Gemma के ओपन मॉडल इस्तेमाल करने का तरीका जानें.
- KerasNLP का इस्तेमाल करके Gemma को फ़ाइन-ट्यून करने और Vertex AI पर डिप्लॉय करने का तरीका जानें.
Google Colab में चलाएं
GitHub पर सोर्स देखें