| | Ekzekuto në Google Colab | | | Shiko burimin në GitHub |
Ky udhëzues ju udhëzon se si ta përshtatni Gemma-n në një grup të dhënash të personalizuara nga teksti në SQL duke përdorur Hugging Face Transformers dhe TRL . Do të mësoni:
- Çfarë është Përshtatja e Kuantizuar me Rang të Ulët (QLoRA)
- Konfiguro mjedisin e zhvillimit
- Krijo dhe përgatit të dhënat e rregullimit të imët
- Përmirëso Gemma-n duke përdorur TRL dhe SFTTrainer
- Testimi i Modelit të Inferencës dhe gjenerimi i pyetjeve SQL
Çfarë është Përshtatja e Kuantizuar me Rang të Ulët (QLoRA)
Ky udhëzues demonstron përdorimin e Adaptimit të Kuantizuar me Rang të Ulët (QLoRA) , i cili u shfaq si një metodë popullore për të rregulluar në mënyrë efikase LLM-të, pasi zvogëlon kërkesat për burime llogaritëse duke ruajtur performancë të lartë. Në QloRA, modeli i para-trajnuar kuantizohet në 4-bit dhe peshat ngrihen. Pastaj shtresat e adaptorit të trajnueshëm (LoRA) bashkangjiten dhe vetëm shtresat e adaptorit trajnohen. Më pas, peshat e adaptorit mund të bashkohen me modelin bazë ose të mbahen si një adaptor i veçantë.
Konfiguro mjedisin e zhvillimit
Hapi i parë është instalimi i Bibliotekave të Face Hugging, duke përfshirë TRL, dhe grupeve të të dhënave për të akorduar modelin e hapur, duke përfshirë teknika të ndryshme RLHF dhe shtrirjeje.
# Install Pytorch & other libraries
%pip install torch tensorboard
%pip install -U torchao
# Install Transformers
%pip install "transformers>=5.10.1"
# Install Hugging Face libraries
%pip install datasets accelerate evaluate bitsandbytes trl "peft>=0.19.0" protobuf 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
Shënim: Nëse përdorni një GPU me arkitekturë Ampere (siç është NVIDIA L4) ose më të re, mund të përdorni Flash Attention. Flash Attention është një metodë që përshpejton ndjeshëm llogaritjet dhe zvogëlon përdorimin e memories nga gjatësia kuadratike në atë lineare në sekuencë, duke çuar në përshpejtimin e trajnimit deri në 3 herë. Mësoni më shumë në FlashAttention .
Ju nevojitet një Token i vlefshëm i Hugging Face për të publikuar modelin tuaj. Nëse po përdorni brenda një Google Colab, mund ta përdorni në mënyrë të sigurt Tokenin tuaj të Hugging Face duke përdorur sekretet e Colab, përndryshe mund ta caktoni tokenin direkt në metodën login . Sigurohuni që tokeni juaj të ketë edhe të drejtë shkrimi, ndërsa e shtyni modelin tuaj në Qendër gjatë trajnimit.
# Login into Hugging Face Hub
from huggingface_hub import login
login()
Krijo dhe përgatit të dhënat e rregullimit të imët
Kur përmirësoni LLM-të, është e rëndësishme të dini rastin e përdorimit dhe detyrën që doni të zgjidhni. Kjo ju ndihmon të krijoni një grup të dhënash për të përmirësuar modelin tuaj. Nëse nuk e keni përcaktuar ende rastin e përdorimit, mund të dëshironi të ktheheni në fazën fillestare.
Si shembull, ky udhëzues përqendrohet në rastin e mëposhtëm të përdorimit:
- Përmirësoni një gjuhë natyrore në modelin SQL për integrim të përsosur në një mjet analize të të dhënave. Objektivi është të zvogëlohet ndjeshëm koha dhe ekspertiza e kërkuar për gjenerimin e pyetjeve SQL, duke u mundësuar edhe përdoruesve jo-teknikë të nxjerrin njohuri kuptimplote nga të dhënat.
Konvertimi i tekstit në SQL mund të jetë një rast i mirë përdorimi për përmirësimin e imët të LLM-ve, pasi është një detyrë komplekse që kërkon shumë njohuri (të brendshme) rreth të dhënave dhe gjuhës SQL.
Pasi të keni përcaktuar se rregullimi i imët është zgjidhja e duhur, ju nevojitet një grup të dhënash për ta rregulluar atë. Grupi i të dhënave duhet të jetë një grup i larmishëm demonstrimesh të detyrës/detyrave që dëshironi të zgjidhni. Ka disa mënyra për të krijuar një grup të tillë të dhënash, duke përfshirë:
- Duke përdorur grupe të dhënash ekzistuese me burim të hapur, siç është Spider
- Duke përdorur grupe të dhënash sintetike të krijuara nga LLM, siç është Alpaca
- Duke përdorur grupe të dhënash të krijuara nga njerëzit, siç është Dolly .
- Duke përdorur një kombinim të metodave, siç është Orca
Secila prej metodave ka avantazhet dhe disavantazhet e veta dhe varet nga buxheti, koha dhe kërkesat e cilësisë. Për shembull, përdorimi i një grupi të dhënash ekzistuese është më i lehtë, por mund të mos jetë i përshtatur për rastin tuaj specifik të përdorimit, ndërsa përdorimi i ekspertëve të fushës mund të jetë më i sakti, por mund të kërkojë shumë kohë dhe të jetë i kushtueshëm. Është gjithashtu e mundur të kombinohen disa metoda për të krijuar një grup të dhënash udhëzimesh, siç tregohet në Orca: Mësimi Progresiv nga Gjurmët Komplekse të Shpjegimit të GPT-4.
Ky udhëzues përdor një grup të dhënash tashmë ekzistues ( philschmid/gretel-synthetic-text-to-sql ), një grup të dhënash sintetike Text-to-SQL me cilësi të lartë që përfshin udhëzime në gjuhën natyrore, përkufizime skemash, arsyetim dhe pyetjen përkatëse SQL.
Hugging Face TRL mbështet modelimin automatik të formateve të të dhënave të bisedave. Kjo do të thotë që ju vetëm duhet të konvertoni të dhënat tuaja në objektet e duhura json, dhe trl kujdeset për modelimin dhe vendosjen e tyre në formatin e duhur.
{"messages": [{"role": "system", "content": "You are..."}, {"role": "user", "content": "..."}, {"role": "assistant", "content": "..."}]}
{"messages": [{"role": "system", "content": "You are..."}, {"role": "user", "content": "..."}, {"role": "assistant", "content": "..."}]}
{"messages": [{"role": "system", "content": "You are..."}, {"role": "user", "content": "..."}, {"role": "assistant", "content": "..."}]}
Philschmid/gretel-synthetic-text-to-sql përmban mbi 100 mijë mostra. Për ta mbajtur udhëzuesin të vogël, ai është reduktuar në vetëm 10,000 mostra.
Tani mund të përdorni bibliotekën e të dhënave Hugging Face për të ngarkuar të dhënat dhe për të krijuar një shabllon të shpejtë për të kombinuar udhëzimet e gjuhës natyrore, përkufizimin e skemës dhe për të shtuar një mesazh sistemi për asistentin tuaj.
from datasets import load_dataset
# System message for the assistant
system_message = """You are a text to SQL query translator. Users will ask you questions in English and you will generate a SQL query based on the provided SCHEMA."""
# User prompt that combines the user query and the schema
user_prompt = """Given the <USER_QUERY> and the <SCHEMA>, generate the corresponding SQL command to retrieve the desired data, considering the query's syntax, semantics, and schema constraints.
<SCHEMA>
{context}
</SCHEMA>
<USER_QUERY>
{question}
</USER_QUERY>
"""
def create_conversation(sample, idx):
return {
"messages": [
{"role": "system", "content": system_message},
{"role": "user", "content": user_prompt.format(question=sample["sql_prompt"], context=sample["sql_context"])},
{"role": "assistant", "content": sample["sql"]}
]
}
# Load dataset from the hub
dataset = load_dataset("philschmid/gretel-synthetic-text-to-sql", split="train")
dataset = dataset.select(range(1250))
# Convert dataset to OAI messages
dataset = dataset.map(create_conversation, with_indices=True, remove_columns=dataset.features)
# split dataset into 80% training samples and 20% test samples
dataset = dataset.train_test_split(test_size=0.2, shuffle=False)
# Print formatted user prompt
for item in dataset["train"][0]["messages"]:
print(item)
{'role': 'system', 'content': 'You are a text to SQL query translator. Users will ask you questions in English and you will generate a SQL query based on the provided SCHEMA.'}
{'role': 'user', 'content': "Given the <USER_QUERY> and the <SCHEMA>, generate the corresponding SQL command to retrieve the desired data, considering the query's syntax, semantics, and schema constraints.\n\n<SCHEMA>\nCREATE TABLE salesperson (salesperson_id INT, name TEXT, region TEXT); INSERT INTO salesperson (salesperson_id, name, region) VALUES (1, 'John Doe', 'North'), (2, 'Jane Smith', 'South'); CREATE TABLE timber_sales (sales_id INT, salesperson_id INT, volume REAL, sale_date DATE); INSERT INTO timber_sales (sales_id, salesperson_id, volume, sale_date) VALUES (1, 1, 120, '2021-01-01'), (2, 1, 150, '2021-02-01'), (3, 2, 180, '2021-01-01');\n</SCHEMA>\n\n<USER_QUERY>\nWhat is the total volume of timber sold by each salesperson, sorted by salesperson?\n</USER_QUERY>\n"}
{'role': 'assistant', 'content': 'SELECT salesperson_id, name, SUM(volume) as total_volume FROM timber_sales JOIN salesperson ON timber_sales.salesperson_id = salesperson.salesperson_id GROUP BY salesperson_id, name ORDER BY total_volume DESC;'}
Përmirëso Gemma-n duke përdorur TRL dhe SFTTrainer
Tani jeni gati të përmirësoni modelin tuaj. Hugging Face TRL SFTTrainer e bën të thjeshtë mbikëqyrjen e optimizimit të LLM-ve të hapura. SFTTrainer është një nënklasë e Trainer nga biblioteka transformers dhe mbështet të gjitha veçoritë e njëjta, duke përfshirë regjistrimin, vlerësimin dhe pikat e kontrollit, por shton veçori shtesë të cilësisë së jetës, duke përfshirë:
- Formatimi i të dhënave, duke përfshirë formatet bisedore dhe të udhëzimeve
- Trajnim vetëm për përfundimet, duke injoruar kërkesat
- Paketimi i të dhënave për trajnim më efikas
- Mbështetje për rregullim të imët me efikasitet të parametrave (PEFT) duke përfshirë QloRA
- Përgatitja e modelit dhe tokenizuesit për rregullime të hollësishme bisedore (siç është shtimi i tokenëve specialë)
Kodi i mëposhtëm ngarkon modelin Gemma dhe tokenizuesin nga Hugging Face dhe inicializon konfigurimin e kuantizimit.
import torch
from transformers import AutoProcessor, AutoModelForMultimodalLM, BitsAndBytesConfig
from peft import prepare_model_for_kbit_training
# Hugging Face model id
model_id = "google/gemma-4-E2B" # @param ["google/gemma-4-E2B","google/gemma-4-E4B","google/gemma-4-12B","google/gemma-4-31B","google/gemma-4-26B-A4B"] {"allow-input":true}
# Check if GPU supports bfloat16
if torch.cuda.is_bf16_supported():
torch_dtype = torch.bfloat16
else:
torch_dtype = torch.float16
# Define model init arguments
model_kwargs = dict(
dtype=torch_dtype, # What torch dtype to use
device_map="auto", # Let torch decide how to load the model
)
# BitsAndBytesConfig: Enables 4-bit quantization to reduce model size/memory usage
model_kwargs["quantization_config"] = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_use_double_quant=True,
bnb_4bit_quant_type='nf4',
bnb_4bit_compute_dtype=torch_dtype,
bnb_4bit_quant_storage=torch_dtype,
)
# Load model and processor
model = AutoModelForMultimodalLM.from_pretrained(model_id, **model_kwargs)
processor = AutoProcessor.from_pretrained("google/gemma-4-E2B-it") # Load the Instruction Processor to use the official Gemma template
# NOTE: You should call the prepare_model_for_kbit_training() function to preprocess the quantized model for training.
# On T4, we are skipping this step purely due to VRAM limitation and for a quick demonstration.
if (torch.cuda.get_device_properties(0).total_memory/1024**3) > 16:
model = prepare_model_for_kbit_training(model)
WARNING:torchao:Failed to load /usr/local/lib/python3.12/dist-packages/torchao/_C_mxfp8.cpython-310-x86_64-linux-gnu.so: Could not load this library: /usr/local/lib/python3.12/dist-packages/torchao/_C_mxfp8.cpython-310-x86_64-linux-gnu.so WARNING:torchao:Failed to load /usr/local/lib/python3.12/dist-packages/torchao/_C_cutlass_90a.abi3.so: Could not load this library: /usr/local/lib/python3.12/dist-packages/torchao/_C_cutlass_90a.abi3.so Loading weights: 0%| | 0/1951 [00:00<?, ?it/s] /usr/local/lib/python3.12/dist-packages/bitsandbytes/backends/cuda/ops.py:213: FutureWarning: _check_is_size will be removed in a future PyTorch release along with guard_size_oblivious. Use _check(i >= 0) instead. torch._check_is_size(blocksize)
SFTTrainer mbështet një integrim të integruar me peft , gjë që e bën të thjeshtë akordimin efikas të LLM-ve duke përdorur QLoRA. Ju vetëm duhet të krijoni një LoraConfig dhe t'ia jepni trajnerit.
from peft import LoraConfig
peft_config = LoraConfig(
lora_alpha=16,
lora_dropout=0.05,
r=16,
bias="none",
# no target_modules — PEFT's Gemma 4 defaults scope to the LM layers
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,
)
Para se të filloni trajnimin tuaj, duhet të përcaktoni hiperparametrin që dëshironi të përdorni në një instancë SFTConfig .
import torch
from trl import SFTConfig
args = SFTConfig(
output_dir="gemma-text-to-sql", # directory to save and repository id
max_length=512, # max length for model and packing of the dataset
num_train_epochs=3, # number of training epochs
per_device_train_batch_size=1, # batch size per device during training
per_device_eval_batch_size=1, # batch size per device during evaluation
optim="adamw_torch_fused", # use fused adamw optimizer
logging_steps=10, # log every 10 steps
save_strategy="epoch", # save checkpoint every epoch
eval_strategy="epoch", # evaluate checkpoint every epoch
learning_rate=2e-4, # learning rate
fp16=True if torch_dtype == torch.float16 else False, # use float16 precision
bf16=True if torch_dtype == torch.bfloat16 else False, # use bfloat16 precision
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_kwargs={"skip_prepare_dataset": True}, # important for collator
remove_unused_columns = False, # important for collator
)
# Data collator
def collate_fn(examples):
texts = []
for example in examples:
full_text = processor.apply_chat_template(
example["messages"], add_generation_prompt=False, tokenize=False
)
texts.append(full_text.strip())
# Tokenize the texts and process the audios
batch = processor(text=texts, return_tensors="pt", padding=True)
# The labels are the input_ids, and we mask the padding tokens and audio tokens in the loss computation
labels = batch["input_ids"].clone()
target_tokens = [
processor.tokenizer.convert_tokens_to_ids("<|turn>"),
processor.tokenizer.convert_tokens_to_ids("model"),
processor.tokenizer.convert_tokens_to_ids("\n")
]
target_len = len(target_tokens)
for i in range(labels.size(0)):
row_tokens = batch["input_ids"][i].tolist()
# Find where the assistant block begins
assistant_start_idx = None
for idx in range(len(row_tokens) - target_len + 1):
if row_tokens[idx : idx + target_len] == target_tokens:
# We want to keep loss calculation on the assistant transcription tokens,
# so we move the index right past the assistant header ('<|turn>\nmodel\n')
assistant_start_idx = idx + target_len
break
if assistant_start_idx is not None:
# Mask everything from index 0 up to the start of the actual Japanese text response
labels[i, :assistant_start_idx] = -100
else:
# Fallback safety: if template matching fails for an anomalous row, mask padding anyway
print("WARNING: maybe the sample is too long, try to increase `token_limit` value.")
labels[i, labels[i] == processor.tokenizer.pad_token_id] = -100
"""
# --- DEBUG PRINT CODE ---
print(f"\n--- Example {i} (Split index: {assistant_start_idx}) ---")
debug_string = []
for token_id, label_id in zip(row_tokens, labels[i].tolist()):
# Decode token by token so we can see exactly what is masked
decoded_token = processor.tokenizer.decode([token_id])
if label_id == -100:
# Red text for masked tokens (ANSI Escape Code)
debug_string.append(f"\033[91m{decoded_token}\033[0m")
else:
# Green text for active loss tokens
debug_string.append(f"\033[92m{decoded_token}\033[0m")
print("".join(debug_string))
# ------------------------
"""
# Mask tokens for not being used in the loss computation
labels[labels == processor.tokenizer.pad_token_id] = -100
batch["labels"] = labels
return batch
/tmp/ipykernel_164873/3952412390.py:4: FutureWarning: The default `loss_type` will change from `'nll'` to `'chunked_nll'` in TRL 1.7. For standard models this is transparent (same math, lower memory) and no action is needed — you'll get the new default automatically on upgrade. If you use a custom model, check ahead of time that `loss_type='chunked_nll'` runs and yields the same loss as `'nll'`; if it doesn't, pin `loss_type='nll'` to keep the current behavior and please open an issue at https://github.com/huggingface/trl/issues so we can address the edge case. args = SFTConfig(
Tani keni çdo bllok ndërtimi që ju nevojitet për të krijuar SFTTrainer in tuaj për të filluar trajnimin e modelit tuaj.
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,
)
Filloni stërvitjen duke thirrur metodën 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()
[transformers] 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}.
Processing Files (0 / 0) : | | 0.00B / 0.00B New Data Upload : | | 0.00B / 0.00B ...adapter_model.safetensors: 3%|3 | 56.0MB / 1.62GB ...154.ffa1dd7a1058.125401.0: 100%|##########| 126kB / 126kB ...268.ffa1dd7a1058.112980.0: 100%|##########| 47.9kB / 47.9kB ...-to-sql/training_args.bin: 100%|##########| 5.65kB / 5.65kB ...482.ffa1dd7a1058.164873.0: 100%|##########| 126kB / 126kB ...ext-to-sql/tokenizer.json: 100%|##########| 32.2MB / 32.2MB ...039.ffa1dd7a1058.109416.0: 100%|##########| 8.28kB / 8.28kB No files have been modified since last commit. Skipping to prevent empty commit. WARNING:huggingface_hub.hf_api:No files have been modified since last commit. Skipping to prevent empty commit.
Para se të testoni modelin tuaj, sigurohuni që të lironi memorien.
# free the memory again
del model
del trainer
torch.cuda.empty_cache()
Kur përdorni QLoRA, ju trajnoni vetëm adaptorët dhe jo modelin e plotë. Kjo do të thotë që kur ruani modelin gjatë trajnimit, ju ruani vetëm peshat e adaptorëve dhe jo modelin e plotë. Nëse dëshironi të ruani modelin e plotë, gjë që e bën më të lehtë përdorimin me pirgje shërbimi si vLLM ose TGI, mund të bashkoni peshat e adaptorëve në peshat e modelit duke përdorur metodën merge_and_unload dhe më pas të ruani modelin me metodën save_pretrained . Kjo ruan një model të parazgjedhur, i cili mund të përdoret për përfundime.
from transformers import AutoModelForMultimodalLM, AutoProcessor
from peft import PeftModel
# Load Model base model
model = AutoModelForMultimodalLM.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("google/gemma-4-E2B-it")
processor.save_pretrained("merged_model")
Loading weights: 0%| | 0/1951 [00:00<?, ?it/s] Writing model shards: 0%| | 0/4 [00:00<?, ?it/s] ['merged_model/processor_config.json']
Testimi i Modelit të Inferencës dhe gjenerimi i pyetjeve SQL
Pasi të keni mbaruar trajnimin, do të dëshironi të vlerësoni dhe testoni modelin tuaj. Mund të ngarkoni mostra të ndryshme nga të dhënat e testimit dhe të vlerësoni modelin në ato mostra.
from transformers import AutoModelForMultimodalLM, AutoProcessor
model_id = "merged_model"
# Load Model with PEFT adapter
model = AutoModelForMultimodalLM.from_pretrained(
model_id,
device_map="auto",
dtype="auto",
)
processor = AutoProcessor.from_pretrained(model_id)
Loading weights: 0%| | 0/1951 [00:00<?, ?it/s]
Le të ngarkojmë një mostër të rastësishme nga të dhënat e testimit dhe të gjenerojmë një komandë SQL.
from random import randint
import re
from transformers import pipeline, GenerationConfig, pipeline
config = GenerationConfig.from_pretrained(model_id)
config.max_new_tokens = 256
config.eos_token_id = [processor.tokenizer.convert_tokens_to_ids("<turn|>")]
# Load the model and tokenizer into the pipeline
pipe = pipeline("text-generation", model=model, tokenizer=processor.tokenizer)
# Load a random sample from the test dataset
rand_idx = randint(0, len(dataset["test"]))
test_sample = dataset["test"][rand_idx]
# Convert as test example into a prompt with the Gemma template
prompt = processor.tokenizer.apply_chat_template(test_sample["messages"][:2], tokenize=False, add_generation_prompt=True)
print(prompt)
# Generate our SQL query.
outputs = pipe(text_inputs=prompt, generation_config=config)
# Extract the user query and original answer
print(f"Context:\n", re.search(r'<SCHEMA>\n(.*?)\n</SCHEMA>', test_sample['messages'][1]['content'], re.DOTALL).group(1).strip())
print(f"Query:\n", re.search(r'<USER_QUERY>\n(.*?)\n</USER_QUERY>', test_sample['messages'][1]['content'], re.DOTALL).group(1).strip())
print(f"Original Answer:\n{test_sample['messages'][2]['content']}")
print(f"Generated Answer:\n{outputs[0]['generated_text'][len(prompt):].strip().removesuffix("<turn|>")}")
<bos><|turn>system You are a text to SQL query translator. Users will ask you questions in English and you will generate a SQL query based on the provided SCHEMA.<turn|> <|turn>user Given the <USER_QUERY> and the <SCHEMA>, generate the corresponding SQL command to retrieve the desired data, considering the query's syntax, semantics, and schema constraints. <SCHEMA> CREATE TABLE Auto_Shows (id INT, show_name VARCHAR(255), show_year INT, location VARCHAR(255)); INSERT INTO Auto_Shows (id, show_name, show_year, location) VALUES (1, 'New York International Auto Show', 2019, 'United States'); INSERT INTO Auto_Shows (id, show_name, show_year, location) VALUES (2, 'Chicago Auto Show', 2019, 'United States'); INSERT INTO Auto_Shows (id, show_name, show_year, location) VALUES (3, 'North American International Auto Show', 2018, 'United States'); </SCHEMA> <USER_QUERY> How many auto shows were held in the United States in the year 2019? </USER_QUERY><turn|> <|turn>model Context: CREATE TABLE Auto_Shows (id INT, show_name VARCHAR(255), show_year INT, location VARCHAR(255)); INSERT INTO Auto_Shows (id, show_name, show_year, location) VALUES (1, 'New York International Auto Show', 2019, 'United States'); INSERT INTO Auto_Shows (id, show_name, show_year, location) VALUES (2, 'Chicago Auto Show', 2019, 'United States'); INSERT INTO Auto_Shows (id, show_name, show_year, location) VALUES (3, 'North American International Auto Show', 2018, 'United States'); Query: How many auto shows were held in the United States in the year 2019? Original Answer: SELECT COUNT(*) FROM Auto_Shows WHERE show_year = 2019 AND location = 'United States'; Generated Answer: SELECT COUNT(*) FROM Auto_Shows WHERE location = 'United States' AND show_year = 2019;
Përmbledhje dhe hapat e mëtejshëm
Ky tutorial trajtoi mënyrën e përshtatjes së imët të një modeli Gemma duke përdorur TRL dhe QLoRA. Shikoni dokumentet e mëposhtme më poshtë:
- Mësoni si të gjeneroni tekst me një model Gemma .
- Mësoni si ta përshtatni imët Gemmën për detyrat e shikimit duke përdorur Transformuesit e Fytyrës përqafuese .
- Mësoni si të kryeni rregullime të hollësishme të shpërndara dhe nxjerrje përfundimesh në një model Gemma .
- Mësoni si të përdorni modelet e hapura të Gemma me Vertex AI .
- Mësoni si ta akordoni Gemma-n duke përdorur KerasNLP dhe ta vendosni në Vertex AI .
Ekzekuto në Google Colab
Shiko burimin në GitHub