[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"tool-NVIDIA--sentiment-discovery":3,"similar-NVIDIA--sentiment-discovery":114},{"id":4,"github_repo":5,"name":6,"description_en":7,"description_zh":8,"ai_summary_zh":8,"readme_en":9,"readme_zh":10,"quickstart_zh":11,"use_case_zh":12,"hero_image_url":13,"owner_login":14,"owner_name":15,"owner_avatar_url":16,"owner_bio":17,"owner_company":18,"owner_location":18,"owner_email":18,"owner_twitter":18,"owner_website":19,"owner_url":20,"languages":21,"stars":30,"forks":31,"last_commit_at":32,"license":33,"difficulty_score":34,"env_os":35,"env_gpu":36,"env_ram":35,"env_deps":37,"category_tags":51,"github_topics":18,"view_count":54,"oss_zip_url":18,"oss_zip_packed_at":18,"status":55,"created_at":56,"updated_at":57,"faqs":58,"releases":93},3526,"NVIDIA\u002Fsentiment-discovery","sentiment-discovery","Unsupervised Language Modeling at scale for robust sentiment classification","sentiment-discovery 是一个基于 PyTorch 的开源项目，旨在通过大规模无监督语言建模来实现鲁棒的情感分类。它主要解决了在标注数据稀缺或类别不平衡的现实场景下，传统模型难以准确识别文本情感与复杂情绪的问题。该项目复现并扩展了相关前沿研究，支持将预训练的语言模型迁移到自定义数据集上，仅需少量标注样本即可在情感分析或多模态情绪分类任务中达到业界领先的性能。\n\nsentiment-discovery 特别适合 NLP 研究人员和开发者使用，尤其是那些需要处理大规模文本数据、探索无监督学习技术或构建高精度分类模型的团队。其技术亮点包括支持混合精度训练以及分布式多 GPU、多节点训练，显著提升了训练效率；同时提供了灵活的命令行接口，兼容 Transformer 等多种架构及不同的分词方法。需要注意的是，该仓库目前已标记为弃用，官方建议用户转向功能更完善的 Megatron-LM 项目以获取最新的大规模预训练代码，但若需复现特定历史研究成果，仍可通过该项目的历史版本获取相应资源。","# ** DEPRECATED **\nThis repo has been deprecated. Please visit [Megatron-LM](https:\u002F\u002Fgithub.com\u002FNVIDIA\u002FMegatron-LM) for our up to date Large-scale unsupervised pretraining and finetuning code.\n\nIf you would still like to use this codebase, see our tagged releases and install required software\u002Fdependencies that was available publicly at that date.\n\n\n# PyTorch Unsupervised Sentiment Discovery\nThis codebase contains pretrained binary sentiment and multimodel emotion classification models as well as code to reproduce results from our series of large scale pretraining + transfer NLP papers: _[Large Scale Language Modeling: Converging on 40GB of Text in Four Hours](https:\u002F\u002Fnv-adlr.github.io\u002Fpublication\u002F2018-large-batch-lm)_ and _[Practical Text Classification With Large Pre-Trained Language Models](https:\u002F\u002Farxiv.org\u002Fabs\u002F1812.01207)_. This effort was born out of a desire to reproduce, analyze, and scale the [Generating Reviews and Discovering Sentiment](https:\u002F\u002Fgithub.com\u002Fopenai\u002Fgenerating-reviews-discovering-sentiment) paper from OpenAI.\n\nThe techniques used in this repository are general purpose and our easy to use command line interface can be used to train state of the art classification models on your own difficult classification datasets.\n\nThis codebase supports mixed precision training as well as distributed, multi-gpu, multi-node training for language models (support is provided based on the NVIDIA [APEx](https:\u002F\u002Fgithub.com\u002FNVIDIA\u002Fapex) project). In addition to training language models, this codebase can be used to easily transfer and finetune trained models on custom text classification datasets.\n\nFor example, a [Transformer](https:\u002F\u002Farxiv.org\u002Fabs\u002F1706.03762) language model for unsupervised modeling of large text datasets, such as the [amazon-review dataset](http:\u002F\u002Fjmcauley.ucsd.edu\u002Fdata\u002Famazon\u002F), is implemented in PyTorch. We also support other tokenization methods, such as character or sentencepiece tokenization, and language models using various recurrent architectures.\n\nThe learned language model can be transferred to other natural language processing (NLP) tasks where it is used to featurize text samples. The featurizations provide a strong initialization point for discriminative language tasks, and allow for competitive task performance given only a few labeled samples. For example, we consider finetuning our models on the difficult task of multimodal emotion classification based on a subset of the plutchik wheel of emotions.\n\n![plutchik fig](.\u002Ffigures\u002Fplutchik-wheel.png \"Plutchik Wheel of Emotions\")\n\nCreated by [Robert Plutchik](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FRobert_Plutchik#Plutchik's_wheel_of_emotions), this wheel is used to illustrate different emotions in a compelling and nuanced way. He suggested that there are 8 primary bipolar emotions (joy versus sadness, anger versus fear, trust versus disgust, and surprise versus anticipation) with different levels of emotional intensity. For our classification task we utilize tweets from the [SemEval2018 Task 1E-c emotion classification dataset](https:\u002F\u002Fcompetitions.codalab.org\u002Fcompetitions\u002F17751) to perform multilabel classification of anger, anticipation, disgust, fear, joy, sadness, surprise, and trust. This is a difficult task that suffers from real world classification problems such as class imbalance and labeler disagreement. \n\n![semeval results](.\u002Ffigures\u002Fsemeval_results.PNG \"SemEval Plutchik results\")\n\nOn the full SemEval emotion classification dataset we find that finetuning our model on the data achieves competitive state of the art performance with no additional domain-specific feature engineering.\n\n![semeval leaderboard](.\u002Ffigures\u002Fsemeval_leaderboard.png \"SemEval leaderboard\")\n\n## ReadMe Contents\n * [Setup](#setup)\n   * [Install](#install)\n   * [Pretrained Models](#pretrained-models)\n   * [Data Downloads](#data-downloads)\n * [Usage](#usage)\n    * [Classifying Text](#classifying-text)\n      * [Classification Documentation](.\u002Fscript_docs\u002Farguments.md#running-a-classifier-arguments)\n    * [Training Language Models (+ Distributed\u002FFP16 Training)](#training-language-models-distributed-fp16-training)\n      * [Modeling Documentation](.\u002Fscript_docs\u002Farguments.md#unsupervised-lm-arguments)\n      * [Training HyperParameter Documentation](.\u002Fanalysis\u002Freproduction.md#training-set-up)\n      * [FP16 Training Information](.\u002Fanalysis\u002Freproduction.md#fp16-training)\n    * [Sentiment Transfer](#sentiment-transfer)\n      * [Transfer Documentation](.\u002Fscript_docs\u002Farguments.md#sentiment-transfer-arguments)\n    * [Classifier Finetuning](#classifier-finetuning)\n      * [Finetuning Documentation](.\u002Fscript_docs\u002Farguments.md#finetuning-a-classifier-arguments)\n    * [All Argument Documentation](.\u002Fscript_docs\u002Farguments.md)\n * [Analysis](#analysis)\n    * [Why Unsupervised Language Modeling?](.\u002Fanalysis\u002Funsupervised.md)\n      * [Difficulties of Supervised Natural Language](.\u002Fanalysis\u002Funsupervised.md#difficulties-of-supervised-natural-language)\n      * [Data Robustness](.\u002Fanalysis\u002Funsupervised.md#data-robustness)\n      * [Model\u002FOptimization Robustness](.\u002Fanalysis\u002Funsupervised.md#modeloptimization-robustness)\n  * [Reproducing Results](.\u002Fanalysis\u002Freproduction.md)\n     * [Training](.\u002Fanalysis\u002Freproduction.md#training)\n        * [Transformer Training Setup](.\u002Fanalysis\u002Freproduction.md#transformer-training-set-up)\n        * [mLSTM Training Setup](.\u002Fanalysis\u002Freproduction.md#mlstm-training-set-up)\n     * [FP16 Training](.\u002Fanalysis\u002Freproduction.md#fp16-training)\n     * [Large Model Training](.\u002Fanalysis\u002Freproduction.md#going-bigger-with-large-models)\n     * [Sentiment Transfer](.\u002Fanalysis\u002Freproduction.md#transfer)\n     * [Finetuning Classifiers](.\u002Fanalysis\u002Freproduction.md#finetuning-classifiers)\n     * [ELMo Comparison](.\u002Fanalysis\u002Freproduction.md#elmo-comparison)\n  * [Data Parallel Scalability](.\u002Fanalysis\u002Fscale.md)\n     * [PyTorch + GIL](.\u002Fanalysis\u002Fscale.md#pytorch-gil)\n  * [Open Questions](.\u002Fanalysis\u002Fquestions.md)\n * [Acknowledgement](#acknowledgement)\n * [Thanks](#thanks)\n\n## Setup\n### Install\nInstall the sentiment_discovery package with `python3 setup.py install` in order to run the modules\u002Fscripts within this repo.\n\n### Python Requirements\nAt this time we only support python3.\n * numpy\n * pytorch (>= 0.4.1)\n * pandas\n * scikit-learn\n * matplotlib\n * unidecode\n * sentencepiece\n * seaborn\n * emoji\n\n### Pretrained models\nWe've included our sentencepiece tokenizer model and vocab as a zip file:\n * [sentencepiece tokenizer](https:\u002F\u002Fdrive.google.com\u002Fopen?id=1aw_gKmowfLaGGxSrhRh0jTuC8gWIOtWP) [1MB]\n\nWe've included a transformer language model base as well as a 4096-d mlstm language model base. For examples on how to use these models please see our [finetuning](#classifier-finetuning) and [transfer](#sentiment-transfer) sections. Even though these models were trained with FP16 they can be used in FP32 training\u002Finference.\n * [FP16 Transformer LM](https:\u002F\u002Fdrive.google.com\u002Ffile\u002Fd\u002F1rQfJkHsVJEI2WgvoHzx5Ooxm0CWSjdYt\u002Fview?usp=sharing) [311MB]\n * [FP16 mLSTM LM](https:\u002F\u002Fdrive.google.com\u002Ffile\u002Fd\u002F1EEZCZ_AZX_MlAsV-2GlFqxTT-KaNT3rG\u002Fview?usp=sharing) [169MB]\n\nWe've also included classifiers trained on a subset of SemEval emotions corresponding to the 8 plutchik emotions (anger, anticipation, disgust, fear, joy, sadness, surprise, and trust): \n * [Finetuned Plutchik Transformer](https:\u002F\u002Fdrive.google.com\u002Ffile\u002Fd\u002F1rC6LWGNkHaZkuojCEWDqSKcDGwFMBTYZ\u002Fview?usp=sharing) [673MN]\n * [Finetuned Plutchik mLSTM](https:\u002F\u002Fdrive.google.com\u002Ffile\u002Fd\u002F1ieiWFrYBqzBgGPc3R36x9oL7vlj3lt2F\u002Fview?usp=sharing) [433MB]\n\nLastly, we've also included already trained classification models for SST and IMDB binary sentiment classification:\n * [Finetuned SST Transformer](https:\u002F\u002Fdrive.google.com\u002Ffile\u002Fd\u002F1-lxjFuJm_fQ_DvnxU74-35T_M8WjvrQH\u002Fview?usp=sharing) [621MB]\n * [Transferred SST mLSTM](https:\u002F\u002Fdrive.google.com\u002Ffile\u002Fd\u002F142dVGcHePvOMSojVYiRxutbYSeLu_9ym\u002Fview?usp=sharing) [325MB]\n * [Transferred IMDB mLSTM](https:\u002F\u002Fdrive.google.com\u002Fopen?id=1efsCIWQPsXwmqORZ-qs-JdtxiPOssAss) [325MB]\n\nTo use classification models that reproduce results from our original large batch language modeling paper please use the following [commit hash and set of models](https:\u002F\u002Fgithub.com\u002FNVIDIA\u002Fsentiment-discovery\u002Ftree\u002F7f5ab28918a6fc29318a30f557b9454f0f5cc26a#pretrained-models).\n\nWe did not include pretrained models leveraging ELMo. To reproduce our papers' results with ELMo, please see our [available resources](.\u002Fanalysis\u002Freproduction.md#elmo-comparison).\n \nEach file has a dictionary containing a PyTorch `state_dict` consisting of a language model (lm_encoder keys) trained on Amazon reviews and a classifier (classifier key) as well as accompanying `args` necessary to run a model with that `state_dict`. \n\n### Data Downloads\nIn the `.\u002Fdata` folder we've provided processed copies of [the Binary Stanford Sentiment Treebank (Binary SST)](https:\u002F\u002Fnlp.stanford.edu\u002Fsentiment\u002Findex.html), [IMDB Movie Review](http:\u002F\u002Fai.stanford.edu\u002F~amaas\u002Fdata\u002Fsentiment\u002F), and the [SemEval2018 Tweet Emotion](https:\u002F\u002Fcompetitions.codalab.org\u002Fcompetitions\u002F17751) datasets as part of this repository. In order to train on the amazon dataset please download the \"aggressively deduplicated data\" version from Julian McAuley's original [site](http:\u002F\u002Fjmcauley.ucsd.edu\u002Fdata\u002Famazon\u002F). Access requests to the dataset should be approved instantly. While using the dataset make sure to load it with the `--loose-json` flag.\n\n## Usage\nIn addition to providing easily reusable code of the core functionalities (models, distributed, fp16, etc.) of this work, we also provide scripts to perform the high-level functionalities of the original paper:\n * sentiment classification of input text\n * unsupervised reconstruction\u002Flanguage modeling of a corpus of text (+ script for launching distributed workers)\n * transfer of learned language model to perform sentiment analysis on a specified corpus\n * sampling from language model to generate text (possibly of fixed sentiment) + heatmap visualization of sentiment in text\n\n\u003C!--Script results will be saved\u002Flogged to the `\u003Cexperiment_dir>\u002F\u003Cexperiment_name>\u002F*` directory hierarchy.-->\n\n### Classifying text\nClassify an input csv\u002Fjson using one of our pretrained models or your own.\nPerforms classification on Binary SST by default.\nOutput classification probabilities are saved to a `.npy` file\n\n```\npython3 run_classifier.py --load_model ama_sst.pt                               # classify Binary SST\npython3 run_classifier.py --load_model ama_sst_16.pt --fp16                     # run classification in fp16\npython3 run_classifier.py --load_model ama_sst.pt --text-key \u003Ctext-column> --data \u003Cpath.csv>     # classify your own dataset\n```\n\nSee [here](.\u002Fscript_docs\u002Farguments.md#running-a-classifier-arguments) for more documentation.\n\n### Training Language Models (+ Distributed\u002FFP16 Training)\nTrain a language model on a csv\u002Fjson corpus. By default we train a weight-normalized, 4096-d mLSTM, with a 64-d character embedding.\nThis is the first step of a 2-step process to training your own sentiment classifier.\nSaves model to `lang_model.pt` by default.\n\n```\npython3 pretrain.py                                                               #train a large model on imdb\npython3 pretrain.py --model LSTM --nhid 512                                       #train a small LSTM instead\npython3 pretrain.py --fp16 --dynamic-loss-scale                                   #train a model with fp16\npython3 -m multiproc pretrain.py                                                  #distributed model training\npython3 pretrain.py --data .\u002Fdata\u002Famazon\u002Freviews.json --lazy --loose-json \\       #train a model on amazon data\n  --text-key reviewText --label-key overall --optim Adam --split 1000,1,1 \npython3 pretrain.py --tokenizer-type SentencePieceTokenizer --vocab-size 32000 \\  #train a model with our sentencepiece tokenization\n  --tokenizer-type bpe --tokenizer-path ama_32k_tokenizer.model \npython3 pretrain.py --tokenizer-type SentencePieceTokenizer --vocab-size 32000 \\  #train a transformer model with our sentencepiece tokenization\n  --tokenizer-type bpe --tokenizer-path ama_32k_tokenizer.model --model transformer \\\n  --decoder-layers 12 --decoder-embed-dim 768 --decoder-ffn-embed-dim 3072 \\\n  --decoder-learned-pos --decoder-attention-heads 8\nbash .\u002Fexperiments\u002Ftrain_mlstm_singlenode.sh                                      #run our mLSTM training script on 1 DGX-1V\nbash .\u002Fexperiments\u002Ftrain_transformer_singlenode.sh                                #run our transformer training script on 1 DGX-1V \n```\n\nFor more documentation of our language modeling functionality look [here](.\u002Fscript_docs\u002Farguments.md#unsupervised-lm-arguments)\n\nIn order to learn about our language modeling experiments and reproduce results see the [training reproduction](.\u002Fanalysis\u002Freproduction.md#training-set-up) section in analysis.\n\nFor information about how we achieve numerical stability with FP16 training see our [fp16 training](.\u002Fanalysis\u002Freproduction.md#fp16-training) analysis.\n\n### Sentiment Transfer\nGiven a trained language model, this script will featurize text from train, val, and test csv\u002Fjson's.\nIt then uses sklearn logistic regression to fit a classifier to predict sentiment from these features.\nLastly it performs feature selection to try and fit a regression model to the top n most relevant neurons (features).\nBy default only one neuron is used for this second regression.\n\n```\npython3 transfer.py --load mlstm.pt                                 #performs transfer to SST, saves results to `\u003Cmodel>_transfer\u002F` directory\npython3 transfer.py --load mlstm.pt --neurons 5                     #use 5 neurons for the second regression\npython3 transfer.py --load mlstm.pt --fp16                          #run model in fp16 for featurization step\nbash .\u002Fexperiments\u002Frun_sk_sst.sh                                    #run transfer learning with mlstm on imdb dataset\nbash .\u002Fexperiments\u002Frun_sk_imdb.sh                                   #run transfer learning with mlstm on sst dataset\n```\n\nAdditional documentation of the command line arguments available for transfer can be found [here](.\u002Fscript_docs\u002Farguments.md#sentiment-transfer-arguments)\n \n### Classifier Finetuning\nGiven a trained language model and classification dataset, this script will build a classifier that leverages the trained language model as a text feature encoder.\nThe difference between this script and `transfer.py` is that the model training is performed end to end: the loss from the classifier is backpropagated into the language model encoder as well.\nThis script allows one to build more complex classification models, metrics, and loss functions than `transfer.py`.\nThis script supports building arbitrary multilable, multilayer, and multihead perceptron classifiers. Additionally it allows using language modeling as an auxiliary task loss during training and multihead variance as an auxiliary loss during training.\nLastly this script supports automatically selecting classification thresholds from validation performance. To measure validation performance this script includes more complex metrics including: f1-score, mathew correlation coefficient, jaccard index, recall, precision, and accuracy.\n\n```\npython3 finetune_classifier.py --load mlstm.pt --lr 2e-5 --aux-lm-loss --aux-lm-loss-weight .02   #finetune mLSTM model on sst (default dataset) with auxiliary loss\npython3 finetune_classifier.py --load mlstm.pt --automatic-thresholding --threshold-metric f1     #finetune mLSTM model on sst and automatically select classification thresholds based on the validation f1 score\npython3 finetune_classifier.py --tokenizer-type SentencePieceTokenizer --vocab-size 32000 \\       #finetune transformer with sentencepiece on SST\n  --tokenizer-type bpe tokenizer-path ama_32k_tokenizer.model --model transformer --lr 2e-5 \\\n  --decoder-layers 12 --decoder-embed-dim 768 --decoder-ffn-embed-dim 3072 \\\n  --decoder-learned-pos --decoder-attention-heads 8 --load transformer.pt --use-final-embed\npython3 finetune_classifier.py --automatic-thresholding --non-binary-cols l1 l2 l3 --lr 2e-5\\     #finetune multilayer classifier with 3 classes and 4 heads per class on some custom dataset and automatically select classfication thresholds\n  --classifier-hidden-layers 2048 1024 3 --heads-per-class 4 --aux-head-variance-loss-weight 1.   #`aux-head-variance-loss-weight` is an auxiliary loss to increase the variance between each of the 4 head's weights\n  --data \u003Ccustom_train>.csv --val \u003Ccustom_val>.csv --test \u003Ccustom_test>.csv --load mlstm.pt\nbash .\u002Fexperiments\u002Fse_transformer_multihead.sh                                                    #finetune a multihead transformer on 8 semeval categories\n```\n\nSee how to reproduce our finetuning experiments in the [finetuning reproduction](.\u002Fanalysis\u002Freproduction.md#finetuning-classifiers) section of analysis.\n\nAdditional documentation of the command line arguments available for `finetune_classifier.py` can be found [here](.\u002Fscript_docs\u002Farguments.md#finetuning-a-classifier-arguments)\n\n## [Analysis](.\u002Fanalysis\u002F)\n * [Why Unsupervised Language Modeling?](.\u002Fanalysis\u002Funsupervised.md)\n   * [Difficulties of Supervised Natural Language](.\u002Fanalysis\u002Funsupervised.md#difficulties-of-supervised-natural-language)\n   * [Data Robustness](.\u002Fanalysis\u002Funsupervised.md#data-robustness)\n   * [Model\u002FOptimization Robustness](.\u002Fanalysis\u002Funsupervised.md#modeloptimization-robustness)\n * [Reproducing Results](.\u002Fanalysis\u002Freproduction.md)\n   * [Training](.\u002Fanalysis\u002Freproduction.md#training)\n     * [Transformer Training Setup](.\u002Fanalysis\u002Freproduction.md#transformer-training-set-up)\n     * [mLSTM Training Setup](.\u002Fanalysis\u002Freproduction.md#mlstm-training-set-up)\n   * [FP16 Training](.\u002Fanalysis\u002Freproduction.md#fp16-training) \n   * [Large Model Training](.\u002Fanalysis\u002Freproduction.md#going-bigger-with-large-models)\n   * [Sentiment Transfer](.\u002Fanalysis\u002Freproduction.md#transfer)\n   * [Finetuning Classifiers](.\u002Fanalysis\u002Freproduction.md#finetuning-classifiers)\n   * [ELMo Comparison](.\u002Fanalysis\u002Freproduction.md#elmo-comparison)\n * [Data Parallel Scalability](.\u002Fanalysis\u002Fscale.md)\n   * [PyTorch + GIL](.\u002Fanalysis\u002Fscale.md#pytorch-gil)\n * [Open Questions](.\u002Fanalysis\u002Fquestions.md)\n\n## Acknowledgement\nA special thanks to our amazing summer intern [Neel Kant](https:\u002F\u002Fgithub.com\u002Fkantneel) for all the work he did with transformers, tokenization, and pretraining+finetuning classification models.\n\nA special thanks to [@csarofeen](https:\u002F\u002Fgithub.com\u002Fcsarofeen) and [@Michael Carilli](https:\u002F\u002Fgithub.com\u002Fmcarilli) for their help developing and documenting our RNN interface, Distributed Data Parallel model, and fp16 optimizer. The latest versions of these utilities can be found at the [APEx github page](https:\u002F\u002Fgithub.com\u002FNVIDIA\u002Fapex).\n\nThanks to [@guillitte](https:\u002F\u002Fgithub.com\u002Fguillitte) for providing a lightweight pytorch [port](https:\u002F\u002Fgithub.com\u002Fguillitte\u002Fpytorch-sentiment-neuron) of openai's sentiment-neuron repo.\n\nThis project uses the [amazon review dataset](http:\u002F\u002Fjmcauley.ucsd.edu\u002Fdata\u002Famazon\u002F) collected by J. McAuley\n\n\n## Thanks\nWant to help out? Open up an issue with questions\u002Fsuggestions or pull requests ranging from minor fixes to new functionality.\n\n**May your learning be Deep and Unsupervised.**\n","# ** 已弃用 **\n此仓库已被弃用。请访问 [Megatron-LM](https:\u002F\u002Fgithub.com\u002FNVIDIA\u002FMegatron-LM) 获取我们最新的大规模无监督预训练和微调代码。\n\n如果您仍希望使用此代码库，请查看我们的标记版本，并安装在该日期公开可用的所需软件\u002F依赖项。\n\n\n# PyTorch 无监督情感发现\n本代码库包含预训练的二元情感分类模型和多模态情绪分类模型，以及用于复现我们一系列大规模预训练+迁移NLP论文结果的代码：_《大规模语言建模：四小时内收敛至40GB文本》_(https:\u002F\u002Fnv-adlr.github.io\u002Fpublication\u002F2018-large-batch-lm) 和 _《基于大型预训练语言模型的实际文本分类》_(https:\u002F\u002Farxiv.org\u002Fabs\u002F1812.01207)。这项工作源于对复现、分析并扩展OpenAI的[生成评论与发现情感](https:\u002F\u002Fgithub.com\u002Fopenai\u002Fgenerating-reviews-discovering-sentiment)论文的渴望。\n\n本仓库中采用的技术具有通用性，我们易于使用的命令行界面可用于在您自己的复杂分类数据集上训练最先进的分类模型。\n本代码库支持混合精度训练，以及针对语言模型的分布式、多GPU、多节点训练（支持基于NVIDIA的[APEx](https:\u002F\u002Fgithub.com\u002FNVIDIA\u002Fapex)项目）。除了训练语言模型外，该代码库还可用于轻松地将已训练好的模型迁移到自定义文本分类数据集上进行微调。\n\n例如，我们用PyTorch实现了一个[Transformer](https:\u002F\u002Farxiv.org\u002Fabs\u002F1706.03762)语言模型，用于对大型文本数据集（如[亚马逊评论数据集](http:\u002F\u002Fjmcauley.ucsd.edu\u002Fdata\u002Famazon\u002F)）进行无监督建模。我们还支持其他分词方法，如字符级或sentencepiece分词，以及使用各种循环架构的语言模型。\n学习到的语言模型可以迁移到其他自然语言处理（NLP）任务中，用于对文本样本进行特征提取。这些特征提供了一个强大的判别式语言任务初始化点，在仅有少量标注样本的情况下即可实现具有竞争力的任务性能。例如，我们考虑在普鲁奇克情绪轮的一部分基础上，对多模态情绪分类这一困难任务进行微调。\n\n![plutchik fig](.\u002Ffigures\u002Fplutchik-wheel.png \"普鲁奇克情绪轮\")\n\n由[罗伯特·普鲁奇克](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FRobert_Plutchik#Plutchik's_wheel_of_emotions)创建的情绪轮以引人入胜且细腻的方式展示了不同的情绪。他提出存在8种主要的双极情绪（喜悦与悲伤、愤怒与恐惧、信任与厌恶、惊讶与期待），每种情绪都有不同的强度级别。对于我们的分类任务，我们使用来自[SemEval2018 Task 1E-c情绪分类数据集](https:\u002F\u002Fcompetitions.codalab.org\u002Fcompetitions\u002F17751)的推文，执行愤怒、期待、厌恶、恐惧、喜悦、悲伤、惊讶和信任的多标签分类。这是一项困难的任务，受到现实世界分类问题的影响，如类别不平衡和标注者意见不一致。\n\n![semeval results](.\u002Ffigures\u002Fsemeval_results.PNG \"SemEval 普鲁奇克结果\")\n\n在完整的SemEval情绪分类数据集中，我们发现仅通过对数据进行微调，我们的模型就能在无需额外领域特定特征工程的情况下达到具有竞争力的最新水平性能。\n\n![semeval leaderboard](.\u002Ffigures\u002Fsemeval_leaderboard.png \"SemEval排行榜\")\n\n## ReadMe 目录\n * [设置](#setup)\n   * [安装](#install)\n   * [预训练模型](#pretrained-models)\n   * [数据下载](#data-downloads)\n * [使用](#usage)\n    * [文本分类](#classifying-text)\n      * [分类文档](.\u002Fscript_docs\u002Farguments.md#running-a-classifier-arguments)\n    * [训练语言模型（+ 分布式\u002FFP16训练）](#training-language-models-distributed-fp16-training)\n      * [建模文档](.\u002Fscript_docs\u002Farguments.md#unsupervised-lm-arguments)\n      * [训练超参数文档](.\u002Fanalysis\u002Freproduction.md#training-set-up)\n      * [FP16训练信息](.\u002Fanalysis\u002Freproduction.md#fp16-training)\n    * [情感迁移](#sentiment-transfer)\n      * [迁移文档](.\u002Fscript_docs\u002Farguments.md#sentiment-transfer-arguments)\n    * [分类器微调](#classifier-finetuning)\n      * [微调文档](.\u002Fscript_docs\u002Farguments.md#finetuning-a-classifier-arguments)\n    * [所有参数文档](.\u002Fscript_docs\u002Farguments.md)\n * [分析](#analysis)\n    * [为何选择无监督语言建模？](.\u002Fanalysis\u002Funsupervised.md)\n      * [有监督自然语言的难点](.\u002Fanalysis\u002Funsupervised.md#difficulties-of-supervised-natural-language)\n      * [数据鲁棒性](.\u002Fanalysis\u002Funsupervised.md#data-robustness)\n      * [模型\u002F优化鲁棒性](.\u002Fanalysis\u002Funsupervised.md#modeloptimization-robustness)\n  * [复现结果](.\u002Fanalysis\u002Freproduction.md)\n     * [训练](.\u002Fanalysis\u002Freproduction.md#training)\n        * [Transformer训练设置](.\u002Fanalysis\u002Freproduction.md#transformer-training-set-up)\n        * [mLSTM训练设置](.\u002Fanalysis\u002Freproduction.md#mlstm-training-set-up)\n     * [FP16训练](.\u002Fanalysis\u002Freproduction.md#fp16-training)\n     * [大模型训练](.\u002Fanalysis\u002Freproduction.md#going-bigger-with-large-models)\n     * [情感迁移](.\u002Fanalysis\u002Freproduction.md#transfer)\n     * [分类器微调](.\u002Fanalysis\u002Freproduction.md#finetuning-classifiers)\n     * [ELMo对比](.\u002Fanalysis\u002Freproduction.md#elmo-comparison)\n  * [数据并行可扩展性](.\u002Fanalysis\u002Fscale.md)\n     * [PyTorch + GIL](.\u002Fanalysis\u002Fscale.md#pytorch-gil)\n  * [开放问题](.\u002Fanalysis\u002Fquestions.md)\n * [致谢](#acknowledgement)\n * [感谢](#thanks)\n\n## 设置\n### 安装\n运行`python3 setup.py install`来安装sentiment_discovery包，以便在此仓库内运行模块\u002F脚本。\n\n### Python要求\n目前我们仅支持Python 3。\n * numpy\n * pytorch (>= 0.4.1)\n * pandas\n * scikit-learn\n * matplotlib\n * unidecode\n * sentencepiece\n * seaborn\n * emoji\n\n### 预训练模型\n我们已将 SentencePiece 分词器模型及其词汇表打包成一个 ZIP 文件：\n * [SentencePiece 分词器](https:\u002F\u002Fdrive.google.com\u002Fopen?id=1aw_gKmowfLaGGxSrhRh0jTuC8gWIOtWP) [1MB]\n\n我们还提供了 Transformer 语言模型基础版本以及一个 4096 维的 mLSTM 语言模型基础版本。有关如何使用这些模型的示例，请参阅我们的 [微调](#classifier-finetuning) 和 [迁移](#sentiment-transfer) 部分。尽管这些模型是用 FP16 训练的，但它们同样可以在 FP32 的训练或推理中使用。\n * [FP16 Transformer LM](https:\u002F\u002Fdrive.google.com\u002Ffile\u002Fd\u002F1rQfJkHsVJEI2WgvoHzx5Ooxm0CWSjdYt\u002Fview?usp=sharing) [311MB]\n * [FP16 mLSTM LM](https:\u002F\u002Fdrive.google.com\u002Ffile\u002Fd\u002F1EEZCZ_AZX_MlAsV-2GlFqxTT-KaNT3rG\u002Fview?usp=sharing) [169MB]\n\n此外，我们还提供了在 SemEval 情感数据子集上训练的分类器，对应普鲁奇克的八种情感（愤怒、期待、厌恶、恐惧、喜悦、悲伤、惊讶和信任）：\n * [微调后的普鲁奇克 Transformer](https:\u002F\u002Fdrive.google.com\u002Ffile\u002Fd\u002F1rC6LWGNkHaZkuojCEWDqSKcDGwFMBTYZ\u002Fview?usp=sharing) [673MN]\n * [微调后的普鲁奇克 mLSTM](https:\u002F\u002Fdrive.google.com\u002Ffile\u002Fd\u002F1ieiWFrYBqzBgGPc3R36x9oL7vlj3lt2F\u002Fview?usp=sharing) [433MB]\n\n最后，我们还提供了针对 SST 和 IMDB 二元情感分类的预训练分类模型：\n * [微调后的 SST Transformer](https:\u002F\u002Fdrive.google.com\u002Ffile\u002Fd\u002F1-lxjFuJm_fQ_DvnxU74-35T_M8WjvrQH\u002Fview?usp=sharing) [621MB]\n * [迁移后的 SST mLSTM](https:\u002F\u002Fdrive.google.com\u002Ffile\u002Fd\u002F142dVGcHePvOMSojVYiRxutbYSeLu_9ym\u002Fview?usp=sharing) [325MB]\n * [迁移后的 IMDB mLSTM](https:\u002F\u002Fdrive.google.com\u002Fopen?id=1efsCIWQPsXwmqORZ-qs-JdtxiPOssAss) [325MB]\n\n若要使用能够复现我们原始大批次语言建模论文结果的分类模型，请使用以下 [commit hash 和模型集合](https:\u002F\u002Fgithub.com\u002FNVIDIA\u002Fsentiment-discovery\u002Ftree\u002F7f5ab28918a6fc29318a30f557b9454f0f5cc26a#pretrained-models)。\n\n我们未包含利用 ELMo 的预训练模型。如需使用 ELMo 复现论文结果，请参阅我们的 [可用资源](.\u002Fanalysis\u002Freproduction.md#elmo-comparison)。\n\n每个文件都包含一个字典，其中含有 PyTorch 的 `state_dict`，包括基于亚马逊评论训练的语言模型（lm_encoder 键）和分类器（classifier 键），以及运行该 `state_dict` 所需的配套 `args`。\n\n### 数据下载\n在 `.\u002Fdata` 文件夹中，我们提供了 [二元斯坦福情感树库（Binary SST）](https:\u002F\u002Fnlp.stanford.edu\u002Fsentiment\u002Findex.html)、[IMDB 电影评论](http:\u002F\u002Fai.stanford.edu\u002F~amaas\u002Fdata\u002Fsentiment\u002F) 和 [SemEval2018 推文情感竞赛](https:\u002F\u002Fcompetitions.codalab.org\u002Fcompetitions\u002F17751) 数据集的处理后副本，作为本仓库的一部分。若要使用亚马逊数据集进行训练，请从朱利安·麦考利的原始 [网站](http:\u002F\u002Fjmcauley.ucsd.edu\u002Fdata\u002Famazon\u002F) 下载“激进去重版”数据。对该数据集的访问请求通常会立即获批。使用该数据集时，请务必加上 `--loose-json` 标志加载。\n\n## 使用方法\n除了提供本工作的核心功能（模型、分布式、FP16 等）的可重复使用代码外，我们还提供了用于执行原始论文中高层次功能的脚本：\n * 对输入文本进行情感分类\n * 对语料库中的文本进行无监督重建\u002F语言建模（并附有启动分布式工作节点的脚本）\n * 将学习到的语言模型迁移到指定语料库以进行情感分析\n * 从语言模型中采样生成文本（可能具有固定的情感倾向），并可视化文本中的情感热图\n\n\u003C!--脚本结果将保存\u002F记录到 `\u003Cexperiment_dir>\u002F\u003Cexperiment_name>\u002F*` 目录层级中。-->\n\n### 文本分类\n使用我们的预训练模型或您自己的模型对输入的 CSV\u002FJSON 文件进行分类。\n默认情况下会对 Binary SST 进行分类。\n分类概率输出将保存为 `.npy` 文件。\n\n```\npython3 run_classifier.py --load_model ama_sst.pt                               # 对 Binary SST 进行分类\npython3 run_classifier.py --load_model ama_sst_16.pt --fp16                     # 以 FP16 运行分类\npython3 run_classifier.py --load_model ama_sst.pt --text-key \u003Ctext-column> --data \u003Cpath.csv>     # 对您自己的数据集进行分类\n```\n\n更多文档请参见 [这里](.\u002Fscript_docs\u002Farguments.md#running-a-classifier-arguments)。\n\n### 训练语言模型（含分布式\u002FFP16 训练）\n对 CSV\u002FJSON 语料库训练语言模型。默认情况下，我们将训练一个权重归一化的 4096 维 mLSTM，其字符嵌入维度为 64。\n这是训练您自己的情感分类器的两步过程的第一步。\n默认情况下，模型将保存为 `lang_model.pt`。\n\n```\npython3 pretrain.py                                                               # 在 IMDB 数据上训练大型模型\npython3 pretrain.py --model LSTM --nhid 512                                       # 改为训练小型 LSTM\npython3 pretrain.py --fp16 --dynamic-loss-scale                                   # 以 FP16 训练模型\npython3 -m multiproc pretrain.py                                                  # 分布式模型训练\npython3 pretrain.py --data .\u002Fdata\u002Famazon\u002Freviews.json --lazy --loose-json \\       # 在亚马逊数据上训练模型\n  --text-key reviewText --label-key overall --optim Adam --split 1000,1,1 \npython3 pretrain.py --tokenizer-type SentencePieceTokenizer --vocab-size 32000 \\  # 使用我们的 SentencePiece 分词训练模型\n  --tokenizer-type bpe --tokenizer-path ama_32k_tokenizer.model \npython3 pretrain.py --tokenizer-type SentencePieceTokenizer --vocab-size 32000 \\  # 使用 SentencePiece 分词训练 Transformer 模型\n  --tokenizer-type bpe --tokenizer-path ama_32k_tokenizer.model --model transformer \\\n  --decoder-layers 12 --decoder-embed-dim 768 --decoder-ffn-embed-dim 3072 \\\n  --decoder-learned-pos --decoder-attention-heads 8\nbash .\u002Fexperiments\u002Ftrain_mlstm_singlenode.sh                                      # 在一台 DGX-1V 上运行我们的 mLSTM 训练脚本\nbash .\u002Fexperiments\u002Ftrain_transformer_singlenode.sh                                # 在一台 DGX-1V 上运行我们的 Transformer 训练脚本 \n```\n\n有关语言建模功能的更多文档，请参阅 [这里](.\u002Fscript_docs\u002Farguments.md#unsupervised-lm-arguments)。\n\n如需了解我们的语言建模实验并复现结果，请参阅分析部分的 [训练复现](.\u002Fanalysis\u002Freproduction.md#training-set-up) 章节。\n\n有关我们如何通过 FP16 训练实现数值稳定性的信息，请参阅我们的 [FP16 训练](.\u002Fanalysis\u002Freproduction.md#fp16-training) 分析。\n\n### 情感迁移\n给定一个训练好的语言模型，此脚本将对训练集、验证集和测试集的 CSV\u002FJSON 文件中的文本进行特征提取。然后使用 scikit-learn 的逻辑回归来拟合一个分类器，以根据这些特征预测情感。最后，它会进行特征选择，尝试用最相关的前 n 个神经元（特征）来拟合回归模型。默认情况下，第二次回归只使用一个神经元。\n\n```\npython3 transfer.py --load mlstm.pt                                 # 将模型迁移到 SST 数据集，并将结果保存到 `\u003Cmodel>_transfer\u002F` 目录\npython3 transfer.py --load mlstm.pt --neurons 5                     # 使用 5 个神经元进行第二次回归\npython3 transfer.py --load mlstm.pt --fp16                          # 在特征提取步骤中以 fp16 精度运行模型\nbash .\u002Fexperiments\u002Frun_sk_sst.sh                                    # 在 IMDb 数据集上使用 mlstm 进行情感迁移\nbash .\u002Fexperiments\u002Frun_sk_imdb.sh                                   # 在 SST 数据集上使用 mlstm 进行情感迁移\n```\n\n有关迁移命令行参数的更多文档，请参阅 [这里](.\u002Fscript_docs\u002Farguments.md#sentiment-transfer-arguments)。\n\n### 分类器微调\n给定一个训练好的语言模型和分类数据集，此脚本将构建一个分类器，利用训练好的语言模型作为文本特征编码器。与 `transfer.py` 的区别在于，该脚本的模型训练是端到端进行的：分类器的损失也会反向传播到语言模型编码器中。与 `transfer.py` 相比，此脚本允许构建更复杂的分类模型、指标和损失函数。该脚本支持构建任意多标签、多层和多头感知机分类器。此外，它还允许在训练过程中使用语言建模作为辅助任务损失，以及使用多头方差作为辅助损失。最后，该脚本支持根据验证集的表现自动选择分类阈值。为了衡量验证集的表现，该脚本包含了更复杂的指标，包括 F1 分数、马修斯相关系数、雅卡尔指数、召回率、精确率和准确率。\n\n```\npython3 finetune_classifier.py --load mlstm.pt --lr 2e-5 --aux-lm-loss --aux-lm-loss-weight .02   # 在 SST 数据集上对 mLSTM 模型进行微调，并加入辅助损失\npython3 finetune_classifier.py --load mlstm.pt --automatic-thresholding --threshold-metric f1     # 在 SST 数据集上微调 mLSTM 模型，并根据验证集的 F1 分数自动选择分类阈值\npython3 finetune_classifier.py --tokenizer-type SentencePieceTokenizer --vocab-size 32000 \\       # 在 SST 数据集上使用 SentencePiece 对 Transformer 模型进行微调\n  --tokenizer-type bpe tokenizer-path ama_32k_tokenizer.model --model transformer --lr 2e-5 \\\n  --decoder-layers 12 --decoder-embed-dim 768 --decoder-ffn-embed-dim 3072 \\\n  --decoder-learned-pos --decoder-attention-heads 8 --load transformer.pt --use-final-embed\npython3 finetune_classifier.py --automatic-thresholding --non-binary-cols l1 l2 l3 --lr 2e-5\\     # 在某个自定义数据集上微调一个具有 3 个类别、每类 4 个头的多层分类器，并自动选择分类阈值\n  --classifier-hidden-layers 2048 1024 3 --heads-per-class 4 --aux-head-variance-loss-weight 1.   # `aux-head-variance-loss-weight` 是一种辅助损失，用于增加每个头权重之间的差异\n  --data \u003Ccustom_train>.csv --val \u003Ccustom_val>.csv --test \u003Ccustom_test>.csv --load mlstm.pt\nbash .\u002Fexperiments\u002Fse_transformer_multihead.sh                                                    # 在 8 个 SemEval 类别上微调一个多头 Transformer 模型\n```\n\n请参阅分析部分的 [微调复现](.\u002Fanalysis\u002Freproduction.md#finetuning-classifiers) 部分，了解如何重现我们的微调实验。\n\n有关 `finetune_classifier.py` 可用命令行参数的更多文档，请参阅 [这里](.\u002Fscript_docs\u002Farguments.md#finetuning-a-classifier-arguments)。\n\n## [分析](.\u002Fanalysis\u002F)\n * [为什么选择无监督语言建模？](.\u002Fanalysis\u002Funsupervised.md)\n   * [有监督自然语言处理的难点](.\u002Fanalysis\u002Funsupervised.md#difficulties-of-supervised-natural-language)\n   * [数据鲁棒性](.\u002Fanalysis\u002Funsupervised.md#data-robustness)\n   * [模型\u002F优化鲁棒性](.\u002Fanalysis\u002Funsupervised.md#modeloptimization-robustness)\n * [结果复现](.\u002Fanalysis\u002Freproduction.md)\n   * [训练](.\u002Fanalysis\u002Freproduction.md#training)\n     * [Transformer 训练设置](.\u002Fanalysis\u002Freproduction.md#transformer-training-set-up)\n     * [mLSTM 训练设置](.\u002Fanalysis\u002Freproduction.md#mlstm-training-set-up)\n   * [FP16 训练](.\u002Fanalysis\u002Freproduction.md#fp16-training) \n   * [大模型训练](.\u002Fanalysis\u002Freproduction.md#going-bigger-with-large-models)\n   * [情感迁移](.\u002Fanalysis\u002Freproduction.md#transfer)\n   * [分类器微调](.\u002Fanalysis\u002Freproduction.md#finetuning-classifiers)\n   * [ELMo 对比](.\u002Fanalysis\u002Freproduction.md#elmo-comparison)\n * [数据并行扩展性](.\u002Fanalysis\u002Fscale.md)\n   * [PyTorch + GIL](.\u002Fanalysis\u002Fscale.md#pytorch-gil)\n * [未解决问题](.\u002Fanalysis\u002Fquestions.md)\n\n## 致谢\n特别感谢我们出色的暑期实习生 [Neel Kant](https:\u002F\u002Fgithub.com\u002Fkantneel)，他在 Transformer、分词以及预训练和微调分类模型方面所做的大量工作。\n\n还要特别感谢 [@csarofeen](https:\u002F\u002Fgithub.com\u002Fcsarofeen) 和 [@Michael Carilli](https:\u002F\u002Fgithub.com\u002Fmcarilli)，他们在开发和记录我们的 RNN 接口、分布式数据并行模型和 fp16 优化器方面提供的帮助。这些工具的最新版本可以在 [APEx GitHub 页面](https:\u002F\u002Fgithub.com\u002FNVIDIA\u002Fapex) 上找到。\n\n感谢 [@guillitte](https:\u002F\u002Fgithub.com\u002Fguillitte)，他提供了 OpenAI 情感神经元仓库的一个轻量级 PyTorch [移植版](https:\u002F\u002Fgithub.com\u002Fguillitte\u002Fpytorch-sentiment-neuron)。\n\n该项目使用了由 J. McAuley 收集的 [亚马逊评论数据集](http:\u002F\u002Fjmcauley.ucsd.edu\u002Fdata\u002Famazon\u002F)。\n\n## 感谢\n想帮忙吗？可以开一个议题提出问题或建议，也可以提交从轻微修复到新功能的各种拉取请求。\n\n**愿你的学习深入而无监督。**","# sentiment-discovery 快速上手指南\n\n> **⚠️ 重要提示**：该仓库已官方标记为**弃用 (DEPRECATED)**。NVIDIA 建议用户迁移至 [Megatron-LM](https:\u002F\u002Fgithub.com\u002FNVIDIA\u002FMegatron-LM) 以获取最新的大规模无监督预训练和微调代码。如果您仍需使用本工具，请参考其历史发布版本安装当时公开的依赖项。\n\n本工具基于 PyTorch，提供了预训练的情感分类和多模态情绪分类模型，支持大规模文本的无监督语言建模及迁移学习。\n\n## 1. 环境准备\n\n### 系统要求\n- **Python**: 仅支持 Python 3\n- **GPU**: 推荐使用 NVIDIA GPU 以加速训练和推理（支持混合精度 FP16 和多卡分布式训练）\n\n### 前置依赖\n在安装主程序前，请确保已安装以下 Python 库：\n- `numpy`\n- `pytorch` (版本 >= 0.4.1)\n- `pandas`\n- `scikit-learn`\n- `matplotlib`\n- `unidecode`\n- `sentencepiece`\n- `seaborn`\n- `emoji`\n\n> **国内加速建议**：建议使用清华或阿里镜像源安装依赖，例如：\n> ```bash\n> pip install -i https:\u002F\u002Fpypi.tuna.tsinghua.edu.cn\u002Fsimple numpy pandas scikit-learn matplotlib unidecode sentencepiece seaborn emoji\n> ```\n> PyTorch 安装请参考 [PyTorch 官网](https:\u002F\u002Fpytorch.org\u002F) 选择对应的 CUDA 版本命令。\n\n## 2. 安装步骤\n\n克隆仓库并安装 `sentiment_discovery` 包：\n\n```bash\ngit clone https:\u002F\u002Fgithub.com\u002FNVIDIA\u002Fsentiment-discovery.git\ncd sentiment-discovery\npython3 setup.py install\n```\n\n### 下载预训练模型与分词器\n本工具依赖外部下载的预训练模型文件。您需要手动下载以下文件（通过 Google Drive 链接）：\n\n1. **分词器模型** (SentencePiece): [下载链接](https:\u002F\u002Fdrive.google.com\u002Fopen?id=1aw_gKmowfLaGGxSrhRh0jTuC8gWIOtWP)\n2. **语言模型基座** (可选):\n   - FP16 Transformer LM: [下载链接](https:\u002F\u002Fdrive.google.com\u002Ffile\u002Fd\u002F1rQfJkHsVJEI2WgvoHzx5Ooxm0CWSjdYt\u002Fview?usp=sharing)\n   - FP16 mLSTM LM: [下载链接](https:\u002F\u002Fdrive.google.com\u002Ffile\u002Fd\u002F1EEZCZ_AZX_MlAsV-2GlFqxTT-KaNT3rG\u002Fview?usp=sharing)\n3. **微调后的分类器** (可选，如 SST\u002FIMDB\u002FPlutchik 情绪分类): 详见 README \"Pretrained models\" 章节。\n\n下载后，请将模型文件放置在项目目录或指定路径中。\n\n## 3. 基本使用\n\n### 场景一：文本情感分类\n使用预训练模型对 CSV 或 JSON 格式的数据进行情感分类。默认针对 Binary SST 数据集，也可用于自定义数据。\n\n**示例 1：分类默认数据集 (Binary SST)**\n```bash\npython3 run_classifier.py --load_model ama_sst.pt\n```\n\n**示例 2：使用 FP16 加速推理**\n```bash\npython3 run_classifier.py --load_model ama_sst_16.pt --fp16\n```\n\n**示例 3：分类自定义数据集**\n假设您的数据位于 `data.csv`，文本列名为 `review_text`：\n```bash\npython3 run_classifier.py --load_model ama_sst.pt --text-key review_text --data data.csv\n```\n*输出结果将保存为 `.npy` 文件。*\n\n### 场景二：训练语言模型 (无监督预训练)\n这是构建自定义情感分类器的第一步。默认训练一个 4096 维的 mLSTM 模型。\n\n**示例 1：在 IMDB 数据集上训练大型模型**\n```bash\npython3 pretrain.py\n```\n\n**示例 2：训练小型 LSTM 模型**\n```bash\npython3 pretrain.py --model LSTM --nhid 512\n```\n\n**示例 3：开启混合精度 (FP16) 训练**\n```bash\npython3 pretrain.py --fp16 --dynamic-loss-scale\n```\n\n**示例 4：分布式多卡训练**\n```bash\npython3 -m multiproc pretrain.py\n```\n\n**示例 5：在 Amazon 评论数据上训练 (需先下载数据)**\n```bash\npython3 pretrain.py --data .\u002Fdata\u002Famazon\u002Freviews.json --lazy --loose-json \\\n  --text-key reviewText --label-key overall --optim Adam --split 1000,1,1\n```\n\n**示例 6：使用 SentencePiece 分词器训练**\n```bash\npython3 pretrain.py --tokenizer-type SentencePieceTokenizer --vocab-size 32000 \\\n  --tokenizer-path ama_32k_tokenizer.model\n```\n\n*训练完成的模型默认保存为 `lang_model.pt`。*\n\n### 场景三：模型微调 (Transfer Learning)\n利用预训练的语言模型，在少量标注数据上微调以获得高性能分类器（具体参数请参考 `script_docs\u002Farguments.md` 中的 \"Finetuning a classifier\" 部分）。","某电商数据团队需要快速构建一个能精准识别用户评论中复杂情绪（如愤怒、失望、惊喜等）的分析系统，以应对突发舆情。\n\n### 没有 sentiment-discovery 时\n- **标注成本高昂**：面对海量未标记的用户评论，团队需人工标注数万条数据才能训练基础模型，耗时数周且费用巨大。\n- **细粒度情绪识别难**：传统二分类模型（仅正面\u002F负面）无法区分“愤怒”与“悲伤”等细微差别，导致运营策略缺乏针对性。\n- **冷启动效果差**：在新业务线缺乏历史标注数据时，模型因训练样本不足而准确率极低，难以投入生产。\n- **领域适配慢**：针对特定商品类别的语境变化，重新训练模型需要大量算力资源和漫长的调优周期。\n\n### 使用 sentiment-discovery 后\n- **无需标注即可启动**：利用其大规模无监督预训练能力，直接对海量原始评论进行建模，省去了繁琐的人工标注环节。\n- **支持多维情绪分类**：基于普鲁奇克情绪轮（Plutchik Wheel）的微调功能，可精准识别愤怒、恐惧、信任等 8 种具体情绪，洞察更深层用户心理。\n- **小样本高效迁移**：凭借强大的特征提取能力，仅需少量标注样本即可完成迁移学习，在新场景下迅速达到业界领先的准确率。\n- **训练效率显著提升**：支持混合精度和多 GPU 分布式训练，大幅缩短模型迭代时间，让团队能快速响应市场变化。\n\nsentiment-discovery 通过无监督预训练与小样本微调的结合，将情绪分析从“劳动密集型”的数据标注工作转变为高效的智能化决策工具。","https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FNVIDIA_sentiment-discovery_1fa0c490.png","NVIDIA","NVIDIA Corporation","https:\u002F\u002Foss.gittoolsai.com\u002Favatars\u002FNVIDIA_7dcf6000.png","",null,"https:\u002F\u002Fnvidia.com","https:\u002F\u002Fgithub.com\u002FNVIDIA",[22,26],{"name":23,"color":24,"percentage":25},"Python","#3572A5",99.6,{"name":27,"color":28,"percentage":29},"Shell","#89e051",0.4,1071,205,"2026-03-30T05:37:46","NOASSERTION",4,"未说明","需要 NVIDIA GPU 以支持混合精度训练 (FP16) 和分布式多卡训练 (基于 NVIDIA APEX)，具体显存大小取决于模型规模 (文中提及 4096-d mLSTM 及大型 Transformer)，CUDA 版本需与安装的 PyTorch 及 APEX 兼容",{"notes":38,"python":39,"dependencies":40},"该仓库已弃用 (DEPRECATED)，官方建议转向使用 Megatron-LM。若仍需使用，需安装特定历史版本的依赖。支持混合精度 (FP16) 及分布式多节点训练。预训练模型和分词器需从 Google Drive 手动下载。训练亚马逊数据集时需使用 '--loose-json' 标志。","3.x (仅支持 Python 3)",[41,42,43,44,45,46,47,48,49,50],"numpy","pytorch>=0.4.1","pandas","scikit-learn","matplotlib","unidecode","sentencepiece","seaborn","emoji","nvidia-apex",[52,53],"语言模型","开发框架",3,"ready","2026-03-27T02:49:30.150509","2026-04-06T08:09:00.714195",[59,64,69,74,78,83,88],{"id":60,"question_zh":61,"answer_zh":62,"source_url":63},16159,"在 Amazon 数据集上训练时遇到 MemoryError（内存错误）怎么办？","该问题通常与数据加载过程中的内存占用过高有关。维护者指出此问题已在相关 PR（如 #32）中修复，主要涉及 Unicode 解码错误的处理和数据分片加载逻辑的优化。建议更新代码到最新 master 分支，并确保使用 `--lazy` 和 `--loose_json` 参数来减少内存占用。如果问题依旧，请检查是否已应用了针对 `lazy_loader.py` 的修复补丁。","https:\u002F\u002Fgithub.com\u002FNVIDIA\u002Fsentiment-discovery\u002Fissues\u002F31",{"id":65,"question_zh":66,"answer_zh":67,"source_url":68},16160,"如何提取预训练模型的文本嵌入（embeddings）以用于迁移学习？","用户可以编写一个简单的 PyTorch 脚本来提取嵌入。核心思路是加载模型权重，定义一个包含 `nn.Embedding` 和 `stackedRNN` (mLSTMRNNCell) 的特征提取器类。在 `forward` 方法中，遍历输入序列，通过 encoder 获取嵌入，然后传入 RNN 并收集最后的隐藏状态作为句子向量。注意：较新版本（PyTorch >= 0.3）的模型权重通常可以在不同实现间互换加载。","https:\u002F\u002Fgithub.com\u002FNVIDIA\u002Fsentiment-discovery\u002Fissues\u002F34",{"id":70,"question_zh":71,"answer_zh":72,"source_url":73},16161,"加载预训练语言模型进行情感分类时，出现 state_dict 键不匹配（Missing\u002FUnexpected keys）错误如何解决？","这通常是因为训练模型和加载模型时使用的 RNN 单元格类型或参数化方式不一致（例如权重归一化 weight_norm 的应用与否）。确保在加载模型前，模型架构的定义（如 `mLSTMRNNCell` 的参数）与训练时完全一致。如果是版本差异导致的，尝试检查是否需要手动移除或应用权重归一化，或者确认使用的 PyTorch 版本是否支持自动转换。","https:\u002F\u002Fgithub.com\u002FNVIDIA\u002Fsentiment-discovery\u002Fissues\u002F35",{"id":75,"question_zh":76,"answer_zh":77,"source_url":73},16162,"运行 classifier.py 时遇到“除以零”（divide by zero）的 RuntimeError 怎么办？","这是因为计算字符处理速度时，`elapsed_time` 可能为 0 或极小值。解决方案是修改 `classifier.py` 中的计算逻辑，将 `ch_per_s = num_char \u002F elapsed_time` 改为 `ch_per_s = num_char.float() \u002F elapsed_time` 或者添加一个极小值防止除零：`ch_per_s = num_char \u002F (elapsed_time + 1e-8)`。此外，对于 PyTorch 0.5+ 版本，需注意将 `tensor.data[0]` 改为 `tensor.item()` 以获取标量值。",{"id":79,"question_zh":80,"answer_zh":81,"source_url":82},16163,"如何使用预训练模型对单个句子进行交互式情感预测？","虽然官方尚未提供独立的轻量级脚本，但用户可以通过结合基础模型和 sklearn 分类器来实现。具体做法是：加载预训练的语言模型提取句子特征（embeddings），然后加载与之配套训练的 sklearn 模型（通常为 pickle 格式）进行预测。用户也可以参考社区提供的代码片段，自行构建一个包含编码器和分类头的简化推理脚本。","https:\u002F\u002Fgithub.com\u002FNVIDIA\u002Fsentiment-discovery\u002Fissues\u002F10",{"id":84,"question_zh":85,"answer_zh":86,"source_url":87},16164,"使用预训练模型分类时，为什么所有输出的标签都是 -1.0（负面）？","这通常是因为在使用 `classifier.py` 时，测试数据文件中缺少真实的标签列，导致程序将默认的缺失标签（-1.0）直接复制到了输出结果中，而不是显示预测概率或预测类别。解决方法是使用 `--write_results` 参数并将输出重定向到新文件，同时确保输入数据格式正确。如果目的是查看预测概率，应检查输出 CSV 中的概率列而非标签列，或者确保输入数据包含占位符标签以便程序执行完整的预测流程。","https:\u002F\u002Fgithub.com\u002FNVIDIA\u002Fsentiment-discovery\u002Fissues\u002F45",{"id":89,"question_zh":90,"answer_zh":91,"source_url":92},16165,"DataLoader 报错提示参数数量不匹配（expected 5 arguments, got 1）是什么原因？","这是一个已知的问题，通常发生在特定版本的 PyTorch（如 0.4.0）与数据处理代码不兼容时。该问题已在后续的更新（参考 Issue #31 相关的合并请求）中修复。建议将代码库更新到最新的 master 分支，以确保 `data_utils` 中的数据加载器函数签名与当前 PyTorch 版本兼容。","https:\u002F\u002Fgithub.com\u002FNVIDIA\u002Fsentiment-discovery\u002Fissues\u002F26",[94,99,104,109],{"id":95,"version":96,"summary_zh":97,"released_at":98},90818,"v0.3.large_batch_stable","本版本用于复现我们发表在[大规模语言模型](https:\u002F\u002Farxiv.org\u002Fabs\u002F1808.01371)论文中的实验结果。","2018-12-14T19:44:49",{"id":100,"version":101,"summary_zh":102,"released_at":103},90819,"v0.3","我们已将 mLSTM 模型切换为 PyTorch 内置的融合 LSTM 单元，相比此前版本中使用的未融合实现，该单元显著提升了 GPU 内存利用率（从而支持更大批量的训练），并在速度上也有小幅提升。\n\n若需将您过去训练的模型转换为兼容此版本的格式，请参阅此 [issue](https:\u002F\u002Fgithub.com\u002FNVIDIA\u002Fsentiment-discovery\u002Fissues\u002F18)。\n\n此外，我们还更新了分布式代码，以适配 PyTorch 于 4 月 3 日对 Tensor 和 Variable 做出的最新更改。","2018-04-06T19:41:22",{"id":105,"version":106,"summary_zh":107,"released_at":108},90820,"v0.2","本次发布的主要目标有两个：\n* 解决使用体验方面的顾虑\n* 在代码仓库中更新 FP16 和分布式训练的相关代码\n\n## 使用体验\n* 我们使训练和生成代码更接近 PyTorch 的语言模型示例\n* 提供用于从输入文本张量中进行情感分类的 PyTorch 分类器模块\u002F函数\n  * 为该模块提供预训练的分类器和语言模型\n  * 提供一个简单的独立分类器脚本\u002F示例，能够对输入的 CSV 或 JSON 文件进行分类，并将结果写入其他 CSV 或 JSON 文件\n* 简化目录结构，便于查找代码\n* 将可重用的 PyTorch 功能（新的 RNN API、权重归一化功能，以及未来所有的 FP16 相关功能）提取到一个独立的 Python 模块中，计划在后续发布\n\n## FP16 + 分布式\n* FP16 优化器封装器，用于按照我们的[最佳实践]（https:\u002F\u002Fgithub.com\u002FNVIDIA\u002Fsentiment-discovery\u002Fblob\u002Fmaster\u002Fanalysis\u002Freproduction.md#fp16-training）优化 FP16 模型\n  * 位于 `fp16\u002Ffp16.py`\n* 轻量级分布式封装器，支持在多 GPU 上通过 NCCL 或 Gloo 后端进行梯度规约\n  * `model\u002Fdistributed.py`\n* 分布式工作进程启动脚本\n  * `multiproc.py`","2018-03-13T19:41:40",{"id":110,"version":111,"summary_zh":112,"released_at":113},90821,"v0.1","**模块更新**\n * 在 mLSTM 模块中，通过 `fuse_lstm` 标志启用融合 LSTM 内核\n**模型更新**\n * 改进了模型序列化大小和选项\n   * 不保存梯度\n   * 优化器的保存为可选\n   * 重新加载使用权重归一化训练的权重时更加稳定\n**权重归一化\u002F重参数化更新**\n * 修改了钩子，使其与融合 LSTM 内核兼容\n**数据更新**\n * 自动解析数据集类型（csv、json 等）。只需指定是监督学习还是无监督学习即可\n * 增加了对松散 JSON 格式的支持\n * 对 csv 数据集进行了更全面的测试\n * 修复了保存处理结果时文件名的问题，现在会保留原始文件名\n * 修复了 DataParallel 和 DistributedDP 在评估数据集批处理中的问题\n * 使指定验证集和测试集更加方便\n * 使指定数据集分片更加简便\n * 为数据集增加了负长度序列的功能。","2017-12-12T19:35:02",[115,125,134,142,150,163],{"id":116,"name":117,"github_repo":118,"description_zh":119,"stars":120,"difficulty_score":54,"last_commit_at":121,"category_tags":122,"status":55},3808,"stable-diffusion-webui","AUTOMATIC1111\u002Fstable-diffusion-webui","stable-diffusion-webui 是一个基于 Gradio 构建的网页版操作界面，旨在让用户能够轻松地在本地运行和使用强大的 Stable Diffusion 图像生成模型。它解决了原始模型依赖命令行、操作门槛高且功能分散的痛点，将复杂的 AI 绘图流程整合进一个直观易用的图形化平台。\n\n无论是希望快速上手的普通创作者、需要精细控制画面细节的设计师，还是想要深入探索模型潜力的开发者与研究人员，都能从中获益。其核心亮点在于极高的功能丰富度：不仅支持文生图、图生图、局部重绘（Inpainting）和外绘（Outpainting）等基础模式，还独创了注意力机制调整、提示词矩阵、负向提示词以及“高清修复”等高级功能。此外，它内置了 GFPGAN 和 CodeFormer 等人脸修复工具，支持多种神经网络放大算法，并允许用户通过插件系统无限扩展能力。即使是显存有限的设备，stable-diffusion-webui 也提供了相应的优化选项，让高质量的 AI 艺术创作变得触手可及。",162132,"2026-04-05T11:01:52",[53,123,124],"图像","Agent",{"id":126,"name":127,"github_repo":128,"description_zh":129,"stars":130,"difficulty_score":131,"last_commit_at":132,"category_tags":133,"status":55},1381,"everything-claude-code","affaan-m\u002Feverything-claude-code","everything-claude-code 是一套专为 AI 编程助手（如 Claude Code、Codex、Cursor 等）打造的高性能优化系统。它不仅仅是一组配置文件，而是一个经过长期实战打磨的完整框架，旨在解决 AI 代理在实际开发中面临的效率低下、记忆丢失、安全隐患及缺乏持续学习能力等核心痛点。\n\n通过引入技能模块化、直觉增强、记忆持久化机制以及内置的安全扫描功能，everything-claude-code 能显著提升 AI 在复杂任务中的表现，帮助开发者构建更稳定、更智能的生产级 AI 代理。其独特的“研究优先”开发理念和针对 Token 消耗的优化策略，使得模型响应更快、成本更低，同时有效防御潜在的攻击向量。\n\n这套工具特别适合软件开发者、AI 研究人员以及希望深度定制 AI 工作流的技术团队使用。无论您是在构建大型代码库，还是需要 AI 协助进行安全审计与自动化测试，everything-claude-code 都能提供强大的底层支持。作为一个曾荣获 Anthropic 黑客大奖的开源项目，它融合了多语言支持与丰富的实战钩子（hooks），让 AI 真正成长为懂上",140436,2,"2026-04-05T23:32:43",[53,124,52],{"id":135,"name":136,"github_repo":137,"description_zh":138,"stars":139,"difficulty_score":131,"last_commit_at":140,"category_tags":141,"status":55},2271,"ComfyUI","Comfy-Org\u002FComfyUI","ComfyUI 是一款功能强大且高度模块化的视觉 AI 引擎，专为设计和执行复杂的 Stable Diffusion 图像生成流程而打造。它摒弃了传统的代码编写模式，采用直观的节点式流程图界面，让用户通过连接不同的功能模块即可构建个性化的生成管线。\n\n这一设计巧妙解决了高级 AI 绘图工作流配置复杂、灵活性不足的痛点。用户无需具备编程背景，也能自由组合模型、调整参数并实时预览效果，轻松实现从基础文生图到多步骤高清修复等各类复杂任务。ComfyUI 拥有极佳的兼容性，不仅支持 Windows、macOS 和 Linux 全平台，还广泛适配 NVIDIA、AMD、Intel 及苹果 Silicon 等多种硬件架构，并率先支持 SDXL、Flux、SD3 等前沿模型。\n\n无论是希望深入探索算法潜力的研究人员和开发者，还是追求极致创作自由度的设计师与资深 AI 绘画爱好者，ComfyUI 都能提供强大的支持。其独特的模块化架构允许社区不断扩展新功能，使其成为当前最灵活、生态最丰富的开源扩散模型工具之一，帮助用户将创意高效转化为现实。",107662,"2026-04-03T11:11:01",[53,123,124],{"id":143,"name":144,"github_repo":145,"description_zh":146,"stars":147,"difficulty_score":131,"last_commit_at":148,"category_tags":149,"status":55},3704,"NextChat","ChatGPTNextWeb\u002FNextChat","NextChat 是一款轻量且极速的 AI 助手，旨在为用户提供流畅、跨平台的大模型交互体验。它完美解决了用户在多设备间切换时难以保持对话连续性，以及面对众多 AI 模型不知如何统一管理的痛点。无论是日常办公、学习辅助还是创意激发，NextChat 都能让用户随时随地通过网页、iOS、Android、Windows、MacOS 或 Linux 端无缝接入智能服务。\n\n这款工具非常适合普通用户、学生、职场人士以及需要私有化部署的企业团队使用。对于开发者而言，它也提供了便捷的自托管方案，支持一键部署到 Vercel 或 Zeabur 等平台。\n\nNextChat 的核心亮点在于其广泛的模型兼容性，原生支持 Claude、DeepSeek、GPT-4 及 Gemini Pro 等主流大模型，让用户在一个界面即可自由切换不同 AI 能力。此外，它还率先支持 MCP（Model Context Protocol）协议，增强了上下文处理能力。针对企业用户，NextChat 提供专业版解决方案，具备品牌定制、细粒度权限控制、内部知识库整合及安全审计等功能，满足公司对数据隐私和个性化管理的高标准要求。",87618,"2026-04-05T07:20:52",[53,52],{"id":151,"name":152,"github_repo":153,"description_zh":154,"stars":155,"difficulty_score":131,"last_commit_at":156,"category_tags":157,"status":55},2268,"ML-For-Beginners","microsoft\u002FML-For-Beginners","ML-For-Beginners 是由微软推出的一套系统化机器学习入门课程，旨在帮助零基础用户轻松掌握经典机器学习知识。这套课程将学习路径规划为 12 周，包含 26 节精炼课程和 52 道配套测验，内容涵盖从基础概念到实际应用的完整流程，有效解决了初学者面对庞大知识体系时无从下手、缺乏结构化指导的痛点。\n\n无论是希望转型的开发者、需要补充算法背景的研究人员，还是对人工智能充满好奇的普通爱好者，都能从中受益。课程不仅提供了清晰的理论讲解，还强调动手实践，让用户在循序渐进中建立扎实的技能基础。其独特的亮点在于强大的多语言支持，通过自动化机制提供了包括简体中文在内的 50 多种语言版本，极大地降低了全球不同背景用户的学习门槛。此外，项目采用开源协作模式，社区活跃且内容持续更新，确保学习者能获取前沿且准确的技术资讯。如果你正寻找一条清晰、友好且专业的机器学习入门之路，ML-For-Beginners 将是理想的起点。",84991,"2026-04-05T10:45:23",[123,158,159,160,124,161,52,53,162],"数据工具","视频","插件","其他","音频",{"id":164,"name":165,"github_repo":166,"description_zh":167,"stars":168,"difficulty_score":54,"last_commit_at":169,"category_tags":170,"status":55},3128,"ragflow","infiniflow\u002Fragflow","RAGFlow 是一款领先的开源检索增强生成（RAG）引擎，旨在为大语言模型构建更精准、可靠的上下文层。它巧妙地将前沿的 RAG 技术与智能体（Agent）能力相结合，不仅支持从各类文档中高效提取知识，还能让模型基于这些知识进行逻辑推理和任务执行。\n\n在大模型应用中，幻觉问题和知识滞后是常见痛点。RAGFlow 通过深度解析复杂文档结构（如表格、图表及混合排版），显著提升了信息检索的准确度，从而有效减少模型“胡编乱造”的现象，确保回答既有据可依又具备时效性。其内置的智能体机制更进一步，使系统不仅能回答问题，还能自主规划步骤解决复杂问题。\n\n这款工具特别适合开发者、企业技术团队以及 AI 研究人员使用。无论是希望快速搭建私有知识库问答系统，还是致力于探索大模型在垂直领域落地的创新者，都能从中受益。RAGFlow 提供了可视化的工作流编排界面和灵活的 API 接口，既降低了非算法背景用户的上手门槛，也满足了专业开发者对系统深度定制的需求。作为基于 Apache 2.0 协议开源的项目，它正成为连接通用大模型与行业专有知识之间的重要桥梁。",77062,"2026-04-04T04:44:48",[124,123,53,52,161]]