Как загрузить веса LoRA для модели классификации изображенийPython

Программы на Python
Anonymous
Как загрузить веса LoRA для модели классификации изображений

Сообщение Anonymous »

Я обучил модель, как показано ниже.

Код: Выделить всё

model_name = 'owkin/phikon'
model = AutoModelForImageClassification.from_pretrained(
model_name,
label2id=label2id,
id2label=id2label,
ignore_mismatched_sizes=False,
cache_dir=cache_dir,
)

from peft import LoraConfig, get_peft_model, PeftConfig, PeftModel

config = LoraConfig(
r=16,
lora_alpha=16,
target_modules=["query", "value"],
lora_dropout=0.1,
bias="none",
modules_to_save=["classifier"],
)
lora_model = get_peft_model(model, config)

import numpy as np
import torch

import evaluate
from transformers import TrainingArguments, Trainer

# LoRA configuration
#lora_model = model
save_name = 'custom_training_2'
batch_size = 128 if "v2" not in model_name else 32
args = TrainingArguments(
save_name,
remove_unused_columns=False,
evaluation_strategy="steps",
save_strategy="steps",
learning_rate=5e-3,
gradient_accumulation_steps=1,
per_device_train_batch_size=batch_size,
per_device_eval_batch_size=batch_size,
fp16=True,
seed=SEED,
num_train_epochs=10,
logging_steps=1,
load_best_model_at_end=True,
metric_for_best_model="accuracy",  # dataset is roughly balanced
push_to_hub=False,
label_names=["labels"],
save_steps = 10,

)

# Metric configuration

metric = evaluate.load("accuracy")

def compute_metrics(eval_pred: np.ndarray) -> float:
"""Computes accuracy on a batch of predictions."""
predictions = np.argmax(eval_pred.predictions, axis=1)
return metric.compute(predictions=predictions, references=eval_pred.label_ids)

# Inputs generation for training

def collate_fn(examples) -> dict[str, torch.Tensor]:
"""Create the inputs for LoRA from an example in the dataset."""
pixel_values = torch.stack([example["pixel_values"] for example in examples])
labels = torch.tensor([example["label"] for example in examples])
return {"pixel_values": pixel_values, "labels": labels}

# Here is the final trainer
trainer_lora = Trainer(
model=lora_model,
args=args,
train_dataset=train_dataset,
eval_dataset=val_dataset,
tokenizer=image_processor,
compute_metrics=compute_metrics,
data_collator=collate_fn,
)

# Here is for fully training the model.

import warnings

from transformers.utils import logging

with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=UserWarning)
train_results_lora = trainer_lora.train()
metrics_lora = trainer_lora.evaluate(test_dataset)
trainer_lora.log_metrics("Trained model: VAL-CRC-7K", metrics_lora)

В конце обучения я получаю папку, как показано ниже

Код: Выделить всё

--\runs
--\checkpoint-10
--\checkpoint-20
----adapter_config.json
----adapter_model.safetensors
----optimizer.pt
----preprocessor_config.json
----README.md
----rng_state.pth
----scheduler.pt
----trainer_state.json
----training_args.bin
Мой вопрос: как загрузить обученные веса для вывода?
Я нашел эти решения, но они мне не помогли:
Как загрузить веса LoRA, сохраненные локально?
https://pypi.org/project/lora-pytorch/
https://discuss .huggingface.co/t/loading-lora-models-after-trainning/74076
Если вам нужно, я могу предоставить вам более подробную информацию.

Подробнее здесь: https://stackoverflow.com/questions/787 ... tion-model

Вернуться в «Python»