Следуют версии пакета, а среда — Google-colab под управлением Ubuntu 22.04.3 LTS.
Код: Выделить всё
$pip list | grep -E 'torch|transformers'
sentence-transformers 3.2.1
torch 2.5.1+cu121
transformers 4.46.2
Код: Выделить всё
import torch
from transformers import pipeline
torch_device = torch.device('cuda:0')
classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli", device=torch_device)
result = classifier(
"one day I will see the world",
['travel', 'cooking', 'dancing', 'exploration'],
multi_label=True
)
print(result)
Код: Выделить всё
{
'sequence': 'one day I will see the world',
'labels': ['travel', 'exploration', 'dancing', 'cooking'],
'scores': [0.9945111274719238, 0.9383887052536011, 0.005706209223717451, 0.0018193129217252135]
}
Код: Выделить всё
from transformers import AutoModelForSequenceClassification, AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained('facebook/bart-large-mnli')
nli_model = AutoModelForSequenceClassification.from_pretrained('facebook/bart-large-mnli').to(torch_device)
inputs = tokenizer.batch_encode_plus(
['one day I will see the world'] + ['travel', 'exploration', 'dancing', 'cooking'],
return_tensors='pt',
padding=True
)
output = nli_model(
inputs['input_ids'].to(torch_device),
attention_mask=inputs['attention_mask'].to(torch_device)
)[0]
# doing `1:` to discard outputs for the premise
label_reps = output[1:, [0, 2]]
# softmax to not have logits
probs = label_reps.softmax(dim=1)
# extract probabilities that the output class is 1
prob_label_is_true = probs[:, 1]
print(prob_label_is_true)
Код: Выделить всё
tensor([0.8655, 0.4706, 0.9117, 0.7982], device='cuda:0', grad_fn=)
- Вероятности из конвейера значительно выше и имеют больше смысла с учетом входных данных. .
- Ручная токенизация и метод вывода модели дают гораздо меньшие вероятности.
Подробнее здесь: https://stackoverflow.com/questions/791 ... g-pipeline