sts

class hanlp.components.sts.transformer_sts.TransformerSemanticTextualSimilarity(**kwargs)[source]

A simple Semantic Textual Similarity (STS) baseline which fine-tunes a transformer with a regression layer on top of it.

Parameters

**kwargs – Predefined config.

build_criterion(**kwargs)[source]

Implement this method to build criterion (loss function).

Parameters

**kwargs – The subclass decides the method signature.

build_dataloader(data, batch_size, sent_a_col=None, sent_b_col=None, similarity_col=None, delimiter='auto', gradient_accumulation=1, sampler_builder=None, shuffle=False, device=None, logger: logging.Logger = None, split=None, **kwargs) → torch.utils.data.dataloader.DataLoader[source]

Build dataloader for training, dev and test sets. It’s suggested to build vocabs in this method if they are not built yet.

Parameters
  • data – Data representing samples, which can be a path or a list of samples.

  • batch_size – Number of samples per batch.

  • shuffle – Whether to shuffle this dataloader.

  • device – Device tensors should be loaded onto.

  • logger – Logger for reporting some message if dataloader takes a long time or if vocabs has to be built.

  • **kwargs – Arguments from **self.config.

build_metric(**kwargs)[source]

Implement this to build metric(s).

Parameters

**kwargs – The subclass decides the method signature.

build_model(transformer, training=True, **kwargs) → torch.nn.modules.module.Module[source]

Build model.

Parameters
  • trainingTrue if called during training.

  • **kwargs**self.config.

build_optimizer(trn, epochs, gradient_accumulation=1, lr=0.001, transformer_lr=5e-05, adam_epsilon=1e-08, weight_decay=0.0, warmup_steps=0.1, **kwargs)[source]

Implement this method to build an optimizer.

Parameters

**kwargs – The subclass decides the method signature.

evaluate_dataloader(data: torch.utils.data.dataloader.DataLoader, logger: logging.Logger, metric=None, output=False, **kwargs)[source]

Evaluate on a dataloader.

Parameters
  • data – Dataloader which can build from any data source.

  • criterion – Loss function.

  • metric – Metric(s).

  • output – Whether to save outputs into some file.

  • **kwargs – Not used.

execute_training_loop(trn: torch.utils.data.dataloader.DataLoader, dev: torch.utils.data.dataloader.DataLoader, epochs, criterion, optimizer, metric, save_dir, logger: logging.Logger, devices, ratio_width=None, gradient_accumulation=1, **kwargs)[source]

Implement this to run training loop.

Parameters
  • trn – Training set.

  • dev – Development set.

  • epochs – Number of epochs.

  • criterion – Loss function.

  • optimizer – Optimizer(s).

  • metric – Metric(s)

  • save_dir – The directory to save this component.

  • logger – Logger for reporting progress.

  • devices – Devices this component and dataloader will live on.

  • ratio_width – The width of dataset size measured in number of characters. Used for logger to align messages.

  • **kwargs – Other hyper-parameters passed from sub-class.

fit(trn_data, dev_data, save_dir, transformer, sent_a_col, sent_b_col, similarity_col, delimiter='auto', batch_size=32, max_seq_len=128, epochs=3, lr=0.001, transformer_lr=5e-05, adam_epsilon=1e-08, weight_decay=0.0, warmup_steps=0.1, gradient_accumulation=1, grad_norm=1.0, sampler_builder=None, devices=None, logger=None, seed=None, finetune: Union[bool, str] = False, eval_trn=True, _device_placeholder=False, **kwargs)[source]

Fit to data, triggers the training procedure. For training set and dev set, they shall be local or remote files.

Parameters
  • trn_data – Training set.

  • dev_data – Development set.

  • save_dir – The directory to save trained component.

  • batch_size – The number of samples in a batch.

  • epochs – Number of epochs.

  • devices – Devices this component will live on.

  • logger – Any logging.Logger instance.

  • seed – Random seed to reproduce this training.

  • finetuneTrue to load from save_dir instead of creating a randomly initialized component. str to specify a different save_dir to load from.

  • eval_trn – Evaluate training set after each update. This can slow down the training but provides a quick diagnostic for debugging.

  • _device_placeholderTrue to create a placeholder tensor which triggers PyTorch to occupy devices so other components won’t take these devices as first choices.

  • **kwargs – Hyperparameters used by sub-classes.

Returns

Any results sub-classes would like to return. Usually the best metrics on training set.

fit_dataloader(trn: torch.utils.data.dataloader.DataLoader, criterion, optimizer, metric: hanlp.metrics.spearman_correlation.SpearmanCorrelation, logger: logging.Logger, history=None, gradient_accumulation=1, **kwargs)[source]

Fit onto a dataloader.

Parameters
  • trn – Training set.

  • criterion – Loss function.

  • optimizer – Optimizer.

  • metric – Metric(s).

  • logger – Logger for reporting progress.

  • **kwargs – Other hyper-parameters passed from sub-class.

on_config_ready(transformer, max_seq_len, **kwargs)[source]

Called when config is ready, either during fit ot load. Subclass can perform extra initialization tasks in this callback.

Parameters

**kwargs – Not used.

predict(data: Union[List[str], List[List[str]]], batch_size: int = None, **kwargs) → Union[float, List[float]][source]

Predict the similarity between sentence pairs.

Parameters
  • data – Sentence pairs.

  • batch_size – The number of samples in a batch.

  • **kwargs – Not used.

Returns

Similarities between sentences.