simpletransformers

ThilinaRajapakseApache-2.0更新放缓

基于 Transformers 的 Python 训练库,把文本分类、NER、问答、信息检索、语言生成、多模态和对话 AI 等任务的训练与推理流程统一封装,省去手写训练循环的麻烦。

Transformers for Information Retrieval, Text Classification, NER, QA, Language Modelling, Language Generation, T5, Multi-Modal, and Conversational AI

v0.60.0发布于 2021-02-01 20:38 UTC4,258star709fork同步于 2026-11-10 23:39 UTC

怎么上手

由 README 提炼,执行前请确认
conda create -n st python pandas tqdm
conda activate st
pip install simpletransformers
硬件要求按 README 说明

README 未说明具体显存要求;安装时可选 CUDA 版 PyTorch(pytorch>=1.6 + cudatoolkit=11.0)或纯 CPU 版(cpuonly),未列出支持的 GPU 厂商与型号。

支持 Apple Silicon
下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

基于 HuggingFace Transformers 的高层封装库,三行代码完成模型初始化、训练与评估

基于 Transformers 的 Python 训练库,把文本分类、NER、问答、信息检索、语言生成、多模态和对话 AI 等任务的训练与推理流程统一封装,省去手写训练循环的麻烦。

核心能力

  • 按任务提供专用模型类,如 ClassificationModel、NERModel、QuestionAnsweringModel
  • 统一 initialize、train_model、eval_model、predict 四步使用流程
  • 覆盖信息检索、文本分类、NER、问答、语言生成、T5、多模态与对话 AI
  • 支持直接指定 HuggingFace 预训练模型名与 model_type 加载
  • 可选集成 Weights and Biases 记录并可视化训练实验

容易踩的坑

需先自行安装 PyTorch,CUDA 与 CPU 版本二选一,否则 pip 安装后无法运行;预训练模型需从 HuggingFace 下载,首次运行依赖网络;wandb 实验跟踪需额外 pip install wandb,非默认安装。

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

5 个版本v0.60.0
  1. v0.60.0New Classification Models最新正式版2021-02-01 · 2021-02-01 20:38 UTC

    New Classification Models

    Added

    • Added class weights support for Longformer classification
    • Added new classification models (multilabel classification is not supported yet):
      • DeBERTa
      • MPNet
      • SqueezeBert (no sliding window support)

    Changed

    • Updated ClassificationModel logic to make it easier to add new models
  2. v0.51.0MT5, Adafactor optimizer, additional schedulers2020-12-05 · 2020-12-05 15:36 UTC
    查看更新说明

    MT5, Adafactor optimizer, additional schedulers

    Breaking change

    • T5Model now has a required model_type parameter ("t5" or "mt5")

    Added

    • Added support for MT5
    • Added support for Adafactor optimizer
    • Added support for various schedulers:
      • get_constant_schedule
      • get_constant_schedule_with_warmup
      • get_linear_schedule_with_warmup
      • get_cosine_schedule_with_warmup
      • get_cosine_with_hard_restarts_schedule_with_warmup
      • get_polynomial_decay_schedule_with_warmup

    Changed

    • T5Model now has a required model_type parameter ("t5" or "mt5")

    Fixed

    • Fixed issue with class weights not working in ClassificationModel when using mult-GPU training
  3. v0.49.0LayoutLM model for Classification. MBart. BERTWeet for NER. Longformer for Multilabel Classification.2020-11-09 · 2020-11-09 13:38 UTC
    查看更新说明

    Added

    Fixed

    • Fixed issue with Seq2SeqModel when the model_name contained backslashes.
    • Fixed issue with saving args when a dataset_class is specified in Seq2SeqModel.

    Changed

    • The Electra implementation used with ClassificationModel is now fully compatible with Hugging Face.
  4. v0.48.6LayoutLM model for NER2020-09-26 · 2020-09-26 08:23 UTC
    查看更新说明

    Added

    • Added layoutlm model for NER (see docs)

    Fixed

    • Potential fix for inconsistent eval_loss calculation
  5. v0.48.5Evaluation/Prediction Performance enhancements and ONNX support2020-09-24 · 2020-09-24 09:52 UTC
    查看更新说明

    Mixed Precision Support for evaluation and prediction

    Mixed precision (fp16) inference is now supported for evaluation and prediction in the following models:

    • ClassificationModel
    • ConvAI
    • MultiModalClassificationModel
    • NERModel
    • QuestionAnsweringModel
    • Seq2Seq
    • T5Model

    You can disable fp16 by setting fp16 = False in the model_args.

    Multi-GPU support for evaluation and prediction

    Set the number of GPUs with n_gpu. in model_args Currently supported in the following models:

    • ClassificationModel
    • ConvAI
    • MultiModalClassificationModel
    • NERModel
    • QuestionAnsweringModel
    • Seq2Seq
    • T5Model

    Native ONNX support for Classification and NER tasks (Beta)

    Please note that ONNX support is still experimental.

    See docs for details.

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    License Downloads

    All Contributors

    Simple Transformers

    This library is based on the Transformers library by HuggingFace. Simple Transformers lets you quickly train and evaluate Transformer models. Only 3 lines of code are needed to initialize, train, and evaluate a model.

    Supported Tasks:

    • Information Retrieval (Dense Retrieval)
    • (Large) Language Models (Training, Fine-tuning, and Generation)
    • Encoder Model Training and Fine-tuning
    • Sequence Classification
    • Token Classification (NER)
    • Question Answering
    • Language Generation
    • T5 Model
    • Seq2Seq Tasks
    • Multi-Modal Classification
    • Conversational AI

    Citation

    If you use Simple Transformers in your work, please cite:

    @inproceedings{Rajapakse2024SimpleTransformers,
      author    = {Rajapakse, Thilina C. and Yates, Andrew and de Rijke, Maarten},
      title     = {Simple Transformers: Open-source for All},
      booktitle = {Proceedings of the 2024 Annual International ACM SIGIR
                   Conference on Research and Development in Information
                   Retrieval in the Asia Pacific Region},
      series    = {SIGIR-AP 2024},
      pages     = {209--215},
      year      = {2024},
      doi       = {10.1145/3673791.3698412},
      url       = {https://doi.org/10.1145/3673791.3698412},
      location  = {Tokyo, Japan}
    }
    

    Table of contents

    Setup

    With Conda

    1. Install Anaconda or Miniconda Package Manager from here
    2. Create a new virtual environment and install packages.
    $ conda create -n st python pandas tqdm
    $ conda activate st
    

    Using Cuda:

    $ conda install pytorch>=1.6 cudatoolkit=11.0 -c pytorch
    

    Without using Cuda

    $ conda install pytorch cpuonly -c pytorch
    
    1. Install simpletransformers.
    $ pip install simpletransformers
    
    Optional
    1. Install Weights and Biases (wandb) for tracking and visualizing training in a web browser.
    $ pip install wandb
    

    Usage

    All documentation is now live at thilinarajapakse.github.io/simpletransformers

    Simple Transformer models are built with a particular Natural Language Processing (NLP) task in mind. Each such model comes equipped with features and functionality designed to best fit the task that they are intended to perform. The high-level process of using Simple Transformers models follows the same pattern.

    1. Initialize a task-specific model
    2. Train the model with train_model()
    3. Evaluate the model with eval_model()
    4. Make predictions on (unlabelled) data with predict()

    However, there are necessary differences between the different models to ensure that they are well suited for their intended task. The key differences will typically be the differences in input/output data formats and any task specific features/configuration options. These can all be found in the documentation section for each task.

    The currently implemented task-specific Simple Transformer models, along with their task, are given below.

    TaskModel
    Binary and multi-class text classificationClassificationModel
    Conversational AI (chatbot training)ConvAIModel
    Language generationLanguageGenerationModel
    Language model training/fine-tuningLanguageModelingModel
    Multi-label text classificationMultiLabelClassificationModel
    Multi-modal classification (text and image data combined)MultiModalClassificationModel
    Named entity recognitionNERModel
    Question answeringQuestionAnsweringModel
    RegressionClassificationModel
    Sentence-pair classificationClassificationModel
    Text Representation GenerationRepresentationModel
    Document RetrievalRetrievalModel
    • Please refer to the relevant section in the docs for more information on how to use these models.
    • Example scripts can be found in the examples directory.
    • See the Changelog for up-to-date changes to the project.

    A quick example

    from simpletransformers.classification import ClassificationModel, ClassificationArgs
    import pandas as pd
    import logging
    
    
    logging.basicConfig(level=logging.INFO)
    transformers_logger = logging.getLogger("transformers")
    transformers_logger.setLevel(logging.WARNING)
    
    # Preparing train data
    train_data = [
        ["Aragorn was the heir of Isildur", 1],
        ["Frodo was the heir of Isildur", 0],
    ]
    train_df = pd.DataFrame(train_data)
    train_df.columns = ["text", "labels"]
    
    # Preparing eval data
    eval_data = [
        ["Theoden was the king of Rohan", 1],
        ["Merry was the king of Rohan", 0],
    ]
    eval_df = pd.DataFrame(eval_data)
    eval_df.columns = ["text", "labels"]
    
    # Optional model configuration
    model_args = ClassificationArgs(num_train_epochs=1)
    
    # Create a ClassificationModel
    model = ClassificationModel(
        "roberta", "roberta-base", args=model_args
    )
    
    # Train the model
    model.train_model(train_df)
    
    # Evaluate the model
    result, model_outputs, wrong_predictions = model.eval_model(eval_df)
    
    # Make predictions with the model
    predictions, raw_outputs = model.predict(["Sam was a Wizard"])
    
    

    Experiment Tracking with Weights and Biases

    • Weights and Biases makes it incredibly easy to keep track of all your experiments. Check it out on Colab here: Open In Colab

    Current Pretrained Models

    For a list of pretrained models, see Hugging Face docs.

    The model_types available for each task can be found under their respective section. Any pretrained model of that type found in the Hugging Face docs should work. To use any of them set the correct model_type and model_name in the args dictionary.


    Contributors ✨

    Thanks goes to these wonderful people (emoji key):

    This project follows the all-contributors specification. Contributions of any kind welcome!

    If you should be on this list but you aren't, or you are on the list but don't want to be, please don't hesitate to contact me!


    How to Contribute

    How to Update Docs

    The latest version of the docs is hosted on Github Pages, if you want to help document Simple Transformers below are the steps to edit the docs. Docs are built using Jekyll library, refer to their webpage for a detailed explanation of how it works.

    1. Install Jekyll: Run the command gem install bundler jekyll
    2. Visualizing the docs on your local computer: In your terminal cd into the docs directory of this repo, eg: cd simpletransformers/docs From the docs directory run this command to serve the Jekyll docs locally: bundle exec jekyll serve Browse to http://localhost:4000 or whatever url you see in the console to visualize the docs.
    3. Edit and visualize changes: All the section pages of our docs can be found under docs/_docs directory, you can edit any file you want by following the markdown format and visualize the changes after refreshing the browser tab.

    Acknowledgements

    None of this would have been possible without the hard work by the HuggingFace team in developing the Transformers library.

    <div>Icon for the Social Media Preview made by <a href="https://www.flaticon.com/authors/freepik" title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" title="Flaticon">www.flaticon.com</a></div>