docs / huggingface_setfit.txt
danidarko's picture
Upload 59 files
b1d4de0 verified
# File: setfit-main/src/setfit/__init__.py
__version__ = '1.1.0.dev0'
import importlib
import os
import warnings
from .data import get_templated_dataset, sample_dataset
from .model_card import SetFitModelCardData
from .modeling import SetFitHead, SetFitModel
from .span import AbsaModel, AbsaTrainer, AspectExtractor, AspectModel, PolarityModel
from .trainer import SetFitTrainer, Trainer
from .trainer_distillation import DistillationSetFitTrainer, DistillationTrainer
from .training_args import TrainingArguments
warnings.filterwarnings('default', category=DeprecationWarning)
if importlib.util.find_spec('codecarbon') and 'CODECARBON_LOG_LEVEL' not in os.environ:
os.environ['CODECARBON_LOG_LEVEL'] = 'error'
# File: setfit-main/src/setfit/data.py
from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union
import pandas as pd
import torch
from datasets import Dataset, DatasetDict, load_dataset
from torch.utils.data import Dataset as TorchDataset
from . import logging
logging.set_verbosity_info()
logger = logging.get_logger(__name__)
if TYPE_CHECKING:
from transformers import PreTrainedTokenizerBase
TokenizerOutput = Dict[str, List[int]]
SEEDS = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
SAMPLE_SIZES = [2, 4, 8, 16, 32, 64]
def get_templated_dataset(dataset: Optional[Dataset]=None, candidate_labels: Optional[List[str]]=None, reference_dataset: Optional[str]=None, template: str='This sentence is {}', sample_size: int=2, text_column: str='text', label_column: str='label', multi_label: bool=False, label_names_column: str='label_text') -> Dataset:
if dataset is None:
dataset = Dataset.from_dict({})
required_columns = {text_column, label_column}
column_names = set(dataset.column_names)
if column_names:
missing_columns = required_columns.difference(column_names)
if missing_columns:
raise ValueError(f'The following columns are missing from the input dataset: {missing_columns}.')
if bool(reference_dataset) == bool(candidate_labels):
raise ValueError('Must supply exactly one of `reference_dataset` or `candidate_labels` to `get_templated_dataset()`!')
if candidate_labels is None:
candidate_labels = get_candidate_labels(reference_dataset, label_names_column)
empty_label_vector = [0] * len(candidate_labels)
for (label_id, label_name) in enumerate(candidate_labels):
label_vector = empty_label_vector.copy()
label_vector[label_id] = 1
example = {text_column: template.format(label_name), label_column: label_vector if multi_label else label_id}
for _ in range(sample_size):
dataset = dataset.add_item(example)
return dataset
def get_candidate_labels(dataset_name: str, label_names_column: str='label_text') -> List[str]:
dataset = load_dataset(dataset_name, split='train')
try:
label_features = dataset.features['label']
candidate_labels = label_features.names
except AttributeError:
label_names = dataset.unique(label_names_column)
label_ids = dataset.unique('label')
id2label = sorted(zip(label_ids, label_names), key=lambda x: x[0])
candidate_labels = list(map(lambda x: x[1], id2label))
return candidate_labels
def create_samples(df: pd.DataFrame, sample_size: int, seed: int) -> pd.DataFrame:
examples = []
for label in df['label'].unique():
subset = df.query(f'label == {label}')
if len(subset) > sample_size:
examples.append(subset.sample(sample_size, random_state=seed, replace=False))
else:
examples.append(subset)
return pd.concat(examples)
def sample_dataset(dataset: Dataset, label_column: str='label', num_samples: int=8, seed: int=42) -> Dataset:
shuffled_dataset = dataset.shuffle(seed=seed)
df = shuffled_dataset.to_pandas()
df = df.groupby(label_column)
df = df.apply(lambda x: x.sample(min(num_samples, len(x)), random_state=seed))
df = df.reset_index(drop=True)
all_samples = Dataset.from_pandas(df, features=dataset.features)
return all_samples.shuffle(seed=seed)
def create_fewshot_splits(dataset: Dataset, sample_sizes: List[int], add_data_augmentation: bool=False, dataset_name: Optional[str]=None) -> DatasetDict:
splits_ds = DatasetDict()
df = dataset.to_pandas()
if add_data_augmentation and dataset_name is None:
raise ValueError('If `add_data_augmentation` is True, must supply a `dataset_name` to create_fewshot_splits()!')
for sample_size in sample_sizes:
if add_data_augmentation:
augmented_df = get_templated_dataset(reference_dataset=dataset_name, sample_size=sample_size).to_pandas()
for (idx, seed) in enumerate(SEEDS):
split_df = create_samples(df, sample_size, seed)
if add_data_augmentation:
split_df = pd.concat([split_df, augmented_df], axis=0).sample(frac=1, random_state=seed)
splits_ds[f'train-{sample_size}-{idx}'] = Dataset.from_pandas(split_df, preserve_index=False)
return splits_ds
def create_samples_multilabel(df: pd.DataFrame, sample_size: int, seed: int) -> pd.DataFrame:
examples = []
column_labels = [_col for _col in df.columns.tolist() if _col != 'text']
for label in column_labels:
subset = df.query(f'{label} == 1')
if len(subset) > sample_size:
examples.append(subset.sample(sample_size, random_state=seed, replace=False))
else:
examples.append(subset)
return pd.concat(examples).drop_duplicates()
def create_fewshot_splits_multilabel(dataset: Dataset, sample_sizes: List[int]) -> DatasetDict:
splits_ds = DatasetDict()
df = dataset.to_pandas()
for sample_size in sample_sizes:
for (idx, seed) in enumerate(SEEDS):
split_df = create_samples_multilabel(df, sample_size, seed)
splits_ds[f'train-{sample_size}-{idx}'] = Dataset.from_pandas(split_df, preserve_index=False)
return splits_ds
class SetFitDataset(TorchDataset):
def __init__(self, x: List[str], y: Union[List[int], List[List[int]]], tokenizer: 'PreTrainedTokenizerBase', max_length: int=32) -> None:
assert len(x) == len(y)
self.x = x
self.y = y
self.tokenizer = tokenizer
self.max_length = max_length
def __len__(self) -> int:
return len(self.x)
def __getitem__(self, idx: int) -> Tuple[TokenizerOutput, Union[int, List[int]]]:
feature = self.tokenizer(self.x[idx], max_length=self.max_length, padding='max_length', truncation=True, return_attention_mask='attention_mask' in self.tokenizer.model_input_names, return_token_type_ids='token_type_ids' in self.tokenizer.model_input_names)
label = self.y[idx]
return (feature, label)
def collate_fn(self, batch):
features = {input_name: [] for input_name in self.tokenizer.model_input_names}
labels = []
for (feature, label) in batch:
features['input_ids'].append(feature['input_ids'])
if 'attention_mask' in features:
features['attention_mask'].append(feature['attention_mask'])
if 'token_type_ids' in features:
features['token_type_ids'].append(feature['token_type_ids'])
labels.append(label)
features = {k: torch.Tensor(v).int() for (k, v) in features.items()}
labels = torch.Tensor(labels)
labels = labels.long() if len(labels.size()) == 1 else labels.float()
return (features, labels)
# File: setfit-main/src/setfit/exporters/onnx.py
import copy
import warnings
from typing import Callable, Optional, Union
import numpy as np
import onnx
import torch
from sentence_transformers import SentenceTransformer, models
from sklearn.linear_model import LogisticRegression
from transformers.modeling_utils import PreTrainedModel
from setfit.exporters.utils import mean_pooling
class OnnxSetFitModel(torch.nn.Module):
def __init__(self, model_body: PreTrainedModel, pooler: Optional[Union[torch.nn.Module, Callable[[torch.Tensor], torch.Tensor]]]=None, model_head: Optional[Union[torch.nn.Module, LogisticRegression]]=None):
super().__init__()
self.model_body = model_body
if pooler is None:
print('No pooler was set so defaulting to mean pooling.')
self.pooler = mean_pooling
else:
self.pooler = pooler
self.model_head = model_head
def forward(self, input_ids: torch.Tensor, attention_mask: torch.Tensor, token_type_ids: torch.Tensor):
hidden_states = self.model_body(input_ids, attention_mask, token_type_ids)
hidden_states = {'token_embeddings': hidden_states[0], 'attention_mask': attention_mask}
embeddings = self.pooler(hidden_states)
if self.model_head is None:
return embeddings
out = self.model_head(embeddings)
return out
def export_onnx_setfit_model(setfit_model: OnnxSetFitModel, inputs, output_path, opset: int=12):
input_names = list(inputs.keys())
output_names = ['logits']
dynamic_axes_input = {}
for input_name in input_names:
dynamic_axes_input[input_name] = {0: 'batch_size', 1: 'sequence'}
dynamic_axes_output = {}
for output_name in output_names:
dynamic_axes_output[output_name] = {0: 'batch_size'}
target = setfit_model.model_body.device
args = tuple((value.to(target) for value in inputs.values()))
setfit_model.eval()
with torch.no_grad():
torch.onnx.export(setfit_model, args=args, f=output_path, opset_version=opset, input_names=['input_ids', 'attention_mask', 'token_type_ids'], output_names=output_names, dynamic_axes={**dynamic_axes_input, **dynamic_axes_output})
def export_sklearn_head_to_onnx(model_head: LogisticRegression, opset: int) -> onnx.onnx_ml_pb2.ModelProto:
try:
import onnxconverter_common
from skl2onnx import convert_sklearn
from skl2onnx.common.data_types import guess_data_type
from skl2onnx.sklapi import CastTransformer
from sklearn.pipeline import Pipeline
except ImportError:
msg = '\n `skl2onnx` must be installed in order to convert a model with an sklearn head.\n Please install with `pip install skl2onnx`.\n '
raise ImportError(msg)
input_shape = (None, model_head.n_features_in_)
if hasattr(model_head, 'coef_'):
dtype = guess_data_type(model_head.coef_, shape=input_shape)[0][1]
elif not hasattr(model_head, 'coef_') and hasattr(model_head, 'estimators_'):
if any([not hasattr(e, 'coef_') for e in model_head.estimators_]):
raise ValueError('The model_head is a meta-estimator but not all of the estimators have a coef_ attribute.')
dtype = guess_data_type(model_head.estimators_[0].coef_, shape=input_shape)[0][1]
else:
raise ValueError('The model_head either does not have a coef_ attribute or some estimators in model_head.estimators_ do not have a coef_ attribute. Conversion to ONNX only supports these cases.')
dtype.shape = input_shape
if isinstance(dtype, onnxconverter_common.data_types.DoubleTensorType):
sklearn_model = Pipeline([('castdouble', CastTransformer(dtype=np.double)), ('head', model_head)])
else:
sklearn_model = model_head
onnx_model = convert_sklearn(sklearn_model, initial_types=[('model_head', dtype)], target_opset=opset, options={id(sklearn_model): {'zipmap': False}})
return onnx_model
def hummingbird_export(model, data_sample):
try:
from hummingbird.ml import convert
except ImportError:
raise ImportError("Hummingbird-ML library is not installed.Run 'pip install hummingbird-ml' to use this type of export.")
onnx_model = convert(model, 'onnx', data_sample)
return onnx_model._model
def export_onnx(model_body: SentenceTransformer, model_head: Union[torch.nn.Module, LogisticRegression], opset: int, output_path: str='model.onnx', ignore_ir_version: bool=True, use_hummingbird: bool=False) -> None:
model_body_module = model_body._modules['0']
model_pooler = model_body._modules['1']
tokenizer = model_body_module.tokenizer
max_length = model_body_module.max_seq_length
transformer = model_body_module.auto_model
transformer.eval()
tokenizer_kwargs = dict(max_length=max_length, padding='max_length', return_attention_mask=True, return_token_type_ids=True, return_tensors='pt')
dummy_sample = "It's a test."
dummy_inputs = tokenizer(dummy_sample, **tokenizer_kwargs)
if issubclass(type(model_head), models.Dense):
setfit_model = OnnxSetFitModel(transformer, lambda x: model_pooler(x)['sentence_embedding'], model_head).cpu()
export_onnx_setfit_model(setfit_model, dummy_inputs, output_path, opset)
onnx_setfit_model = onnx.load(output_path)
meta = onnx_setfit_model.metadata_props.add()
for (key, value) in tokenizer_kwargs.items():
meta = onnx_setfit_model.metadata_props.add()
meta.key = str(key)
meta.value = str(value)
else:
if use_hummingbird:
with torch.no_grad():
test_input = copy.deepcopy(dummy_inputs)
head_input = model_body(test_input)['sentence_embedding']
onnx_head = hummingbird_export(model_head, head_input.detach().numpy())
else:
onnx_head = export_sklearn_head_to_onnx(model_head, opset)
max_opset = max([x.version for x in onnx_head.opset_import])
if max_opset != opset:
warnings.warn(f'sklearn onnx max opset is {max_opset} requested opset {opset} using opset {max_opset} for compatibility.')
export_onnx_setfit_model(OnnxSetFitModel(transformer, lambda x: model_pooler(x)['sentence_embedding']), dummy_inputs, output_path, max_opset)
onnx_body = onnx.load(output_path)
if ignore_ir_version:
onnx_head.ir_version = onnx_body.ir_version
elif onnx_head.ir_version != onnx_body.ir_version:
msg = f'\n IR Version mismatch between head={onnx_head.ir_version} and body={onnx_body.ir_version}\n Make sure that the ONNX IR versions are aligned and supported between the chosen Sklearn model\n and the transformer. You can set ignore_ir_version=True to coerce them but this might cause errors.\n '
raise ValueError(msg)
head_input_name = next(iter(onnx_head.graph.input)).name
onnx_setfit_model = onnx.compose.merge_models(onnx_body, onnx_head, io_map=[('logits', head_input_name)])
onnx.save(onnx_setfit_model, output_path)
# File: setfit-main/src/setfit/exporters/openvino.py
import os
import openvino.runtime as ov
from setfit import SetFitModel
from setfit.exporters.onnx import export_onnx
def export_to_openvino(model: SetFitModel, output_path: str='model.xml') -> None:
OPENVINO_SUPPORTED_OPSET = 13
model.model_body.cpu()
onnx_path = output_path.replace('.xml', '.onnx')
export_onnx(model.model_body, model.model_head, opset=OPENVINO_SUPPORTED_OPSET, output_path=onnx_path, ignore_ir_version=True, use_hummingbird=True)
ov_model = ov.Core().read_model(onnx_path)
ov.serialize(ov_model, output_path)
os.remove(onnx_path)
# File: setfit-main/src/setfit/exporters/utils.py
import torch
def mean_pooling(token_embeddings: torch.Tensor, attention_mask: torch.Tensor) -> torch.Tensor:
input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-09)
# File: setfit-main/src/setfit/integrations.py
import importlib.util
from typing import TYPE_CHECKING
from .utils import BestRun
if TYPE_CHECKING:
from .trainer import Trainer
def is_optuna_available() -> bool:
return importlib.util.find_spec('optuna') is not None
def default_hp_search_backend():
if is_optuna_available():
return 'optuna'
def run_hp_search_optuna(trainer: 'Trainer', n_trials: int, direction: str, **kwargs) -> BestRun:
import optuna
def _objective(trial):
trainer.objective = None
trainer.train(trial=trial)
if getattr(trainer, 'objective', None) is None:
metrics = trainer.evaluate()
trainer.objective = trainer.compute_objective(metrics)
return trainer.objective
timeout = kwargs.pop('timeout', None)
n_jobs = kwargs.pop('n_jobs', 1)
study = optuna.create_study(direction=direction, **kwargs)
study.optimize(_objective, n_trials=n_trials, timeout=timeout, n_jobs=n_jobs)
best_trial = study.best_trial
return BestRun(str(best_trial.number), best_trial.value, best_trial.params, study)
# File: setfit-main/src/setfit/logging.py
""""""
import logging
import os
import sys
import threading
from logging import CRITICAL
from logging import DEBUG
from logging import ERROR
from logging import FATAL
from logging import INFO
from logging import NOTSET
from logging import WARN
from logging import WARNING
from typing import Optional
import huggingface_hub.utils as hf_hub_utils
from tqdm import auto as tqdm_lib
_lock = threading.Lock()
_default_handler: Optional[logging.Handler] = None
log_levels = {'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL}
_default_log_level = logging.WARNING
_tqdm_active = True
def _get_default_logging_level():
env_level_str = os.getenv('TRANSFORMERS_VERBOSITY', None)
if env_level_str:
if env_level_str in log_levels:
return log_levels[env_level_str]
else:
logging.getLogger().warning(f"Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, has to be one of: {', '.join(log_levels.keys())}")
return _default_log_level
def _get_library_name() -> str:
return __name__.split('.')[0]
def _get_library_root_logger() -> logging.Logger:
return logging.getLogger(_get_library_name())
def _configure_library_root_logger() -> None:
global _default_handler
with _lock:
if _default_handler:
return
_default_handler = logging.StreamHandler()
_default_handler.flush = sys.stderr.flush
library_root_logger = _get_library_root_logger()
library_root_logger.addHandler(_default_handler)
library_root_logger.setLevel(_get_default_logging_level())
library_root_logger.propagate = False
def _reset_library_root_logger() -> None:
global _default_handler
with _lock:
if not _default_handler:
return
library_root_logger = _get_library_root_logger()
library_root_logger.removeHandler(_default_handler)
library_root_logger.setLevel(logging.NOTSET)
_default_handler = None
def get_log_levels_dict():
return log_levels
def get_logger(name: Optional[str]=None) -> logging.Logger:
if name is None:
name = _get_library_name()
_configure_library_root_logger()
return logging.getLogger(name)
def get_verbosity() -> int:
_configure_library_root_logger()
return _get_library_root_logger().getEffectiveLevel()
def set_verbosity(verbosity: int) -> None:
_configure_library_root_logger()
_get_library_root_logger().setLevel(verbosity)
def set_verbosity_info():
return set_verbosity(INFO)
def set_verbosity_warning():
return set_verbosity(WARNING)
def set_verbosity_debug():
return set_verbosity(DEBUG)
def set_verbosity_error():
return set_verbosity(ERROR)
def disable_default_handler() -> None:
_configure_library_root_logger()
assert _default_handler is not None
_get_library_root_logger().removeHandler(_default_handler)
def enable_default_handler() -> None:
_configure_library_root_logger()
assert _default_handler is not None
_get_library_root_logger().addHandler(_default_handler)
def add_handler(handler: logging.Handler) -> None:
_configure_library_root_logger()
assert handler is not None
_get_library_root_logger().addHandler(handler)
def remove_handler(handler: logging.Handler) -> None:
_configure_library_root_logger()
assert handler is not None and handler not in _get_library_root_logger().handlers
_get_library_root_logger().removeHandler(handler)
def disable_propagation() -> None:
_configure_library_root_logger()
_get_library_root_logger().propagate = False
def enable_propagation() -> None:
_configure_library_root_logger()
_get_library_root_logger().propagate = True
def enable_explicit_format() -> None:
handlers = _get_library_root_logger().handlers
for handler in handlers:
formatter = logging.Formatter('[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s')
handler.setFormatter(formatter)
def reset_format() -> None:
handlers = _get_library_root_logger().handlers
for handler in handlers:
handler.setFormatter(None)
def warning_advice(self, *args, **kwargs):
no_advisory_warnings = os.getenv('TRANSFORMERS_NO_ADVISORY_WARNINGS', False)
if no_advisory_warnings:
return
self.warning(*args, **kwargs)
logging.Logger.warning_advice = warning_advice
class EmptyTqdm:
def __init__(self, *args, **kwargs):
self._iterator = args[0] if args else None
def __iter__(self):
return iter(self._iterator)
def __getattr__(self, _):
def empty_fn(*args, **kwargs):
return
return empty_fn
def __enter__(self):
return self
def __exit__(self, type_, value, traceback):
return
class _tqdm_cls:
def __call__(self, *args, **kwargs):
if _tqdm_active:
return tqdm_lib.tqdm(*args, **kwargs)
else:
return EmptyTqdm(*args, **kwargs)
def set_lock(self, *args, **kwargs):
self._lock = None
if _tqdm_active:
return tqdm_lib.tqdm.set_lock(*args, **kwargs)
def get_lock(self):
if _tqdm_active:
return tqdm_lib.tqdm.get_lock()
tqdm = _tqdm_cls()
def is_progress_bar_enabled() -> bool:
global _tqdm_active
return bool(_tqdm_active)
def enable_progress_bar():
global _tqdm_active
_tqdm_active = True
hf_hub_utils.enable_progress_bars()
def disable_progress_bar():
global _tqdm_active
_tqdm_active = False
hf_hub_utils.disable_progress_bars()
# File: setfit-main/src/setfit/losses.py
import torch
from torch import nn
class SupConLoss(nn.Module):
def __init__(self, model, temperature=0.07, contrast_mode='all', base_temperature=0.07):
super(SupConLoss, self).__init__()
self.model = model
self.temperature = temperature
self.contrast_mode = contrast_mode
self.base_temperature = base_temperature
def forward(self, sentence_features, labels=None, mask=None):
features = self.model(sentence_features[0])['sentence_embedding']
features = torch.nn.functional.normalize(features, p=2, dim=1)
features = torch.unsqueeze(features, 1)
device = features.device
if len(features.shape) < 3:
raise ValueError('`features` needs to be [bsz, n_views, ...],at least 3 dimensions are required')
if len(features.shape) > 3:
features = features.view(features.shape[0], features.shape[1], -1)
batch_size = features.shape[0]
if labels is not None and mask is not None:
raise ValueError('Cannot define both `labels` and `mask`')
elif labels is None and mask is None:
mask = torch.eye(batch_size, dtype=torch.float32).to(device)
elif labels is not None:
labels = labels.contiguous().view(-1, 1)
if labels.shape[0] != batch_size:
raise ValueError('Num of labels does not match num of features')
mask = torch.eq(labels, labels.T).float().to(device)
else:
mask = mask.float().to(device)
contrast_count = features.shape[1]
contrast_feature = torch.cat(torch.unbind(features, dim=1), dim=0)
if self.contrast_mode == 'one':
anchor_feature = features[:, 0]
anchor_count = 1
elif self.contrast_mode == 'all':
anchor_feature = contrast_feature
anchor_count = contrast_count
else:
raise ValueError('Unknown mode: {}'.format(self.contrast_mode))
anchor_dot_contrast = torch.div(torch.matmul(anchor_feature, contrast_feature.T), self.temperature)
(logits_max, _) = torch.max(anchor_dot_contrast, dim=1, keepdim=True)
logits = anchor_dot_contrast - logits_max.detach()
mask = mask.repeat(anchor_count, contrast_count)
logits_mask = torch.scatter(torch.ones_like(mask), 1, torch.arange(batch_size * anchor_count).view(-1, 1).to(device), 0)
mask = mask * logits_mask
exp_logits = torch.exp(logits) * logits_mask
log_prob = logits - torch.log(exp_logits.sum(1, keepdim=True))
mean_log_prob_pos = (mask * log_prob).sum(1) / mask.sum(1)
loss = -(self.temperature / self.base_temperature) * mean_log_prob_pos
loss = loss.view(anchor_count, batch_size).mean()
return loss
# File: setfit-main/src/setfit/model_card.py
import collections
import random
from collections import Counter, defaultdict
from dataclasses import dataclass, field, fields
from pathlib import Path
from platform import python_version
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union
import datasets
import tokenizers
import torch
import transformers
from datasets import Dataset
from huggingface_hub import CardData, ModelCard, dataset_info, list_datasets, model_info
from huggingface_hub.repocard_data import EvalResult, eval_results_to_model_index
from huggingface_hub.utils import yaml_dump
from sentence_transformers import __version__ as sentence_transformers_version
from transformers import PretrainedConfig, TrainerCallback
from transformers.integrations import CodeCarbonCallback
from transformers.modelcard import make_markdown_table
from transformers.trainer_callback import TrainerControl, TrainerState
from transformers.training_args import TrainingArguments
from setfit import __version__ as setfit_version
from . import logging
logger = logging.get_logger(__name__)
if TYPE_CHECKING:
from setfit.modeling import SetFitModel
from setfit.trainer import Trainer
class ModelCardCallback(TrainerCallback):
def __init__(self, trainer: 'Trainer') -> None:
super().__init__()
self.trainer = trainer
callbacks = [callback for callback in self.trainer.callback_handler.callbacks if isinstance(callback, CodeCarbonCallback)]
if callbacks:
trainer.model.model_card_data.code_carbon_callback = callbacks[0]
def on_init_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, model: 'SetFitModel', **kwargs):
if not model.model_card_data.dataset_id:
try:
model.model_card_data.infer_dataset_id(self.trainer.train_dataset)
except Exception:
pass
dataset = self.trainer.eval_dataset or self.trainer.train_dataset
if dataset is not None:
if not model.model_card_data.widget:
model.model_card_data.set_widget_examples(dataset)
if self.trainer.train_dataset:
model.model_card_data.set_train_set_metrics(self.trainer.train_dataset)
try:
model.model_card_data.num_classes = len(set(self.trainer.train_dataset['label']))
model.model_card_data.set_label_examples(self.trainer.train_dataset)
except Exception:
pass
def on_train_begin(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, model: 'SetFitModel', **kwargs) -> None:
ignore_keys = {'output_dir', 'logging_dir', 'logging_strategy', 'logging_first_step', 'logging_steps', 'eval_strategy', 'eval_steps', 'eval_delay', 'save_strategy', 'save_steps', 'save_total_limit', 'metric_for_best_model', 'greater_is_better', 'report_to', 'samples_per_label', 'show_progress_bar'}
get_name_keys = {'loss', 'distance_metric'}
args_dict = args.to_dict()
model.model_card_data.hyperparameters = {key: value.__name__ if key in get_name_keys else value for (key, value) in args_dict.items() if key not in ignore_keys and value is not None}
def on_evaluate(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, model: 'SetFitModel', metrics: Dict[str, float], **kwargs) -> None:
if model.model_card_data.eval_lines_list and model.model_card_data.eval_lines_list[-1]['Step'] == state.global_step:
model.model_card_data.eval_lines_list[-1]['Validation Loss'] = metrics['eval_embedding_loss']
else:
model.model_card_data.eval_lines_list.append({'Epoch': state.epoch, 'Step': state.global_step, 'Training Loss': '-', 'Validation Loss': metrics['eval_embedding_loss']})
def on_log(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, model: 'SetFitModel', logs: Dict[str, float], **kwargs):
keys = {'embedding_loss', 'polarity_embedding_loss', 'aspect_embedding_loss'} & set(logs)
if keys:
if model.model_card_data.eval_lines_list and model.model_card_data.eval_lines_list[-1]['Step'] == state.global_step:
model.model_card_data.eval_lines_list[-1]['Training Loss'] = logs[keys.pop()]
else:
model.model_card_data.eval_lines_list.append({'Epoch': state.epoch, 'Step': state.global_step, 'Training Loss': logs[keys.pop()], 'Validation Loss': '-'})
YAML_FIELDS = ['language', 'license', 'library_name', 'tags', 'datasets', 'metrics', 'pipeline_tag', 'widget', 'model-index', 'co2_eq_emissions', 'base_model', 'inference']
IGNORED_FIELDS = ['model']
@dataclass
class SetFitModelCardData(CardData):
language: Optional[Union[str, List[str]]] = None
license: Optional[str] = None
tags: Optional[List[str]] = field(default_factory=lambda : ['setfit', 'sentence-transformers', 'text-classification', 'generated_from_setfit_trainer'])
model_name: Optional[str] = None
model_id: Optional[str] = None
dataset_name: Optional[str] = None
dataset_id: Optional[str] = None
dataset_revision: Optional[str] = None
task_name: Optional[str] = None
st_id: Optional[str] = None
hyperparameters: Dict[str, Any] = field(default_factory=dict, init=False)
eval_results_dict: Optional[Dict[str, Any]] = field(default_factory=dict, init=False)
eval_lines_list: List[Dict[str, float]] = field(default_factory=list, init=False)
metric_lines: List[Dict[str, float]] = field(default_factory=list, init=False)
widget: List[Dict[str, str]] = field(default_factory=list, init=False)
predict_example: Optional[str] = field(default=None, init=False)
label_example_list: List[Dict[str, str]] = field(default_factory=list, init=False)
tokenizer_warning: bool = field(default=False, init=False)
train_set_metrics_list: List[Dict[str, str]] = field(default_factory=list, init=False)
train_set_sentences_per_label_list: List[Dict[str, str]] = field(default_factory=list, init=False)
code_carbon_callback: Optional[CodeCarbonCallback] = field(default=None, init=False)
num_classes: Optional[int] = field(default=None, init=False)
best_model_step: Optional[int] = field(default=None, init=False)
metrics: List[str] = field(default_factory=lambda : ['accuracy'], init=False)
pipeline_tag: str = field(default='text-classification', init=False)
library_name: str = field(default='setfit', init=False)
version: Dict[str, str] = field(default_factory=lambda : {'python': python_version(), 'setfit': setfit_version, 'sentence_transformers': sentence_transformers_version, 'transformers': transformers.__version__, 'torch': torch.__version__, 'datasets': datasets.__version__, 'tokenizers': tokenizers.__version__}, init=False)
absa: Dict[str, Any] = field(default=None, init=False, repr=False)
model: Optional['SetFitModel'] = field(default=None, init=False, repr=False)
head_class: Optional[str] = field(default=None, init=False, repr=False)
inference: Optional[bool] = field(default=True, init=False, repr=False)
def __post_init__(self):
if self.dataset_id:
if is_on_huggingface(self.dataset_id, is_model=False):
if self.language is None:
try:
info = dataset_info(self.dataset_id)
except Exception:
pass
else:
if info.cardData:
self.language = info.cardData.get('language', self.language)
else:
logger.warning(f'The provided {self.dataset_id!r} dataset could not be found on the Hugging Face Hub. Setting `dataset_id` to None.')
self.dataset_id = None
if self.model_id and self.model_id.count('/') != 1:
logger.warning(f'The provided {self.model_id!r} model ID should include the organization or user, such as "tomaarsen/setfit-bge-small-v1.5-sst2-8-shot". Setting `model_id` to None.')
self.model_id = None
def set_best_model_step(self, step: int) -> None:
self.best_model_step = step
def set_widget_examples(self, dataset: Dataset) -> None:
samples = dataset.select(random.sample(range(len(dataset)), k=min(len(dataset), 5)))['text']
self.widget = [{'text': sample} for sample in samples]
samples.sort(key=len)
if samples:
self.predict_example = samples[0]
def set_train_set_metrics(self, dataset: Dataset) -> None:
def add_naive_word_count(sample: Dict[str, Any]) -> Dict[str, Any]:
sample['word_count'] = len(sample['text'].split(' '))
return sample
dataset = dataset.map(add_naive_word_count)
self.train_set_metrics_list = [{'Training set': 'Word count', 'Min': min(dataset['word_count']), 'Median': sum(dataset['word_count']) / len(dataset), 'Max': max(dataset['word_count'])}]
if 'label' not in dataset.column_names:
return
sample_label = dataset[0]['label']
if isinstance(sample_label, collections.abc.Sequence) and (not isinstance(sample_label, str)):
return
try:
counter = Counter(dataset['label'])
if self.model.labels:
self.train_set_sentences_per_label_list = [{'Label': str_label, 'Training Sample Count': counter[str_label if isinstance(sample_label, str) else self.model.label2id[str_label]]} for str_label in self.model.labels]
else:
self.train_set_sentences_per_label_list = [{'Label': self.model.labels[label] if self.model.labels and isinstance(label, int) else str(label), 'Training Sample Count': count} for (label, count) in sorted(counter.items())]
except Exception:
pass
def set_label_examples(self, dataset: Dataset) -> None:
num_examples_per_label = 3
examples = defaultdict(list)
finished_labels = set()
for sample in dataset:
text = sample['text']
label = sample['label']
if label not in finished_labels:
examples[label].append(f'<li>{repr(text)}</li>')
if len(examples[label]) >= num_examples_per_label:
finished_labels.add(label)
if len(finished_labels) == self.num_classes:
break
self.label_example_list = [{'Label': self.model.labels[label] if self.model.labels and isinstance(label, int) else label, 'Examples': '<ul>' + ''.join(example_set) + '</ul>'} for (label, example_set) in examples.items()]
def infer_dataset_id(self, dataset: Dataset) -> None:
def subtuple_finder(tuple: Tuple[str], subtuple: Tuple[str]) -> int:
for (i, element) in enumerate(tuple):
if element == subtuple[0] and tuple[i:i + len(subtuple)] == subtuple:
return i
return -1
def normalize(dataset_id: str) -> str:
for token in '/\\_-':
dataset_id = dataset_id.replace(token, '')
return dataset_id.lower()
cache_files = dataset.cache_files
if cache_files and 'filename' in cache_files[0]:
cache_path_parts = Path(cache_files[0]['filename']).parts
subtuple = ('huggingface', 'datasets')
index = subtuple_finder(cache_path_parts, subtuple)
if index == -1:
return
cache_dataset_name = cache_path_parts[index + len(subtuple)]
if '___' in cache_dataset_name:
(author, dataset_name) = cache_dataset_name.split('___')
else:
author = None
dataset_name = cache_dataset_name
dataset_list = [dataset for dataset in list_datasets(author=author, dataset_name=dataset_name) if normalize(dataset.id) == normalize(cache_dataset_name)]
if len(dataset_list) == 1:
self.dataset_id = dataset_list[0].id
def register_model(self, model: 'SetFitModel') -> None:
self.model = model
head_class = model.model_head.__class__.__name__
self.head_class = {'LogisticRegression': '[LogisticRegression](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html)', 'SetFitHead': '[SetFitHead](huggingface.co/docs/setfit/reference/main#setfit.SetFitHead)'}.get(head_class, head_class)
if not self.model_name:
if self.st_id:
self.model_name = f'SetFit with {self.st_id}'
if self.dataset_name or self.dataset_id:
self.model_name += f' on {self.dataset_name or self.dataset_id}'
else:
self.model_name = 'SetFit'
self.inference = self.model.multi_target_strategy is None
def infer_st_id(self, setfit_model_id: str) -> None:
(config_dict, _) = PretrainedConfig.get_config_dict(setfit_model_id)
st_id = config_dict.get('_name_or_path')
st_id_path = Path(st_id)
candidate_model_ids = ['/'.join(st_id_path.parts[-2:])]
splits = st_id_path.name.split('_')
candidate_model_ids += ['_'.join(splits[:idx]) + '/' + '_'.join(splits[idx:]) for idx in range(1, len(splits))]
for model_id in candidate_model_ids:
if is_on_huggingface(model_id):
self.st_id = model_id
break
def set_st_id(self, model_id: str) -> None:
if is_on_huggingface(model_id):
self.st_id = model_id
def post_training_eval_results(self, results: Dict[str, float]) -> None:
def try_to_pure_python(value: Any) -> Any:
try:
if hasattr(value, 'dtype'):
return value.item()
except Exception:
pass
return value
pure_python_results = {key: try_to_pure_python(value) for (key, value) in results.items()}
results_without_split = {key.split('_', maxsplit=1)[1].title(): value for (key, value) in pure_python_results.items()}
self.eval_results_dict = pure_python_results
self.metric_lines = [{'Label': '**all**', **results_without_split}]
def _maybe_round(self, v, decimals=4):
if isinstance(v, float) and len(str(v).split('.')) > 1 and (len(str(v).split('.')[1]) > decimals):
return f'{v:.{decimals}f}'
return str(v)
def to_dict(self) -> Dict[str, Any]:
super_dict = {field.name: getattr(self, field.name) for field in fields(self)}
if self.eval_results_dict:
dataset_split = list(self.eval_results_dict.keys())[0].split('_')[0]
dataset_id = self.dataset_id or 'unknown'
dataset_name = self.dataset_name or self.dataset_id or 'Unknown'
eval_results = [EvalResult(task_type='text-classification', dataset_type=dataset_id, dataset_name=dataset_name, dataset_split=dataset_split, dataset_revision=self.dataset_revision, metric_type=metric_key.split('_', maxsplit=1)[1], metric_value=metric_value, task_name='Text Classification', metric_name=metric_key.split('_', maxsplit=1)[1].title()) for (metric_key, metric_value) in self.eval_results_dict.items()]
super_dict['metrics'] = [metric_key.split('_', maxsplit=1)[1] for metric_key in self.eval_results_dict]
super_dict['model-index'] = eval_results_to_model_index(self.model_name, eval_results)
eval_lines_list = [{key: f'**{self._maybe_round(value)}**' if line['Step'] == self.best_model_step else value for (key, value) in line.items()} for line in self.eval_lines_list]
super_dict['eval_lines'] = make_markdown_table(eval_lines_list)
super_dict['explain_bold_in_eval'] = '**' in super_dict['eval_lines']
super_dict['label_examples'] = make_markdown_table(self.label_example_list).replace('-:|', '--|')
super_dict['train_set_metrics'] = make_markdown_table(self.train_set_metrics_list).replace('-:|', '--|')
super_dict['train_set_sentences_per_label_list'] = make_markdown_table(self.train_set_sentences_per_label_list).replace('-:|', '--|')
super_dict['metrics_table'] = make_markdown_table(self.metric_lines).replace('-:|', '--|')
if self.code_carbon_callback and self.code_carbon_callback.tracker:
emissions_data = self.code_carbon_callback.tracker._prepare_emissions_data()
super_dict['co2_eq_emissions'] = {'emissions': float(emissions_data.emissions) * 1000, 'source': 'codecarbon', 'training_type': 'fine-tuning', 'on_cloud': emissions_data.on_cloud == 'Y', 'cpu_model': emissions_data.cpu_model, 'ram_total_size': emissions_data.ram_total_size, 'hours_used': round(emissions_data.duration / 3600, 3)}
if emissions_data.gpu_model:
super_dict['co2_eq_emissions']['hardware_used'] = emissions_data.gpu_model
if self.dataset_id:
super_dict['datasets'] = [self.dataset_id]
if self.st_id:
super_dict['base_model'] = self.st_id
super_dict['model_max_length'] = self.model.model_body.get_max_seq_length()
if super_dict['num_classes'] is None:
if self.model.labels:
super_dict['num_classes'] = len(self.model.labels)
if super_dict['absa']:
super_dict.update(super_dict.pop('absa'))
for key in IGNORED_FIELDS:
super_dict.pop(key, None)
return super_dict
def to_yaml(self, line_break=None) -> str:
return yaml_dump({key: value for (key, value) in self.to_dict().items() if key in YAML_FIELDS and value is not None}, sort_keys=False, line_break=line_break).strip()
def is_on_huggingface(repo_id: str, is_model: bool=True) -> bool:
if len(repo_id.split('/')) > 2:
return False
try:
if is_model:
model_info(repo_id)
else:
dataset_info(repo_id)
return True
except Exception:
return False
def generate_model_card(model: 'SetFitModel') -> str:
template_path = Path(__file__).parent / 'model_card_template.md'
model_card = ModelCard.from_template(card_data=model.model_card_data, template_path=template_path, hf_emoji='🤗')
return model_card.content
# File: setfit-main/src/setfit/modeling.py
import json
import os
import tempfile
import warnings
from pathlib import Path
from typing import Dict, List, Literal, Optional, Set, Tuple, Union
import joblib
import numpy as np
import requests
import torch
from huggingface_hub import ModelHubMixin, hf_hub_download
from huggingface_hub.utils import validate_hf_hub_args
from packaging.version import Version, parse
from sentence_transformers import SentenceTransformer
from sentence_transformers import __version__ as sentence_transformers_version
from sentence_transformers import models
from sklearn.linear_model import LogisticRegression
from sklearn.multiclass import OneVsRestClassifier
from sklearn.multioutput import ClassifierChain, MultiOutputClassifier
from torch import nn
from torch.utils.data import DataLoader
from tqdm.auto import tqdm, trange
from transformers.utils import copy_func
from . import logging
from .data import SetFitDataset
from .model_card import SetFitModelCardData, generate_model_card
from .utils import set_docstring
logging.set_verbosity_info()
logger = logging.get_logger(__name__)
MODEL_HEAD_NAME = 'model_head.pkl'
CONFIG_NAME = 'config_setfit.json'
class SetFitHead(models.Dense):
def __init__(self, in_features: Optional[int]=None, out_features: int=2, temperature: float=1.0, eps: float=1e-05, bias: bool=True, device: Optional[Union[torch.device, str]]=None, multitarget: bool=False) -> None:
super(models.Dense, self).__init__()
if out_features == 1:
logger.warning('Change `out_features` from 1 to 2 since we use `CrossEntropyLoss` for binary classification.')
out_features = 2
if in_features is not None:
self.linear = nn.Linear(in_features, out_features, bias=bias)
else:
self.linear = nn.LazyLinear(out_features, bias=bias)
self.in_features = in_features
self.out_features = out_features
self.temperature = temperature
self.eps = eps
self.bias = bias
self._device = device or 'cuda' if torch.cuda.is_available() else 'cpu'
self.multitarget = multitarget
self.to(self._device)
self.apply(self._init_weight)
def forward(self, features: Union[Dict[str, torch.Tensor], torch.Tensor], temperature: Optional[float]=None) -> Union[Dict[str, torch.Tensor], Tuple[torch.Tensor]]:
temperature = temperature or self.temperature
is_features_dict = False
if isinstance(features, dict):
assert 'sentence_embedding' in features
is_features_dict = True
x = features['sentence_embedding'] if is_features_dict else features
logits = self.linear(x)
logits = logits / (temperature + self.eps)
if self.multitarget:
probs = torch.sigmoid(logits)
else:
probs = nn.functional.softmax(logits, dim=-1)
if is_features_dict:
features.update({'logits': logits, 'probs': probs})
return features
return (logits, probs)
def predict_proba(self, x_test: torch.Tensor) -> torch.Tensor:
self.eval()
return self(x_test)[1]
def predict(self, x_test: torch.Tensor) -> torch.Tensor:
probs = self.predict_proba(x_test)
if self.multitarget:
return torch.where(probs >= 0.5, 1, 0)
return torch.argmax(probs, dim=-1)
def get_loss_fn(self) -> nn.Module:
if self.multitarget:
return torch.nn.BCEWithLogitsLoss()
return torch.nn.CrossEntropyLoss()
@property
def device(self) -> torch.device:
return next(self.parameters()).device
def get_config_dict(self) -> Dict[str, Optional[Union[int, float, bool]]]:
return {'in_features': self.in_features, 'out_features': self.out_features, 'temperature': self.temperature, 'bias': self.bias, 'device': self.device.type}
@staticmethod
def _init_weight(module) -> None:
if isinstance(module, nn.Linear):
nn.init.xavier_uniform_(module.weight)
if module.bias is not None:
nn.init.constant_(module.bias, 0.01)
def __repr__(self) -> str:
return 'SetFitHead({})'.format(self.get_config_dict())
class SetFitModel(ModelHubMixin):
def __init__(self, model_body: Optional[SentenceTransformer]=None, model_head: Optional[Union[SetFitHead, LogisticRegression]]=None, multi_target_strategy: Optional[str]=None, normalize_embeddings: bool=False, labels: Optional[List[str]]=None, model_card_data: Optional[SetFitModelCardData]=None, sentence_transformers_kwargs: Optional[Dict]=None, **kwargs) -> None:
super(SetFitModel, self).__init__()
self.model_body = model_body
self.model_head = model_head
self.multi_target_strategy = multi_target_strategy
self.normalize_embeddings = normalize_embeddings
self.labels = labels
self.model_card_data = model_card_data or SetFitModelCardData()
self.sentence_transformers_kwargs = sentence_transformers_kwargs or {}
self.attributes_to_save: Set[str] = {'normalize_embeddings', 'labels'}
self.model_card_data.register_model(self)
@property
def has_differentiable_head(self) -> bool:
return isinstance(self.model_head, nn.Module)
@property
def id2label(self) -> Dict[int, str]:
if self.labels is None:
return {}
return dict(enumerate(self.labels))
@property
def label2id(self) -> Dict[str, int]:
if self.labels is None:
return {}
return {label: idx for (idx, label) in enumerate(self.labels)}
def fit(self, x_train: List[str], y_train: Union[List[int], List[List[int]]], num_epochs: int, batch_size: Optional[int]=None, body_learning_rate: Optional[float]=None, head_learning_rate: Optional[float]=None, end_to_end: bool=False, l2_weight: Optional[float]=None, max_length: Optional[int]=None, show_progress_bar: bool=True) -> None:
if self.has_differentiable_head:
self.model_body.train()
self.model_head.train()
if not end_to_end:
self.freeze('body')
dataloader = self._prepare_dataloader(x_train, y_train, batch_size, max_length)
criterion = self.model_head.get_loss_fn()
optimizer = self._prepare_optimizer(head_learning_rate, body_learning_rate, l2_weight)
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=5, gamma=0.5)
for epoch_idx in trange(num_epochs, desc='Epoch', disable=not show_progress_bar):
for batch in tqdm(dataloader, desc='Iteration', disable=not show_progress_bar, leave=False):
(features, labels) = batch
optimizer.zero_grad()
features = {k: v.to(self.device) for (k, v) in features.items()}
labels = labels.to(self.device)
outputs = self.model_body(features)
if self.normalize_embeddings:
outputs['sentence_embedding'] = nn.functional.normalize(outputs['sentence_embedding'], p=2, dim=1)
outputs = self.model_head(outputs)
logits = outputs['logits']
loss: torch.Tensor = criterion(logits, labels)
loss.backward()
optimizer.step()
scheduler.step()
if not end_to_end:
self.unfreeze('body')
else:
embeddings = self.model_body.encode(x_train, normalize_embeddings=self.normalize_embeddings)
self.model_head.fit(embeddings, y_train)
if self.labels is None and self.multi_target_strategy is None:
try:
classes = self.model_head.classes_
if classes.dtype.char == 'U':
self.labels = classes.tolist()
except Exception:
pass
def _prepare_dataloader(self, x_train: List[str], y_train: Union[List[int], List[List[int]]], batch_size: Optional[int]=None, max_length: Optional[int]=None, shuffle: bool=True) -> DataLoader:
max_acceptable_length = self.model_body.get_max_seq_length()
if max_length is None:
max_length = max_acceptable_length
logger.warning(f'The `max_length` is `None`. Using the maximum acceptable length according to the current model body: {max_length}.')
if max_length > max_acceptable_length:
logger.warning(f'The specified `max_length`: {max_length} is greater than the maximum length of the current model body: {max_acceptable_length}. Using {max_acceptable_length} instead.')
max_length = max_acceptable_length
dataset = SetFitDataset(x_train, y_train, tokenizer=self.model_body.tokenizer, max_length=max_length)
dataloader = DataLoader(dataset, batch_size=batch_size, collate_fn=dataset.collate_fn, shuffle=shuffle, pin_memory=True)
return dataloader
def _prepare_optimizer(self, head_learning_rate: float, body_learning_rate: Optional[float], l2_weight: float) -> torch.optim.Optimizer:
body_learning_rate = body_learning_rate or head_learning_rate
l2_weight = l2_weight or 0.01
optimizer = torch.optim.AdamW([{'params': self.model_body.parameters(), 'lr': body_learning_rate, 'weight_decay': l2_weight}, {'params': self.model_head.parameters(), 'lr': head_learning_rate, 'weight_decay': l2_weight}])
return optimizer
def freeze(self, component: Optional[Literal['body', 'head']]=None) -> None:
if component is None or component == 'body':
self._freeze_or_not(self.model_body, to_freeze=True)
if (component is None or component == 'head') and self.has_differentiable_head:
self._freeze_or_not(self.model_head, to_freeze=True)
def unfreeze(self, component: Optional[Literal['body', 'head']]=None, keep_body_frozen: Optional[bool]=None) -> None:
if keep_body_frozen is not None:
warnings.warn('`keep_body_frozen` is deprecated and will be removed in v2.0.0 of SetFit. Please either pass "head", "body" or no arguments to unfreeze both.', DeprecationWarning, stacklevel=2)
if keep_body_frozen and (not component):
component = 'head'
if component is None or component == 'body':
self._freeze_or_not(self.model_body, to_freeze=False)
if (component is None or component == 'head') and self.has_differentiable_head:
self._freeze_or_not(self.model_head, to_freeze=False)
def _freeze_or_not(self, model: nn.Module, to_freeze: bool) -> None:
for param in model.parameters():
param.requires_grad = not to_freeze
def encode(self, inputs: List[str], batch_size: int=32, show_progress_bar: Optional[bool]=None) -> Union[torch.Tensor, np.ndarray]:
return self.model_body.encode(inputs, batch_size=batch_size, normalize_embeddings=self.normalize_embeddings, convert_to_tensor=self.has_differentiable_head, show_progress_bar=show_progress_bar)
def _output_type_conversion(self, outputs: Union[torch.Tensor, np.ndarray], as_numpy: bool=False) -> Union[torch.Tensor, np.ndarray]:
if as_numpy and self.has_differentiable_head:
outputs = outputs.detach().cpu().numpy()
elif not as_numpy and (not self.has_differentiable_head) and (outputs.dtype.char != 'U'):
outputs = torch.from_numpy(outputs)
return outputs
def predict_proba(self, inputs: Union[str, List[str]], batch_size: int=32, as_numpy: bool=False, show_progress_bar: Optional[bool]=None) -> Union[torch.Tensor, np.ndarray]:
is_singular = isinstance(inputs, str)
if is_singular:
inputs = [inputs]
embeddings = self.encode(inputs, batch_size=batch_size, show_progress_bar=show_progress_bar)
probs = self.model_head.predict_proba(embeddings)
if isinstance(probs, list):
if self.has_differentiable_head:
probs = torch.stack(probs, axis=1)
else:
probs = np.stack(probs, axis=1)
outputs = self._output_type_conversion(probs, as_numpy=as_numpy)
return outputs[0] if is_singular else outputs
def predict(self, inputs: Union[str, List[str]], batch_size: int=32, as_numpy: bool=False, use_labels: bool=True, show_progress_bar: Optional[bool]=None) -> Union[torch.Tensor, np.ndarray, List[str], int, str]:
is_singular = isinstance(inputs, str)
if is_singular:
inputs = [inputs]
embeddings = self.encode(inputs, batch_size=batch_size, show_progress_bar=show_progress_bar)
preds = self.model_head.predict(embeddings)
if use_labels and self.labels and (preds.ndim == 1) and (self.has_differentiable_head or preds.dtype.char != 'U'):
outputs = [self.labels[int(pred)] for pred in preds]
else:
outputs = self._output_type_conversion(preds, as_numpy=as_numpy)
return outputs[0] if is_singular else outputs
def __call__(self, inputs: Union[str, List[str]], batch_size: int=32, as_numpy: bool=False, use_labels: bool=True, show_progress_bar: Optional[bool]=None) -> Union[torch.Tensor, np.ndarray, List[str], int, str]:
return self.predict(inputs, batch_size=batch_size, as_numpy=as_numpy, use_labels=use_labels, show_progress_bar=show_progress_bar)
@property
def device(self) -> torch.device:
if parse(sentence_transformers_version) >= Version('2.3.0'):
return self.model_body.device
return self.model_body._target_device
def to(self, device: Union[str, torch.device]) -> 'SetFitModel':
if parse(sentence_transformers_version) < Version('2.3.0'):
self.model_body._target_device = device if isinstance(device, torch.device) else torch.device(device)
self.model_body = self.model_body.to(device)
if self.has_differentiable_head:
self.model_head = self.model_head.to(device)
return self
def create_model_card(self, path: str, model_name: Optional[str]='SetFit Model') -> None:
if not os.path.exists(path):
os.makedirs(path)
model_path = Path(model_name)
if self.model_card_data.model_id is None and model_path.exists() and (Path(tempfile.gettempdir()) in model_path.resolve().parents):
self.model_card_data.model_id = '/'.join(model_path.parts[-2:])
with open(os.path.join(path, 'README.md'), 'w', encoding='utf-8') as f:
f.write(self.generate_model_card())
def generate_model_card(self) -> str:
return generate_model_card(self)
def _save_pretrained(self, save_directory: Union[Path, str]) -> None:
save_directory = str(save_directory)
config_path = os.path.join(save_directory, CONFIG_NAME)
with open(config_path, 'w') as f:
json.dump({attr_name: getattr(self, attr_name) for attr_name in self.attributes_to_save if hasattr(self, attr_name)}, f, indent=2)
self.model_body.save(path=save_directory, create_model_card=False)
self.create_model_card(path=save_directory, model_name=save_directory)
if self.has_differentiable_head:
self.model_head.to('cpu')
joblib.dump(self.model_head, str(Path(save_directory) / MODEL_HEAD_NAME))
if self.has_differentiable_head:
self.model_head.to(self.device)
@classmethod
@validate_hf_hub_args
def _from_pretrained(cls, model_id: str, revision: Optional[str]=None, cache_dir: Optional[str]=None, force_download: Optional[bool]=None, proxies: Optional[Dict]=None, resume_download: Optional[bool]=None, local_files_only: Optional[bool]=None, token: Optional[Union[bool, str]]=None, multi_target_strategy: Optional[str]=None, use_differentiable_head: bool=False, device: Optional[Union[torch.device, str]]=None, trust_remote_code: bool=False, **model_kwargs) -> 'SetFitModel':
sentence_transformers_kwargs = {'cache_folder': cache_dir, 'use_auth_token': token, 'device': device, 'trust_remote_code': trust_remote_code}
if parse(sentence_transformers_version) >= Version('2.3.0'):
sentence_transformers_kwargs = {'cache_folder': cache_dir, 'token': token, 'device': device, 'trust_remote_code': trust_remote_code}
else:
if trust_remote_code:
raise ValueError('The `trust_remote_code` argument is only supported for `sentence-transformers` >= 2.3.0.')
sentence_transformers_kwargs = {'cache_folder': cache_dir, 'use_auth_token': token, 'device': device}
model_body = SentenceTransformer(model_id, **sentence_transformers_kwargs)
if parse(sentence_transformers_version) >= Version('2.3.0'):
device = model_body.device
else:
device = model_body._target_device
model_body.to(device)
config_file: Optional[str] = None
if os.path.isdir(model_id):
if CONFIG_NAME in os.listdir(model_id):
config_file = os.path.join(model_id, CONFIG_NAME)
else:
try:
config_file = hf_hub_download(repo_id=model_id, filename=CONFIG_NAME, revision=revision, cache_dir=cache_dir, force_download=force_download, proxies=proxies, resume_download=resume_download, token=token, local_files_only=local_files_only)
except requests.exceptions.RequestException:
pass
model_kwargs = {key: value for (key, value) in model_kwargs.items() if value is not None}
if config_file is not None:
with open(config_file, 'r', encoding='utf-8') as f:
config = json.load(f)
for (setting, value) in config.items():
if setting in model_kwargs:
if model_kwargs[setting] != value:
logger.warning(f'Overriding {setting} in model configuration from {value} to {model_kwargs[setting]}.')
else:
model_kwargs[setting] = value
if os.path.isdir(model_id):
if MODEL_HEAD_NAME in os.listdir(model_id):
model_head_file = os.path.join(model_id, MODEL_HEAD_NAME)
else:
logger.info(f'{MODEL_HEAD_NAME} not found in {Path(model_id).resolve()}, initialising classification head with random weights. You should TRAIN this model on a downstream task to use it for predictions and inference.')
model_head_file = None
else:
try:
model_head_file = hf_hub_download(repo_id=model_id, filename=MODEL_HEAD_NAME, revision=revision, cache_dir=cache_dir, force_download=force_download, proxies=proxies, resume_download=resume_download, token=token, local_files_only=local_files_only)
except requests.exceptions.RequestException:
logger.info(f'{MODEL_HEAD_NAME} not found on HuggingFace Hub, initialising classification head with random weights. You should TRAIN this model on a downstream task to use it for predictions and inference.')
model_head_file = None
model_card_data: SetFitModelCardData = model_kwargs.pop('model_card_data', SetFitModelCardData())
if model_head_file is not None:
model_head = joblib.load(model_head_file)
if isinstance(model_head, torch.nn.Module):
model_head.to(device)
model_card_data.infer_st_id(model_id)
else:
head_params = model_kwargs.pop('head_params', {})
if use_differentiable_head:
if multi_target_strategy is None:
use_multitarget = False
elif multi_target_strategy in ['one-vs-rest', 'multi-output']:
use_multitarget = True
else:
raise ValueError(f"multi_target_strategy '{multi_target_strategy}' is not supported for differentiable head")
base_head_params = {'in_features': model_body.get_sentence_embedding_dimension(), 'device': device, 'multitarget': use_multitarget}
model_head = SetFitHead(**{**head_params, **base_head_params})
else:
clf = LogisticRegression(**head_params)
if multi_target_strategy is not None:
if multi_target_strategy == 'one-vs-rest':
multilabel_classifier = OneVsRestClassifier(clf)
elif multi_target_strategy == 'multi-output':
multilabel_classifier = MultiOutputClassifier(clf)
elif multi_target_strategy == 'classifier-chain':
multilabel_classifier = ClassifierChain(clf)
else:
raise ValueError(f'multi_target_strategy {multi_target_strategy} is not supported.')
model_head = multilabel_classifier
else:
model_head = clf
model_card_data.set_st_id(model_id if '/' in model_id else f'sentence-transformers/{model_id}')
model_kwargs.pop('config', None)
return cls(model_body=model_body, model_head=model_head, multi_target_strategy=multi_target_strategy, model_card_data=model_card_data, sentence_transformers_kwargs=sentence_transformers_kwargs, **model_kwargs)
docstring = SetFitModel.from_pretrained.__doc__
cut_index = docstring.find('model_kwargs')
if cut_index != -1:
docstring = docstring[:cut_index] + 'labels (`List[str]`, *optional*):\n If the labels are integers ranging from `0` to `num_classes-1`, then these labels indicate\n the corresponding labels.\n model_card_data (`SetFitModelCardData`, *optional*):\n A `SetFitModelCardData` instance storing data such as model language, license, dataset name,\n etc. to be used in the automatically generated model cards.\n multi_target_strategy (`str`, *optional*):\n The strategy to use with multi-label classification. One of "one-vs-rest", "multi-output",\n or "classifier-chain".\n use_differentiable_head (`bool`, *optional*):\n Whether to load SetFit using a differentiable (i.e., Torch) head instead of Logistic Regression.\n normalize_embeddings (`bool`, *optional*):\n Whether to apply normalization on the embeddings produced by the Sentence Transformer body.\n device (`Union[torch.device, str]`, *optional*):\n The device on which to load the SetFit model, e.g. `"cuda:0"`, `"mps"` or `torch.device("cuda")`.\n trust_remote_code (`bool`, defaults to `False`): Whether or not to allow for custom Sentence Transformers\n models defined on the Hub in their own modeling files. This option should only be set to True for\n repositories you trust and in which you have read the code, as it will execute code present on\n the Hub on your local machine. Defaults to False.\n\n Example::\n\n >>> from setfit import SetFitModel\n >>> model = SetFitModel.from_pretrained(\n ... "sentence-transformers/paraphrase-mpnet-base-v2",\n ... labels=["positive", "negative"],\n ... )\n '
SetFitModel.from_pretrained = set_docstring(SetFitModel.from_pretrained, docstring)
SetFitModel.save_pretrained = copy_func(SetFitModel.save_pretrained)
SetFitModel.save_pretrained.__doc__ = SetFitModel.save_pretrained.__doc__.replace('~ModelHubMixin._from_pretrained', 'SetFitModel.push_to_hub')
# File: setfit-main/src/setfit/sampler.py
from itertools import zip_longest
from typing import Generator, Iterable, List, Optional
import numpy as np
import torch
from sentence_transformers import InputExample
from torch.utils.data import IterableDataset
from . import logging
logging.set_verbosity_info()
logger = logging.get_logger(__name__)
def shuffle_combinations(iterable: Iterable, replacement: bool=True) -> Generator:
n = len(iterable)
k = 1 if not replacement else 0
idxs = np.stack(np.triu_indices(n, k), axis=-1)
for i in np.random.RandomState(seed=42).permutation(len(idxs)):
(_idx, idx) = idxs[i, :]
yield (iterable[_idx], iterable[idx])
class ContrastiveDataset(IterableDataset):
def __init__(self, examples: List[InputExample], multilabel: bool, num_iterations: Optional[None]=None, sampling_strategy: str='oversampling', max_pairs: int=-1) -> None:
super().__init__()
self.pos_index = 0
self.neg_index = 0
self.pos_pairs = []
self.neg_pairs = []
self.sentences = np.array([s.texts[0] for s in examples])
self.labels = np.array([s.label for s in examples])
self.sentence_labels = list(zip(self.sentences, self.labels))
self.max_pairs = max_pairs
if multilabel:
self.generate_multilabel_pairs()
else:
self.generate_pairs()
if num_iterations is not None and num_iterations > 0:
self.len_pos_pairs = num_iterations * len(self.sentences)
self.len_neg_pairs = num_iterations * len(self.sentences)
elif sampling_strategy == 'unique':
self.len_pos_pairs = len(self.pos_pairs)
self.len_neg_pairs = len(self.neg_pairs)
elif sampling_strategy == 'undersampling':
self.len_pos_pairs = min(len(self.pos_pairs), len(self.neg_pairs))
self.len_neg_pairs = min(len(self.pos_pairs), len(self.neg_pairs))
elif sampling_strategy == 'oversampling':
self.len_pos_pairs = max(len(self.pos_pairs), len(self.neg_pairs))
self.len_neg_pairs = max(len(self.pos_pairs), len(self.neg_pairs))
else:
raise ValueError("Invalid sampling strategy. Must be one of 'unique', 'oversampling', or 'undersampling'.")
def generate_pairs(self) -> None:
for ((_text, _label), (text, label)) in shuffle_combinations(self.sentence_labels):
if _label == label:
self.pos_pairs.append(InputExample(texts=[_text, text], label=1.0))
else:
self.neg_pairs.append(InputExample(texts=[_text, text], label=0.0))
if self.max_pairs != -1 and len(self.pos_pairs) > self.max_pairs and (len(self.neg_pairs) > self.max_pairs):
break
def generate_multilabel_pairs(self) -> None:
for ((_text, _label), (text, label)) in shuffle_combinations(self.sentence_labels):
if any(np.logical_and(_label, label)):
self.pos_pairs.append(InputExample(texts=[_text, text], label=1.0))
else:
self.neg_pairs.append(InputExample(texts=[_text, text], label=0.0))
if self.max_pairs != -1 and len(self.pos_pairs) > self.max_pairs and (len(self.neg_pairs) > self.max_pairs):
break
def get_positive_pairs(self) -> List[InputExample]:
pairs = []
for _ in range(self.len_pos_pairs):
if self.pos_index >= len(self.pos_pairs):
self.pos_index = 0
pairs.append(self.pos_pairs[self.pos_index])
self.pos_index += 1
return pairs
def get_negative_pairs(self) -> List[InputExample]:
pairs = []
for _ in range(self.len_neg_pairs):
if self.neg_index >= len(self.neg_pairs):
self.neg_index = 0
pairs.append(self.neg_pairs[self.neg_index])
self.neg_index += 1
return pairs
def __iter__(self):
for (pos_pair, neg_pair) in zip_longest(self.get_positive_pairs(), self.get_negative_pairs()):
if pos_pair is not None:
yield pos_pair
if neg_pair is not None:
yield neg_pair
def __len__(self) -> int:
return self.len_pos_pairs + self.len_neg_pairs
class ContrastiveDistillationDataset(ContrastiveDataset):
def __init__(self, examples: List[InputExample], cos_sim_matrix: torch.Tensor, num_iterations: Optional[None]=None, sampling_strategy: str='oversampling', max_pairs: int=-1) -> None:
self.cos_sim_matrix = cos_sim_matrix
super().__init__(examples, multilabel=False, num_iterations=num_iterations, sampling_strategy=sampling_strategy, max_pairs=max_pairs)
self.sentence_labels = list(enumerate(self.sentences))
self.len_neg_pairs = 0
if num_iterations is not None and num_iterations > 0:
self.len_pos_pairs = num_iterations * len(self.sentences)
else:
self.len_pos_pairs = len(self.pos_pairs)
def generate_pairs(self) -> None:
for ((text_one, id_one), (text_two, id_two)) in shuffle_combinations(self.sentence_labels):
self.pos_pairs.append(InputExample(texts=[text_one, text_two], label=self.cos_sim_matrix[id_one][id_two]))
if self.max_pairs != -1 and len(self.pos_pairs) > self.max_pairs:
break
# File: setfit-main/src/setfit/span/aspect_extractor.py
from typing import TYPE_CHECKING, List, Tuple
if TYPE_CHECKING:
from spacy.tokens import Doc
class AspectExtractor:
def __init__(self, spacy_model: str) -> None:
super().__init__()
import spacy
self.nlp = spacy.load(spacy_model)
def find_groups(self, aspect_mask: List[bool]):
start = None
for (idx, flag) in enumerate(aspect_mask):
if flag:
if start is None:
start = idx
elif start is not None:
yield slice(start, idx)
start = None
if start is not None:
yield slice(start, idx + 1)
def __call__(self, texts: List[str]) -> Tuple[List['Doc'], List[slice]]:
aspects_list = []
docs = list(self.nlp.pipe(texts))
for doc in docs:
aspect_mask = [token.pos_ in ('NOUN', 'PROPN') for token in doc]
aspects_list.append(list(self.find_groups(aspect_mask)))
return (docs, aspects_list)
# File: setfit-main/src/setfit/span/modeling.py
import copy
import os
import re
import tempfile
import types
from collections import defaultdict
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple, Union
import torch
from datasets import Dataset
from huggingface_hub.utils import SoftTemporaryDirectory
from setfit.utils import set_docstring
from .. import logging
from ..modeling import SetFitModel
from .aspect_extractor import AspectExtractor
if TYPE_CHECKING:
from spacy.tokens import Doc
logger = logging.get_logger(__name__)
class SpanSetFitModel(SetFitModel):
def __init__(self, spacy_model: str='en_core_web_lg', span_context: int=0, **kwargs):
super().__init__(**kwargs)
self.spacy_model = spacy_model
self.span_context = span_context
self.attributes_to_save = {'normalize_embeddings', 'labels', 'span_context', 'spacy_model'}
def prepend_aspects(self, docs: List['Doc'], aspects_list: List[List[slice]]) -> Iterable[str]:
for (doc, aspects) in zip(docs, aspects_list):
for aspect_slice in aspects:
aspect = doc[max(aspect_slice.start - self.span_context, 0):aspect_slice.stop + self.span_context]
yield (aspect.text + ':' + doc.text)
def __call__(self, docs: List['Doc'], aspects_list: List[List[slice]]) -> List[bool]:
inputs_list = list(self.prepend_aspects(docs, aspects_list))
preds = self.predict(inputs_list, as_numpy=True)
iter_preds = iter(preds)
return [[next(iter_preds) for _ in aspects] for aspects in aspects_list]
def create_model_card(self, path: str, model_name: Optional[str]=None) -> None:
if not os.path.exists(path):
os.makedirs(path)
model_path = Path(model_name)
if model_path.exists() and Path(tempfile.gettempdir()) in model_path.resolve().parents:
model_name = '/'.join(model_path.parts[-2:])
is_aspect = isinstance(self, AspectModel)
aspect_model = 'setfit-absa-aspect'
polarity_model = 'setfit-absa-polarity'
if model_name is not None:
if is_aspect:
aspect_model = model_name
if model_name.endswith('-aspect'):
polarity_model = model_name[:-len('-aspect')] + '-polarity'
else:
polarity_model = model_name
if model_name.endswith('-polarity'):
aspect_model = model_name[:-len('-polarity')] + '-aspect'
if self.model_card_data.absa is None and self.model_card_data.model_name:
from spacy import __version__ as spacy_version
self.model_card_data.model_name = self.model_card_data.model_name.replace('SetFit', 'SetFit Aspect Model' if is_aspect else 'SetFit Polarity Model', 1)
self.model_card_data.tags.insert(1, 'absa')
self.model_card_data.version['spacy'] = spacy_version
self.model_card_data.absa = {'is_absa': True, 'is_aspect': is_aspect, 'spacy_model': self.spacy_model, 'aspect_model': aspect_model, 'polarity_model': polarity_model}
if self.model_card_data.task_name is None:
self.model_card_data.task_name = 'Aspect Based Sentiment Analysis (ABSA)'
self.model_card_data.inference = False
with open(os.path.join(path, 'README.md'), 'w', encoding='utf-8') as f:
f.write(self.generate_model_card())
docstring = SpanSetFitModel.from_pretrained.__doc__
cut_index = docstring.find('multi_target_strategy')
if cut_index != -1:
docstring = docstring[:cut_index] + 'model_card_data (`SetFitModelCardData`, *optional*):\n A `SetFitModelCardData` instance storing data such as model language, license, dataset name,\n etc. to be used in the automatically generated model cards.\n use_differentiable_head (`bool`, *optional*):\n Whether to load SetFit using a differentiable (i.e., Torch) head instead of Logistic Regression.\n normalize_embeddings (`bool`, *optional*):\n Whether to apply normalization on the embeddings produced by the Sentence Transformer body.\n span_context (`int`, defaults to `0`):\n The number of words before and after the span candidate that should be prepended to the full sentence.\n By default, 0 for Aspect models and 3 for Polarity models.\n device (`Union[torch.device, str]`, *optional*):\n The device on which to load the SetFit model, e.g. `"cuda:0"`, `"mps"` or `torch.device("cuda")`.'
SpanSetFitModel.from_pretrained = set_docstring(SpanSetFitModel.from_pretrained, docstring, cls=SpanSetFitModel)
class AspectModel(SpanSetFitModel):
def __call__(self, docs: List['Doc'], aspects_list: List[List[slice]]) -> List[bool]:
sentence_preds = super().__call__(docs, aspects_list)
return [[aspect for (aspect, pred) in zip(aspects, preds) if pred == 'aspect'] for (aspects, preds) in zip(aspects_list, sentence_preds)]
AspectModel.from_pretrained = types.MethodType(AspectModel.from_pretrained.__func__, AspectModel)
class PolarityModel(SpanSetFitModel):
def __init__(self, span_context: int=3, **kwargs):
super().__init__(**kwargs)
self.span_context = span_context
PolarityModel.from_pretrained = types.MethodType(PolarityModel.from_pretrained.__func__, PolarityModel)
@dataclass
class AbsaModel:
aspect_extractor: AspectExtractor
aspect_model: AspectModel
polarity_model: PolarityModel
def gold_aspect_spans_to_aspects_list(self, inputs: Dataset) -> List[List[slice]]:
grouped_data = defaultdict(list)
for sample in inputs:
text = sample.pop('text')
grouped_data[text].append(sample)
(docs, _) = self.aspect_extractor(grouped_data.keys())
aspects_list = []
index = -1
skipped_indices = []
for (doc, samples) in zip(docs, grouped_data.values()):
aspects_list.append([])
for sample in samples:
index += 1
match_objects = re.finditer(re.escape(sample['span']), doc.text)
for (i, match) in enumerate(match_objects):
if i == sample['ordinal']:
char_idx_start = match.start()
char_idx_end = match.end()
span = doc.char_span(char_idx_start, char_idx_end)
if span is None:
logger.warning(f"Aspect term {sample['span']!r} with ordinal {sample['ordinal']}, isn't a token in {doc.text!r} according to spaCy. Skipping this sample.")
skipped_indices.append(index)
continue
aspects_list[-1].append(slice(span.start, span.end))
return (docs, aspects_list, skipped_indices)
def predict_dataset(self, inputs: Dataset) -> Dataset:
if set(inputs.column_names) >= {'text', 'span', 'ordinal'}:
pass
elif set(inputs.column_names) >= {'text', 'span'}:
inputs = inputs.add_column('ordinal', [0] * len(inputs))
else:
raise ValueError(f'`inputs` must be either a `str`, a `List[str]`, or a `datasets.Dataset` with columns `text` and `span` and optionally `ordinal`. Found a dataset with these columns: {inputs.column_names}.')
if 'pred_polarity' in inputs.column_names:
raise ValueError('`predict_dataset` wants to add a `pred_polarity` column, but the input dataset already contains that column.')
(docs, aspects_list, skipped_indices) = self.gold_aspect_spans_to_aspects_list(inputs)
polarity_list = sum(self.polarity_model(docs, aspects_list), [])
for index in skipped_indices:
polarity_list.insert(index, None)
return inputs.add_column('pred_polarity', polarity_list)
def predict(self, inputs: Union[str, List[str], Dataset]) -> Union[List[Dict[str, Any]], Dataset]:
if isinstance(inputs, Dataset):
return self.predict_dataset(inputs)
is_str = isinstance(inputs, str)
inputs_list = [inputs] if is_str else inputs
(docs, aspects_list) = self.aspect_extractor(inputs_list)
if sum(aspects_list, []) == []:
return aspects_list
aspects_list = self.aspect_model(docs, aspects_list)
if sum(aspects_list, []) == []:
return aspects_list
polarity_list = self.polarity_model(docs, aspects_list)
outputs = []
for (docs, aspects, polarities) in zip(docs, aspects_list, polarity_list):
outputs.append([{'span': docs[aspect_slice].text, 'polarity': polarity} for (aspect_slice, polarity) in zip(aspects, polarities)])
return outputs if not is_str else outputs[0]
@property
def device(self) -> torch.device:
return self.aspect_model.device
def to(self, device: Union[str, torch.device]) -> 'AbsaModel':
self.aspect_model.to(device)
self.polarity_model.to(device)
def __call__(self, inputs: Union[str, List[str]]) -> List[Dict[str, Any]]:
return self.predict(inputs)
def save_pretrained(self, save_directory: Union[str, Path], polarity_save_directory: Optional[Union[str, Path]]=None, push_to_hub: bool=False, **kwargs) -> None:
if polarity_save_directory is None:
base_save_directory = Path(save_directory)
save_directory = base_save_directory.parent / (base_save_directory.name + '-aspect')
polarity_save_directory = base_save_directory.parent / (base_save_directory.name + '-polarity')
self.aspect_model.save_pretrained(save_directory=save_directory, push_to_hub=push_to_hub, **kwargs)
self.polarity_model.save_pretrained(save_directory=polarity_save_directory, push_to_hub=push_to_hub, **kwargs)
@classmethod
def from_pretrained(cls, model_id: str, polarity_model_id: Optional[str]=None, spacy_model: Optional[str]=None, span_contexts: Tuple[Optional[int], Optional[int]]=(None, None), force_download: bool=None, resume_download: bool=None, proxies: Optional[Dict]=None, token: Optional[Union[str, bool]]=None, cache_dir: Optional[str]=None, local_files_only: bool=None, use_differentiable_head: bool=None, normalize_embeddings: bool=None, **model_kwargs) -> 'AbsaModel':
revision = None
if len(model_id.split('@')) == 2:
(model_id, revision) = model_id.split('@')
if spacy_model:
model_kwargs['spacy_model'] = spacy_model
aspect_model = AspectModel.from_pretrained(model_id, span_context=span_contexts[0], revision=revision, force_download=force_download, resume_download=resume_download, proxies=proxies, token=token, cache_dir=cache_dir, local_files_only=local_files_only, use_differentiable_head=use_differentiable_head, normalize_embeddings=normalize_embeddings, labels=['no aspect', 'aspect'], **model_kwargs)
if polarity_model_id:
model_id = polarity_model_id
revision = None
if len(model_id.split('@')) == 2:
(model_id, revision) = model_id.split('@')
model_card_data = model_kwargs.pop('model_card_data', None)
if model_card_data:
model_kwargs['model_card_data'] = copy.deepcopy(model_card_data)
polarity_model = PolarityModel.from_pretrained(model_id, span_context=span_contexts[1], revision=revision, force_download=force_download, resume_download=resume_download, proxies=proxies, token=token, cache_dir=cache_dir, local_files_only=local_files_only, use_differentiable_head=use_differentiable_head, normalize_embeddings=normalize_embeddings, **model_kwargs)
if aspect_model.spacy_model != polarity_model.spacy_model:
logger.warning(f'The Aspect and Polarity models are configured to use different spaCy models:\n* {repr(aspect_model.spacy_model)} for the aspect model, and\n* {repr(polarity_model.spacy_model)} for the polarity model.\nThis model will use {repr(aspect_model.spacy_model)}.')
aspect_extractor = AspectExtractor(spacy_model=aspect_model.spacy_model)
return cls(aspect_extractor, aspect_model, polarity_model)
def push_to_hub(self, repo_id: str, polarity_repo_id: Optional[str]=None, **kwargs) -> None:
if '/' not in repo_id:
raise ValueError('`repo_id` must be a full repository ID, including organisation, e.g. "tomaarsen/setfit-absa-restaurant".')
if polarity_repo_id is not None and '/' not in polarity_repo_id:
raise ValueError('`polarity_repo_id` must be a full repository ID, including organisation, e.g. "tomaarsen/setfit-absa-restaurant".')
commit_message = kwargs.pop('commit_message', 'Add SetFit ABSA model')
with SoftTemporaryDirectory() as tmp_dir:
save_directory = Path(tmp_dir) / repo_id
polarity_save_directory = None if polarity_repo_id is None else Path(tmp_dir) / polarity_repo_id
self.save_pretrained(save_directory=save_directory, polarity_save_directory=polarity_save_directory, push_to_hub=True, commit_message=commit_message, **kwargs)
# File: setfit-main/src/setfit/span/trainer.py
from collections import defaultdict
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union
from datasets import Dataset
from transformers.trainer_callback import TrainerCallback
from setfit.span.modeling import AbsaModel, AspectModel, PolarityModel
from setfit.training_args import TrainingArguments
from .. import logging
from ..trainer import ColumnMappingMixin, Trainer
if TYPE_CHECKING:
import optuna
logger = logging.get_logger(__name__)
class AbsaTrainer(ColumnMappingMixin):
_REQUIRED_COLUMNS = {'text', 'span', 'label', 'ordinal'}
def __init__(self, model: AbsaModel, args: Optional[TrainingArguments]=None, polarity_args: Optional[TrainingArguments]=None, train_dataset: Optional['Dataset']=None, eval_dataset: Optional['Dataset']=None, metric: Union[str, Callable[['Dataset', 'Dataset'], Dict[str, float]]]='accuracy', metric_kwargs: Optional[Dict[str, Any]]=None, callbacks: Optional[List[TrainerCallback]]=None, column_mapping: Optional[Dict[str, str]]=None) -> None:
self.model = model
self.aspect_extractor = model.aspect_extractor
if train_dataset is not None and column_mapping:
train_dataset = self._apply_column_mapping(train_dataset, column_mapping)
(aspect_train_dataset, polarity_train_dataset) = self.preprocess_dataset(model.aspect_model, model.polarity_model, train_dataset)
if eval_dataset is not None and column_mapping:
eval_dataset = self._apply_column_mapping(eval_dataset, column_mapping)
(aspect_eval_dataset, polarity_eval_dataset) = self.preprocess_dataset(model.aspect_model, model.polarity_model, eval_dataset)
self.aspect_trainer = Trainer(model.aspect_model, args=args, train_dataset=aspect_train_dataset, eval_dataset=aspect_eval_dataset, metric=metric, metric_kwargs=metric_kwargs, callbacks=callbacks)
self.aspect_trainer._set_logs_mapper({'eval_embedding_loss': 'eval_aspect_embedding_loss', 'embedding_loss': 'aspect_embedding_loss'})
self.polarity_trainer = Trainer(model.polarity_model, args=polarity_args or args, train_dataset=polarity_train_dataset, eval_dataset=polarity_eval_dataset, metric=metric, metric_kwargs=metric_kwargs, callbacks=callbacks)
self.polarity_trainer._set_logs_mapper({'eval_embedding_loss': 'eval_polarity_embedding_loss', 'embedding_loss': 'polarity_embedding_loss'})
def preprocess_dataset(self, aspect_model: AspectModel, polarity_model: PolarityModel, dataset: Dataset) -> Dataset:
if dataset is None:
return (dataset, dataset)
grouped_data = defaultdict(list)
for sample in dataset:
text = sample.pop('text')
grouped_data[text].append(sample)
def index_ordinal(text: str, target: str, ordinal: int) -> Tuple[int, int]:
find_from = 0
for _ in range(ordinal + 1):
start_idx = text.index(target, find_from)
find_from = start_idx + 1
return (start_idx, start_idx + len(target))
def overlaps(aspect: slice, aspects: List[slice]) -> bool:
for test_aspect in aspects:
overlapping_indices = set(range(aspect.start, aspect.stop + 1)) & set(range(test_aspect.start, test_aspect.stop + 1))
if overlapping_indices:
return True
return False
(docs, aspects_list) = self.aspect_extractor(grouped_data.keys())
aspect_aspect_list = []
aspect_labels = []
polarity_aspect_list = []
polarity_labels = []
for (doc, aspects, text) in zip(docs, aspects_list, grouped_data):
gold_aspects = []
gold_polarity_labels = []
for annotation in grouped_data[text]:
try:
(start, end) = index_ordinal(text, annotation['span'], annotation['ordinal'])
except ValueError:
logger.info(f"The ordinal of {annotation['ordinal']} for span {annotation['span']!r} in {text!r} is too high. Skipping this sample.")
continue
gold_aspect_span = doc.char_span(start, end)
if gold_aspect_span is None:
continue
gold_aspects.append(slice(gold_aspect_span.start, gold_aspect_span.end))
gold_polarity_labels.append(annotation['label'])
aspect_labels.extend([True] * len(gold_aspects))
aspect_aspect_list.append(gold_aspects[:])
for aspect in aspects:
if not overlaps(aspect, gold_aspects):
aspect_labels.append(False)
aspect_aspect_list[-1].append(aspect)
polarity_labels.extend(gold_polarity_labels)
polarity_aspect_list.append(gold_aspects)
aspect_texts = list(aspect_model.prepend_aspects(docs, aspect_aspect_list))
polarity_texts = list(polarity_model.prepend_aspects(docs, polarity_aspect_list))
return (Dataset.from_dict({'text': aspect_texts, 'label': aspect_labels}), Dataset.from_dict({'text': polarity_texts, 'label': polarity_labels}))
def train(self, args: Optional[TrainingArguments]=None, polarity_args: Optional[TrainingArguments]=None, trial: Optional[Union['optuna.Trial', Dict[str, Any]]]=None, **kwargs) -> None:
self.train_aspect(args=args, trial=trial, **kwargs)
self.train_polarity(args=polarity_args, trial=trial, **kwargs)
def train_aspect(self, args: Optional[TrainingArguments]=None, trial: Optional[Union['optuna.Trial', Dict[str, Any]]]=None, **kwargs) -> None:
self.aspect_trainer.train(args=args, trial=trial, **kwargs)
def train_polarity(self, args: Optional[TrainingArguments]=None, trial: Optional[Union['optuna.Trial', Dict[str, Any]]]=None, **kwargs) -> None:
self.polarity_trainer.train(args=args, trial=trial, **kwargs)
def add_callback(self, callback: Union[type, TrainerCallback]) -> None:
self.aspect_trainer.add_callback(callback)
self.polarity_trainer.add_callback(callback)
def pop_callback(self, callback: Union[type, TrainerCallback]) -> Tuple[TrainerCallback, TrainerCallback]:
return (self.aspect_trainer.pop_callback(callback), self.polarity_trainer.pop_callback(callback))
def remove_callback(self, callback: Union[type, TrainerCallback]) -> None:
self.aspect_trainer.remove_callback(callback)
self.polarity_trainer.remove_callback(callback)
def push_to_hub(self, repo_id: str, polarity_repo_id: Optional[str]=None, **kwargs) -> None:
return self.model.push_to_hub(repo_id=repo_id, polarity_repo_id=polarity_repo_id, **kwargs)
def evaluate(self, dataset: Optional[Dataset]=None) -> Dict[str, Dict[str, float]]:
aspect_eval_dataset = polarity_eval_dataset = None
if dataset:
(aspect_eval_dataset, polarity_eval_dataset) = self.preprocess_dataset(self.model.aspect_model, self.model.polarity_model, dataset)
return {'aspect': self.aspect_trainer.evaluate(aspect_eval_dataset), 'polarity': self.polarity_trainer.evaluate(polarity_eval_dataset)}
# File: setfit-main/src/setfit/trainer.py
import math
import os
import shutil
import time
import warnings
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Literal, Optional, Tuple, Union
import evaluate
import torch
from datasets import Dataset, DatasetDict
from sentence_transformers import InputExample, SentenceTransformer, losses
from sentence_transformers.datasets import SentenceLabelDataset
from sentence_transformers.losses.BatchHardTripletLoss import BatchHardTripletLossDistanceFunction
from sentence_transformers.util import batch_to_device
from sklearn.preprocessing import LabelEncoder
from torch import nn
from torch.cuda.amp import autocast
from torch.utils.data import DataLoader
from tqdm.autonotebook import tqdm
from transformers.integrations import WandbCallback, get_reporting_integration_callbacks
from transformers.trainer_callback import CallbackHandler, DefaultFlowCallback, IntervalStrategy, PrinterCallback, ProgressCallback, TrainerCallback, TrainerControl, TrainerState
from transformers.trainer_utils import HPSearchBackend, default_compute_objective, number_of_arguments, set_seed, speed_metrics
from transformers.utils.import_utils import is_in_notebook
from setfit.model_card import ModelCardCallback
from . import logging
from .integrations import default_hp_search_backend, is_optuna_available, run_hp_search_optuna
from .losses import SupConLoss
from .sampler import ContrastiveDataset
from .training_args import TrainingArguments
from .utils import BestRun, default_hp_space_optuna
if TYPE_CHECKING:
import optuna
from .modeling import SetFitModel
logging.set_verbosity_info()
logger = logging.get_logger(__name__)
DEFAULT_CALLBACKS = [DefaultFlowCallback]
DEFAULT_PROGRESS_CALLBACK = ProgressCallback
if is_in_notebook():
from transformers.utils.notebook import NotebookProgressCallback
DEFAULT_PROGRESS_CALLBACK = NotebookProgressCallback
class ColumnMappingMixin:
_REQUIRED_COLUMNS = {'text', 'label'}
def _validate_column_mapping(self, dataset: 'Dataset') -> None:
column_names = set(dataset.column_names)
if self.column_mapping is None and (not self._REQUIRED_COLUMNS.issubset(column_names)):
if column_names == {'train'} and isinstance(dataset, DatasetDict):
raise ValueError("SetFit expected a Dataset, but it got a DatasetDict with the split ['train']. Did you mean to select the training split with dataset['train']?")
elif isinstance(dataset, DatasetDict):
raise ValueError(f'SetFit expected a Dataset, but it got a DatasetDict with the splits {sorted(column_names)}. Did you mean to select one of these splits from the dataset?')
else:
raise ValueError(f'SetFit expected the dataset to have the columns {sorted(self._REQUIRED_COLUMNS)}, but only the columns {sorted(column_names)} were found. Either make sure these columns are present, or specify which columns to use with column_mapping in Trainer.')
if self.column_mapping is not None:
missing_columns = set(self._REQUIRED_COLUMNS)
missing_columns -= set(self.column_mapping.values())
missing_columns -= set(dataset.column_names) - set(self.column_mapping.keys())
if missing_columns:
raise ValueError(f'The following columns are missing from the column mapping: {missing_columns}. Please provide a mapping for all required columns.')
if not set(self.column_mapping.keys()).issubset(column_names):
raise ValueError(f'The column mapping expected the columns {sorted(self.column_mapping.keys())} in the dataset, but the dataset had the columns {sorted(column_names)}.')
def _apply_column_mapping(self, dataset: 'Dataset', column_mapping: Dict[str, str]) -> 'Dataset':
dataset = dataset.rename_columns({**column_mapping, **{col: f'feat_{col}' for col in dataset.column_names if col not in column_mapping and col not in self._REQUIRED_COLUMNS}})
dset_format = dataset.format
dataset = dataset.with_format(type=dset_format['type'], columns=dataset.column_names, output_all_columns=dset_format['output_all_columns'], **dset_format['format_kwargs'])
return dataset
class Trainer(ColumnMappingMixin):
def __init__(self, model: Optional['SetFitModel']=None, args: Optional[TrainingArguments]=None, train_dataset: Optional['Dataset']=None, eval_dataset: Optional['Dataset']=None, model_init: Optional[Callable[[], 'SetFitModel']]=None, metric: Union[str, Callable[['Dataset', 'Dataset'], Dict[str, float]]]='accuracy', metric_kwargs: Optional[Dict[str, Any]]=None, callbacks: Optional[List[TrainerCallback]]=None, column_mapping: Optional[Dict[str, str]]=None) -> None:
if args is not None and (not isinstance(args, TrainingArguments)):
raise ValueError('`args` must be a `TrainingArguments` instance imported from `setfit`.')
self.args = args or TrainingArguments()
self.column_mapping = column_mapping
if train_dataset:
self._validate_column_mapping(train_dataset)
if self.column_mapping is not None:
logger.info('Applying column mapping to the training dataset')
train_dataset = self._apply_column_mapping(train_dataset, self.column_mapping)
self.train_dataset = train_dataset
if eval_dataset:
self._validate_column_mapping(eval_dataset)
if self.column_mapping is not None:
logger.info('Applying column mapping to the evaluation dataset')
eval_dataset = self._apply_column_mapping(eval_dataset, self.column_mapping)
self.eval_dataset = eval_dataset
self.model_init = model_init
self.metric = metric
self.metric_kwargs = metric_kwargs
self.logs_mapper = {}
set_seed(12)
if model is None:
if model_init is not None:
model = self.call_model_init()
else:
raise RuntimeError('`Trainer` requires either a `model` or `model_init` argument.')
elif model_init is not None:
raise RuntimeError('`Trainer` requires either a `model` or `model_init` argument, but not both.')
self.model = model
self.hp_search_backend = None
default_callbacks = DEFAULT_CALLBACKS + get_reporting_integration_callbacks(self.args.report_to)
callbacks = default_callbacks if callbacks is None else default_callbacks + callbacks
if WandbCallback in callbacks:
os.environ.setdefault('WANDB_PROJECT', 'setfit')
self.callback_handler = CallbackHandler(callbacks, self.model, self.model.model_body.tokenizer, None, None)
self.state = TrainerState()
self.control = TrainerControl()
self.add_callback(DEFAULT_PROGRESS_CALLBACK if self.args.show_progress_bar else PrinterCallback)
self.control = self.callback_handler.on_init_end(self.args, self.state, self.control)
self.add_callback(ModelCardCallback(self))
self.callback_handler.on_init_end(args, self.state, self.control)
def add_callback(self, callback: Union[type, TrainerCallback]) -> None:
self.callback_handler.add_callback(callback)
def pop_callback(self, callback: Union[type, TrainerCallback]) -> TrainerCallback:
return self.callback_handler.pop_callback(callback)
def remove_callback(self, callback: Union[type, TrainerCallback]) -> None:
self.callback_handler.remove_callback(callback)
def apply_hyperparameters(self, params: Dict[str, Any], final_model: bool=False) -> None:
if self.args is not None:
self.args = self.args.update(params, ignore_extra=True)
else:
self.args = TrainingArguments.from_dict(params, ignore_extra=True)
set_seed(self.args.seed)
self.model = self.model_init(params)
if final_model:
self.model_init = None
def _hp_search_setup(self, trial: Union['optuna.Trial', Dict[str, Any]]) -> None:
if self.hp_search_backend is None or trial is None:
return
if isinstance(trial, Dict):
params = trial
elif self.hp_search_backend == HPSearchBackend.OPTUNA:
params = self.hp_space(trial)
else:
raise ValueError('Invalid trial parameter')
logger.info(f'Trial: {params}')
self.apply_hyperparameters(params, final_model=False)
def call_model_init(self, params: Optional[Dict[str, Any]]=None) -> 'SetFitModel':
model_init_argcount = number_of_arguments(self.model_init)
if model_init_argcount == 0:
model = self.model_init()
elif model_init_argcount == 1:
model = self.model_init(params)
else:
raise RuntimeError('`model_init` should have 0 or 1 argument.')
if model is None:
raise RuntimeError('`model_init` should not return None.')
return model
def freeze(self, component: Optional[Literal['body', 'head']]=None) -> None:
warnings.warn(f'`{self.__class__.__name__}.freeze` is deprecated and will be removed in v2.0.0 of SetFit. Please use `SetFitModel.freeze` directly instead.', DeprecationWarning, stacklevel=2)
return self.model.freeze(component)
def unfreeze(self, component: Optional[Literal['body', 'head']]=None, keep_body_frozen: Optional[bool]=None) -> None:
warnings.warn(f'`{self.__class__.__name__}.unfreeze` is deprecated and will be removed in v2.0.0 of SetFit. Please use `SetFitModel.unfreeze` directly instead.', DeprecationWarning, stacklevel=2)
return self.model.unfreeze(component, keep_body_frozen=keep_body_frozen)
def train(self, args: Optional[TrainingArguments]=None, trial: Optional[Union['optuna.Trial', Dict[str, Any]]]=None, **kwargs) -> None:
if len(kwargs):
warnings.warn(f'`{self.__class__.__name__}.train` does not accept keyword arguments anymore. Please provide training arguments via a `TrainingArguments` instance to the `{self.__class__.__name__}` initialisation or the `{self.__class__.__name__}.train` method.', DeprecationWarning, stacklevel=2)
if trial:
self._hp_search_setup(trial)
args = args or self.args or TrainingArguments()
if self.train_dataset is None:
raise ValueError(f'Training requires a `train_dataset` given to the `{self.__class__.__name__}` initialization.')
train_parameters = self.dataset_to_parameters(self.train_dataset)
full_parameters = train_parameters + self.dataset_to_parameters(self.eval_dataset) if self.eval_dataset else train_parameters
self.train_embeddings(*full_parameters, args=args)
self.train_classifier(*train_parameters, args=args)
def dataset_to_parameters(self, dataset: Dataset) -> List[Iterable]:
return [dataset['text'], dataset['label']]
def train_embeddings(self, x_train: List[str], y_train: Optional[Union[List[int], List[List[int]]]]=None, x_eval: Optional[List[str]]=None, y_eval: Optional[Union[List[int], List[List[int]]]]=None, args: Optional[TrainingArguments]=None) -> None:
args = args or self.args or TrainingArguments()
self.state.logging_steps = args.logging_steps
self.state.eval_steps = args.eval_steps
self.state.save_steps = args.save_steps
self.state.global_step = 0
self.state.total_flos = 0
train_max_pairs = -1 if args.max_steps == -1 else args.max_steps * args.embedding_batch_size
(train_dataloader, loss_func, batch_size, num_unique_pairs) = self.get_dataloader(x_train, y_train, args=args, max_pairs=train_max_pairs)
if x_eval is not None and args.eval_strategy != IntervalStrategy.NO:
eval_max_pairs = -1 if args.eval_max_steps == -1 else args.eval_max_steps * args.embedding_batch_size
(eval_dataloader, _, _, _) = self.get_dataloader(x_eval, y_eval, args=args, max_pairs=eval_max_pairs)
else:
eval_dataloader = None
total_train_steps = len(train_dataloader) * args.embedding_num_epochs
if args.max_steps > 0:
total_train_steps = min(args.max_steps, total_train_steps)
logger.info('***** Running training *****')
logger.info(f' Num unique pairs = {num_unique_pairs}')
logger.info(f' Batch size = {batch_size}')
logger.info(f' Num epochs = {args.embedding_num_epochs}')
logger.info(f' Total optimization steps = {total_train_steps}')
warmup_steps = math.ceil(total_train_steps * args.warmup_proportion)
self._train_sentence_transformer(self.model.model_body, train_dataloader=train_dataloader, eval_dataloader=eval_dataloader, args=args, loss_func=loss_func, warmup_steps=warmup_steps)
def get_dataloader(self, x: List[str], y: Union[List[int], List[List[int]]], args: TrainingArguments, max_pairs: int=-1) -> Tuple[DataLoader, nn.Module, int, int]:
input_data = [InputExample(texts=[text], label=label) for (text, label) in zip(x, y)]
if args.loss in [losses.BatchAllTripletLoss, losses.BatchHardTripletLoss, losses.BatchSemiHardTripletLoss, losses.BatchHardSoftMarginTripletLoss, SupConLoss]:
data_sampler = SentenceLabelDataset(input_data, samples_per_label=args.samples_per_label)
batch_size = min(args.embedding_batch_size, len(data_sampler))
dataloader = DataLoader(data_sampler, batch_size=batch_size, drop_last=True)
if args.loss is losses.BatchHardSoftMarginTripletLoss:
loss = args.loss(model=self.model.model_body, distance_metric=args.distance_metric)
elif args.loss is SupConLoss:
loss = args.loss(model=self.model.model_body)
else:
loss = args.loss(model=self.model.model_body, distance_metric=args.distance_metric, margin=args.margin)
else:
data_sampler = ContrastiveDataset(input_data, self.model.multi_target_strategy, args.num_iterations, args.sampling_strategy, max_pairs=max_pairs)
batch_size = min(args.embedding_batch_size, len(data_sampler))
dataloader = DataLoader(data_sampler, batch_size=batch_size, drop_last=False)
loss = args.loss(self.model.model_body)
return (dataloader, loss, batch_size, len(data_sampler))
def log(self, args: TrainingArguments, logs: Dict[str, float]) -> None:
logs = {self.logs_mapper.get(key, key): value for (key, value) in logs.items()}
if self.state.epoch is not None:
logs['epoch'] = round(self.state.epoch, 2)
output = {**logs, **{'step': self.state.global_step}}
self.state.log_history.append(output)
return self.callback_handler.on_log(args, self.state, self.control, logs)
def _set_logs_mapper(self, logs_mapper: Dict[str, str]) -> None:
self.logs_mapper = logs_mapper
def _train_sentence_transformer(self, model_body: SentenceTransformer, train_dataloader: DataLoader, eval_dataloader: Optional[DataLoader], args: TrainingArguments, loss_func: nn.Module, warmup_steps: int=10000) -> None:
max_grad_norm = 1
weight_decay = 0.01
self.state.epoch = 0
start_time = time.time()
if args.max_steps > 0:
self.state.max_steps = args.max_steps
else:
self.state.max_steps = len(train_dataloader) * args.embedding_num_epochs
self.control = self.callback_handler.on_train_begin(args, self.state, self.control)
steps_per_epoch = len(train_dataloader)
if args.use_amp:
scaler = torch.cuda.amp.GradScaler()
model_body.to(self.model.device)
loss_func.to(self.model.device)
train_dataloader.collate_fn = model_body.smart_batching_collate
if eval_dataloader:
eval_dataloader.collate_fn = model_body.smart_batching_collate
param_optimizer = list(loss_func.named_parameters())
no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
optimizer_grouped_parameters = [{'params': [p for (n, p) in param_optimizer if not any((nd in n for nd in no_decay))], 'weight_decay': weight_decay}, {'params': [p for (n, p) in param_optimizer if any((nd in n for nd in no_decay))], 'weight_decay': 0.0}]
optimizer = torch.optim.AdamW(optimizer_grouped_parameters, **{'lr': args.body_embedding_learning_rate})
scheduler_obj = model_body._get_scheduler(optimizer, scheduler='WarmupLinear', warmup_steps=warmup_steps, t_total=self.state.max_steps)
self.callback_handler.optimizer = optimizer
self.callback_handler.lr_scheduler = scheduler_obj
self.callback_handler.train_dataloader = train_dataloader
self.callback_handler.eval_dataloader = eval_dataloader
self.callback_handler.on_train_begin(args, self.state, self.control)
data_iterator = iter(train_dataloader)
skip_scheduler = False
for epoch in range(args.embedding_num_epochs):
self.control = self.callback_handler.on_epoch_begin(args, self.state, self.control)
loss_func.zero_grad()
loss_func.train()
for step in range(steps_per_epoch):
self.control = self.callback_handler.on_step_begin(args, self.state, self.control)
try:
data = next(data_iterator)
except StopIteration:
data_iterator = iter(train_dataloader)
data = next(data_iterator)
(features, labels) = data
labels = labels.to(self.model.device)
features = list(map(lambda batch: batch_to_device(batch, self.model.device), features))
if args.use_amp:
with autocast():
loss_value = loss_func(features, labels)
scale_before_step = scaler.get_scale()
scaler.scale(loss_value).backward()
scaler.unscale_(optimizer)
torch.nn.utils.clip_grad_norm_(loss_func.parameters(), max_grad_norm)
scaler.step(optimizer)
scaler.update()
skip_scheduler = scaler.get_scale() != scale_before_step
else:
loss_value = loss_func(features, labels)
loss_value.backward()
torch.nn.utils.clip_grad_norm_(loss_func.parameters(), max_grad_norm)
optimizer.step()
optimizer.zero_grad()
if not skip_scheduler:
scheduler_obj.step()
self.state.global_step += 1
self.state.epoch = epoch + (step + 1) / steps_per_epoch
self.control = self.callback_handler.on_step_end(args, self.state, self.control)
self.maybe_log_eval_save(model_body, eval_dataloader, args, scheduler_obj, loss_func, loss_value)
if self.control.should_epoch_stop or self.control.should_training_stop:
break
self.control = self.callback_handler.on_epoch_end(args, self.state, self.control)
self.maybe_log_eval_save(model_body, eval_dataloader, args, scheduler_obj, loss_func, loss_value)
if self.control.should_training_stop:
break
if self.args.load_best_model_at_end and self.state.best_model_checkpoint:
dir_name = Path(self.state.best_model_checkpoint).name
if dir_name.startswith('step_'):
step_to_load = dir_name[5:]
logger.info(f'Loading best SentenceTransformer model from step {step_to_load}.')
self.model.model_card_data.set_best_model_step(int(step_to_load))
sentence_transformer_kwargs = self.model.sentence_transformers_kwargs
sentence_transformer_kwargs['device'] = self.model.device
self.model.model_body = SentenceTransformer(self.state.best_model_checkpoint, **sentence_transformer_kwargs)
self.model.model_body.to(self.model.device)
num_train_samples = self.state.max_steps * args.embedding_batch_size
metrics = speed_metrics('train', start_time, num_samples=num_train_samples, num_steps=self.state.max_steps)
self.control.should_log = True
self.log(args, metrics)
self.control = self.callback_handler.on_train_end(args, self.state, self.control)
def maybe_log_eval_save(self, model_body: SentenceTransformer, eval_dataloader: Optional[DataLoader], args: TrainingArguments, scheduler_obj, loss_func, loss_value: torch.Tensor) -> None:
if self.control.should_log:
learning_rate = scheduler_obj.get_last_lr()[0]
metrics = {'embedding_loss': round(loss_value.item(), 4), 'learning_rate': learning_rate}
self.control = self.log(args, metrics)
eval_loss = None
if self.control.should_evaluate and eval_dataloader is not None:
eval_loss = self._evaluate_with_loss(model_body, eval_dataloader, args, loss_func)
learning_rate = scheduler_obj.get_last_lr()[0]
metrics = {'eval_embedding_loss': round(eval_loss, 4), 'learning_rate': learning_rate}
self.control = self.log(args, metrics)
self.control = self.callback_handler.on_evaluate(args, self.state, self.control, metrics)
loss_func.zero_grad()
loss_func.train()
if self.control.should_save:
checkpoint_dir = self._checkpoint(self.args.output_dir, args.save_total_limit, self.state.global_step)
self.control = self.callback_handler.on_save(self.args, self.state, self.control)
if eval_loss is not None and (self.state.best_metric is None or eval_loss < self.state.best_metric):
self.state.best_metric = eval_loss
self.state.best_model_checkpoint = checkpoint_dir
def _evaluate_with_loss(self, model_body: SentenceTransformer, eval_dataloader: DataLoader, args: TrainingArguments, loss_func: nn.Module) -> float:
model_body.eval()
losses = []
eval_steps = min(len(eval_dataloader), args.eval_max_steps) if args.eval_max_steps != -1 else len(eval_dataloader)
for (step, data) in enumerate(tqdm(iter(eval_dataloader), total=eval_steps, leave=False, disable=not args.show_progress_bar), start=1):
(features, labels) = data
labels = labels.to(self.model.device)
features = list(map(lambda batch: batch_to_device(batch, self.model.device), features))
if args.use_amp:
with autocast():
loss_value = loss_func(features, labels)
losses.append(loss_value.item())
else:
losses.append(loss_func(features, labels).item())
if step >= eval_steps:
break
model_body.train()
return sum(losses) / len(losses)
def _checkpoint(self, checkpoint_path: str, checkpoint_save_total_limit: int, step: int) -> None:
if checkpoint_save_total_limit is not None and checkpoint_save_total_limit > 0:
old_checkpoints = []
for subdir in Path(checkpoint_path).glob('step_*'):
if subdir.name[5:].isdigit() and (self.state.best_model_checkpoint is None or subdir != Path(self.state.best_model_checkpoint)):
old_checkpoints.append({'step': int(subdir.name[5:]), 'path': str(subdir)})
if len(old_checkpoints) > checkpoint_save_total_limit - 1:
old_checkpoints = sorted(old_checkpoints, key=lambda x: x['step'])
shutil.rmtree(old_checkpoints[0]['path'])
checkpoint_file_path = str(Path(checkpoint_path) / f'step_{step}')
self.model.save_pretrained(checkpoint_file_path)
return checkpoint_file_path
def train_classifier(self, x_train: List[str], y_train: Union[List[int], List[List[int]]], args: Optional[TrainingArguments]=None) -> None:
args = args or self.args or TrainingArguments()
self.model.fit(x_train, y_train, num_epochs=args.classifier_num_epochs, batch_size=args.classifier_batch_size, body_learning_rate=args.body_classifier_learning_rate, head_learning_rate=args.head_learning_rate, l2_weight=args.l2_weight, max_length=args.max_length, show_progress_bar=args.show_progress_bar, end_to_end=args.end_to_end)
def evaluate(self, dataset: Optional[Dataset]=None, metric_key_prefix: str='test') -> Dict[str, float]:
if dataset is not None:
self._validate_column_mapping(dataset)
if self.column_mapping is not None:
logger.info('Applying column mapping to the evaluation dataset')
eval_dataset = self._apply_column_mapping(dataset, self.column_mapping)
else:
eval_dataset = dataset
else:
eval_dataset = self.eval_dataset
if eval_dataset is None:
raise ValueError('No evaluation dataset provided to `Trainer.evaluate` nor the `Trainer` initialzation.')
x_test = eval_dataset['text']
y_test = eval_dataset['label']
logger.info('***** Running evaluation *****')
y_pred = self.model.predict(x_test, use_labels=False)
if isinstance(y_pred, torch.Tensor):
y_pred = y_pred.cpu()
if y_test and isinstance(y_test[0], str):
encoder = LabelEncoder()
encoder.fit(list(y_test) + list(y_pred))
y_test = encoder.transform(y_test)
y_pred = encoder.transform(y_pred)
metric_kwargs = self.metric_kwargs or {}
if isinstance(self.metric, str):
metric_config = 'multilabel' if self.model.multi_target_strategy is not None else None
metric_fn = evaluate.load(self.metric, config_name=metric_config)
results = metric_fn.compute(predictions=y_pred, references=y_test, **metric_kwargs)
elif callable(self.metric):
results = self.metric(y_pred, y_test, **metric_kwargs)
else:
raise ValueError('metric must be a string or a callable')
if not isinstance(results, dict):
results = {'metric': results}
self.model.model_card_data.post_training_eval_results({f'{metric_key_prefix}_{key}': value for (key, value) in results.items()})
return results
def hyperparameter_search(self, hp_space: Optional[Callable[['optuna.Trial'], Dict[str, float]]]=None, compute_objective: Optional[Callable[[Dict[str, float]], float]]=None, n_trials: int=10, direction: str='maximize', backend: Optional[Union['str', HPSearchBackend]]=None, hp_name: Optional[Callable[['optuna.Trial'], str]]=None, **kwargs) -> BestRun:
if backend is None:
backend = default_hp_search_backend()
if backend is None:
raise RuntimeError('optuna should be installed. To install optuna run `pip install optuna`.')
backend = HPSearchBackend(backend)
if backend == HPSearchBackend.OPTUNA and (not is_optuna_available()):
raise RuntimeError('You picked the optuna backend, but it is not installed. Use `pip install optuna`.')
elif backend != HPSearchBackend.OPTUNA:
raise RuntimeError('Only optuna backend is supported for hyperparameter search.')
self.hp_search_backend = backend
if self.model_init is None:
raise RuntimeError('To use hyperparameter search, you need to pass your model through a model_init function.')
self.hp_space = default_hp_space_optuna if hp_space is None else hp_space
self.hp_name = hp_name
self.compute_objective = default_compute_objective if compute_objective is None else compute_objective
backend_dict = {HPSearchBackend.OPTUNA: run_hp_search_optuna}
best_run = backend_dict[backend](self, n_trials, direction, **kwargs)
self.hp_search_backend = None
return best_run
def push_to_hub(self, repo_id: str, **kwargs) -> str:
if '/' not in repo_id:
raise ValueError('`repo_id` must be a full repository ID, including organisation, e.g. "tomaarsen/setfit-sst2".')
commit_message = kwargs.pop('commit_message', 'Add SetFit model')
return self.model.push_to_hub(repo_id, commit_message=commit_message, **kwargs)
class SetFitTrainer(Trainer):
def __init__(self, model: Optional['SetFitModel']=None, train_dataset: Optional['Dataset']=None, eval_dataset: Optional['Dataset']=None, model_init: Optional[Callable[[], 'SetFitModel']]=None, metric: Union[str, Callable[['Dataset', 'Dataset'], Dict[str, float]]]='accuracy', metric_kwargs: Optional[Dict[str, Any]]=None, loss_class=losses.CosineSimilarityLoss, num_iterations: int=20, num_epochs: int=1, learning_rate: float=2e-05, batch_size: int=16, seed: int=42, column_mapping: Optional[Dict[str, str]]=None, use_amp: bool=False, warmup_proportion: float=0.1, distance_metric: Callable=BatchHardTripletLossDistanceFunction.cosine_distance, margin: float=0.25, samples_per_label: int=2):
warnings.warn('`SetFitTrainer` has been deprecated and will be removed in v2.0.0 of SetFit. Please use `Trainer` instead.', DeprecationWarning, stacklevel=2)
args = TrainingArguments(num_iterations=num_iterations, num_epochs=num_epochs, body_learning_rate=learning_rate, head_learning_rate=learning_rate, batch_size=batch_size, seed=seed, use_amp=use_amp, warmup_proportion=warmup_proportion, distance_metric=distance_metric, margin=margin, samples_per_label=samples_per_label, loss=loss_class)
super().__init__(model=model, args=args, train_dataset=train_dataset, eval_dataset=eval_dataset, model_init=model_init, metric=metric, metric_kwargs=metric_kwargs, column_mapping=column_mapping)
# File: setfit-main/src/setfit/trainer_distillation.py
import warnings
from typing import TYPE_CHECKING, Callable, Dict, Iterable, List, Optional, Tuple, Union
import torch
from datasets import Dataset
from sentence_transformers import InputExample, losses, util
from torch import nn
from torch.utils.data import DataLoader
from . import logging
from .sampler import ContrastiveDistillationDataset
from .trainer import Trainer
from .training_args import TrainingArguments
if TYPE_CHECKING:
from .modeling import SetFitModel
logging.set_verbosity_info()
logger = logging.get_logger(__name__)
class DistillationTrainer(Trainer):
_REQUIRED_COLUMNS = {'text'}
def __init__(self, teacher_model: 'SetFitModel', student_model: Optional['SetFitModel']=None, args: TrainingArguments=None, train_dataset: Optional['Dataset']=None, eval_dataset: Optional['Dataset']=None, model_init: Optional[Callable[[], 'SetFitModel']]=None, metric: Union[str, Callable[['Dataset', 'Dataset'], Dict[str, float]]]='accuracy', column_mapping: Optional[Dict[str, str]]=None) -> None:
super().__init__(model=student_model, args=args, train_dataset=train_dataset, eval_dataset=eval_dataset, model_init=model_init, metric=metric, column_mapping=column_mapping)
self.teacher_model = teacher_model
self.student_model = self.model
def dataset_to_parameters(self, dataset: Dataset) -> List[Iterable]:
return [dataset['text']]
def get_dataloader(self, x: List[str], y: Optional[Union[List[int], List[List[int]]]], args: TrainingArguments, max_pairs: int=-1) -> Tuple[DataLoader, nn.Module, int, int]:
x_embd_student = self.teacher_model.model_body.encode(x, convert_to_tensor=self.teacher_model.has_differentiable_head)
cos_sim_matrix = util.cos_sim(x_embd_student, x_embd_student)
input_data = [InputExample(texts=[text]) for text in x]
data_sampler = ContrastiveDistillationDataset(input_data, cos_sim_matrix, args.num_iterations, args.sampling_strategy, max_pairs=max_pairs)
batch_size = min(args.embedding_batch_size, len(data_sampler))
dataloader = DataLoader(data_sampler, batch_size=batch_size, drop_last=False)
loss = args.loss(self.model.model_body)
return (dataloader, loss, batch_size, len(data_sampler))
def train_classifier(self, x_train: List[str], args: Optional[TrainingArguments]=None) -> None:
y_train = self.teacher_model.predict(x_train, as_numpy=not self.student_model.has_differentiable_head)
return super().train_classifier(x_train, y_train, args)
class DistillationSetFitTrainer(DistillationTrainer):
def __init__(self, teacher_model: 'SetFitModel', student_model: Optional['SetFitModel']=None, train_dataset: Optional['Dataset']=None, eval_dataset: Optional['Dataset']=None, model_init: Optional[Callable[[], 'SetFitModel']]=None, metric: Union[str, Callable[['Dataset', 'Dataset'], Dict[str, float]]]='accuracy', loss_class: torch.nn.Module=losses.CosineSimilarityLoss, num_iterations: int=20, num_epochs: int=1, learning_rate: float=2e-05, batch_size: int=16, seed: int=42, column_mapping: Optional[Dict[str, str]]=None, use_amp: bool=False, warmup_proportion: float=0.1) -> None:
warnings.warn('`DistillationSetFitTrainer` has been deprecated and will be removed in v2.0.0 of SetFit. Please use `DistillationTrainer` instead.', DeprecationWarning, stacklevel=2)
args = TrainingArguments(num_iterations=num_iterations, num_epochs=num_epochs, body_learning_rate=learning_rate, head_learning_rate=learning_rate, batch_size=batch_size, seed=seed, use_amp=use_amp, warmup_proportion=warmup_proportion, loss=loss_class)
super().__init__(teacher_model=teacher_model, student_model=student_model, args=args, train_dataset=train_dataset, eval_dataset=eval_dataset, model_init=model_init, metric=metric, column_mapping=column_mapping)
# File: setfit-main/src/setfit/training_args.py
from __future__ import annotations
import inspect
import json
from copy import copy
from dataclasses import dataclass, field, fields
from typing import Any, Callable, Dict, Optional, Tuple, Union
import torch
from sentence_transformers import losses
from transformers import IntervalStrategy
from transformers.integrations import get_available_reporting_integrations
from transformers.training_args import default_logdir
from transformers.utils import is_torch_available
from . import logging
logger = logging.get_logger(__name__)
@dataclass
class TrainingArguments:
output_dir: str = 'checkpoints'
batch_size: Union[int, Tuple[int, int]] = field(default=(16, 2), repr=False)
num_epochs: Union[int, Tuple[int, int]] = field(default=(1, 16), repr=False)
max_steps: int = -1
sampling_strategy: str = 'oversampling'
num_iterations: Optional[int] = None
body_learning_rate: Union[float, Tuple[float, float]] = field(default=(2e-05, 1e-05), repr=False)
head_learning_rate: float = 0.01
loss: Callable = losses.CosineSimilarityLoss
distance_metric: Callable = losses.BatchHardTripletLossDistanceFunction.cosine_distance
margin: float = 0.25
end_to_end: bool = field(default=False)
use_amp: bool = False
warmup_proportion: float = 0.1
l2_weight: Optional[float] = None
max_length: Optional[int] = None
samples_per_label: int = 2
show_progress_bar: bool = True
seed: int = 42
report_to: str = 'all'
run_name: Optional[str] = None
logging_dir: Optional[str] = None
logging_strategy: str = 'steps'
logging_first_step: bool = True
logging_steps: int = 50
eval_strategy: str = 'no'
evaluation_strategy: Optional[str] = field(default=None, repr=False)
eval_steps: Optional[int] = None
eval_delay: int = 0
eval_max_steps: int = -1
save_strategy: str = 'steps'
save_steps: int = 500
save_total_limit: Optional[int] = 1
load_best_model_at_end: bool = False
metric_for_best_model: str = field(default='embedding_loss', repr=False)
greater_is_better: bool = field(default=False, repr=False)
def __post_init__(self) -> None:
if isinstance(self.batch_size, int):
self.batch_size = (self.batch_size, self.batch_size)
if isinstance(self.num_epochs, int):
self.num_epochs = (self.num_epochs, self.num_epochs)
if isinstance(self.body_learning_rate, float):
self.body_learning_rate = (self.body_learning_rate, self.body_learning_rate)
if self.warmup_proportion < 0.0 or self.warmup_proportion > 1.0:
raise ValueError(f'warmup_proportion must be greater than or equal to 0.0 and less than or equal to 1.0! But it was: {self.warmup_proportion}')
if self.report_to in (None, 'all', ['all']):
self.report_to = get_available_reporting_integrations()
elif self.report_to in ('none', ['none']):
self.report_to = []
elif not isinstance(self.report_to, list):
self.report_to = [self.report_to]
if self.logging_dir is None:
self.logging_dir = default_logdir()
self.logging_strategy = IntervalStrategy(self.logging_strategy)
if self.evaluation_strategy is not None:
logger.warning('The `evaluation_strategy` argument is deprecated and will be removed in a future version. Please use `eval_strategy` instead.')
self.eval_strategy = self.evaluation_strategy
self.eval_strategy = IntervalStrategy(self.eval_strategy)
if self.eval_steps is not None and self.eval_strategy == IntervalStrategy.NO:
logger.info('Using `eval_strategy="steps"` as `eval_steps` is defined.')
self.eval_strategy = IntervalStrategy.STEPS
if self.eval_strategy == IntervalStrategy.STEPS and (self.eval_steps is None or self.eval_steps == 0):
if self.logging_steps > 0:
self.eval_steps = self.logging_steps
else:
raise ValueError(f'evaluation strategy {self.eval_strategy} requires either non-zero `eval_steps` or `logging_steps`')
if self.load_best_model_at_end:
if self.eval_strategy != self.save_strategy:
raise ValueError(f'`load_best_model_at_end` requires the save and eval strategy to match, but found\n- Evaluation strategy: {self.eval_strategy}\n- Save strategy: {self.save_strategy}')
if self.eval_strategy == IntervalStrategy.STEPS and self.save_steps % self.eval_steps != 0:
raise ValueError(f'`load_best_model_at_end` requires the saving steps to be a round multiple of the evaluation steps, but found {self.save_steps}, which is not a round multiple of {self.eval_steps}.')
if self.logging_strategy == IntervalStrategy.STEPS and self.logging_steps == 0:
raise ValueError(f'Logging strategy {self.logging_strategy} requires non-zero `logging_steps`')
@property
def embedding_batch_size(self) -> int:
return self.batch_size[0]
@property
def classifier_batch_size(self) -> int:
return self.batch_size[1]
@property
def embedding_num_epochs(self) -> int:
return self.num_epochs[0]
@property
def classifier_num_epochs(self) -> int:
return self.num_epochs[1]
@property
def body_embedding_learning_rate(self) -> float:
return self.body_learning_rate[0]
@property
def body_classifier_learning_rate(self) -> float:
return self.body_learning_rate[1]
def to_dict(self) -> Dict[str, Any]:
return {field.name: getattr(self, field.name) for field in fields(self) if field.init}
@classmethod
def from_dict(cls, arguments: Dict[str, Any], ignore_extra: bool=False) -> TrainingArguments:
if ignore_extra:
return cls(**{key: value for (key, value) in arguments.items() if key in inspect.signature(cls).parameters})
return cls(**arguments)
def copy(self) -> TrainingArguments:
return copy(self)
def update(self, arguments: Dict[str, Any], ignore_extra: bool=False) -> TrainingArguments:
return TrainingArguments.from_dict({**self.to_dict(), **arguments}, ignore_extra=ignore_extra)
def to_json_string(self):
return json.dumps({key: str(value) for (key, value) in self.to_dict().items()}, indent=2)
def to_sanitized_dict(self) -> Dict[str, Any]:
d = self.to_dict()
d = {**d, **{'train_batch_size': self.embedding_batch_size, 'eval_batch_size': self.embedding_batch_size}}
valid_types = [bool, int, float, str]
if is_torch_available():
valid_types.append(torch.Tensor)
return {k: v if type(v) in valid_types else str(v) for (k, v) in d.items()}
# File: setfit-main/src/setfit/utils.py
import types
from contextlib import contextmanager
from dataclasses import dataclass, field
from time import monotonic_ns
from typing import Any, Dict, List, NamedTuple, Optional, Tuple
from datasets import Dataset, DatasetDict, load_dataset
from sentence_transformers import losses
from transformers.utils import copy_func
from .data import create_fewshot_splits, create_fewshot_splits_multilabel
from .losses import SupConLoss
SEC_TO_NS_SCALE = 1000000000
DEV_DATASET_TO_METRIC = {'sst2': 'accuracy', 'imdb': 'accuracy', 'subj': 'accuracy', 'bbc-news': 'accuracy', 'enron_spam': 'accuracy', 'student-question-categories': 'accuracy', 'TREC-QC': 'accuracy', 'toxic_conversations': 'matthews_correlation'}
TEST_DATASET_TO_METRIC = {'emotion': 'accuracy', 'SentEval-CR': 'accuracy', 'sst5': 'accuracy', 'ag_news': 'accuracy', 'enron_spam': 'accuracy', 'amazon_counterfactual_en': 'matthews_correlation'}
MULTILINGUAL_DATASET_TO_METRIC = {f'amazon_reviews_multi_{lang}': 'mae' for lang in ['en', 'de', 'es', 'fr', 'ja', 'zh']}
LOSS_NAME_TO_CLASS = {'CosineSimilarityLoss': losses.CosineSimilarityLoss, 'ContrastiveLoss': losses.ContrastiveLoss, 'OnlineContrastiveLoss': losses.OnlineContrastiveLoss, 'BatchSemiHardTripletLoss': losses.BatchSemiHardTripletLoss, 'BatchAllTripletLoss': losses.BatchAllTripletLoss, 'BatchHardTripletLoss': losses.BatchHardTripletLoss, 'BatchHardSoftMarginTripletLoss': losses.BatchHardSoftMarginTripletLoss, 'SupConLoss': SupConLoss}
def default_hp_space_optuna(trial) -> Dict[str, Any]:
from transformers.integrations import is_optuna_available
assert is_optuna_available(), 'This function needs Optuna installed: `pip install optuna`'
return {'learning_rate': trial.suggest_float('learning_rate', 1e-06, 0.0001, log=True), 'num_epochs': trial.suggest_int('num_epochs', 1, 5), 'num_iterations': trial.suggest_categorical('num_iterations', [5, 10, 20]), 'seed': trial.suggest_int('seed', 1, 40), 'batch_size': trial.suggest_categorical('batch_size', [4, 8, 16, 32, 64])}
def load_data_splits(dataset: str, sample_sizes: List[int], add_data_augmentation: bool=False) -> Tuple[DatasetDict, Dataset]:
print(f'\n\n\n============== {dataset} ============')
train_split = load_dataset(f'SetFit/{dataset}', split='train')
train_splits = create_fewshot_splits(train_split, sample_sizes, add_data_augmentation, f'SetFit/{dataset}')
test_split = load_dataset(f'SetFit/{dataset}', split='test')
print(f'Test set: {len(test_split)}')
return (train_splits, test_split)
def load_data_splits_multilabel(dataset: str, sample_sizes: List[int]) -> Tuple[DatasetDict, Dataset]:
print(f'\n\n\n============== {dataset} ============')
train_split = load_dataset(f'SetFit/{dataset}', 'multilabel', split='train')
train_splits = create_fewshot_splits_multilabel(train_split, sample_sizes)
test_split = load_dataset(f'SetFit/{dataset}', 'multilabel', split='test')
print(f'Test set: {len(test_split)}')
return (train_splits, test_split)
@dataclass
class Benchmark:
out_path: Optional[str] = None
summary_msg: str = field(default_factory=str)
def print(self, msg: str) -> None:
print(msg)
if self.out_path is not None:
with open(self.out_path, 'a+') as f:
f.write(msg + '\n')
@contextmanager
def track(self, step):
start = monotonic_ns()
yield
ns = monotonic_ns() - start
msg = f"\n{'*' * 70}\n'{step}' took {ns / SEC_TO_NS_SCALE:.3f}s ({ns:,}ns)\n{'*' * 70}\n"
print(msg)
self.summary_msg += msg + '\n'
def summary(self) -> None:
self.print(f"\n{'#' * 30}\nBenchmark Summary:\n{'#' * 30}\n\n{self.summary_msg}")
class BestRun(NamedTuple):
run_id: str
objective: float
hyperparameters: Dict[str, Any]
backend: Any = None
def set_docstring(method, docstring, cls=None):
copied_function = copy_func(method)
copied_function.__doc__ = docstring
return types.MethodType(copied_function, cls or method.__self__)