Package: benepar
Berkeley Neural ParserA high-accuracy parser with models for 11 languages, implemented in Python. Based onConstituency Parsing with a Self-Attentive Encoderfrom ACL 2018, with additional changes described inMultilingual Constituency Parsing with Self-Attention and Pre-Training.New February 2021:Version 0.2.0 of the Berkeley Neural Parser is now out, with higher-quality pre-trained models for all languages. Inference now uses PyTorch instead of TensorFlow (training has always been PyTorch-only). Drops support for Python 2.7 and 3.5. Includes updated support for training and using your own parsers, based on your choice ofpre-trained model.ContentsInstallationUsageAvailable ModelsTrainingReproducing ExperimentsCitationCreditsIf you are primarily interested in training your own parsing models, skip to theTrainingsection of this README.InstallationTo install the parser, run the command:$pipinstallbeneparNote: benepar 0.2.0 is a major upgrade over the previous version, and comes with entirely new and higher-quality parser models. If you are not ready to upgrade, you can pin your benepar version tothe previous release (0.1.3).Python 3.6 (or newer) andPyTorch1.6 (or newer) are required. See the PyTorch website for instruction on how to select between GPU-enabled and CPU-only versions of PyTorch; benepar will automatically use the GPU if it is available to pytorch.The recommended way of using benepar is through integration withspaCy. If using spaCy, you should install a spaCy model for your language. For English, the installation command is:$python-mspacydownloaden_core_web_mdThe spaCy model is only used for tokenization and sentence segmentation. If language-specific analysis beyond parsing is not required, you may also forego a language-specific model and instead use a multi-language model that only performs tokenization and segmentation.One such model, newly added in spaCy 3.0, should work for English, German, Korean, Polish, and Swedish (but not Chinese, since it doesn't seem to support Chinese word segmentation).Parsing models need to be downloaded separately, using the commands:>>>importbenepar>>>benepar.download('benepar_en3')See theAvailable Modelssection below for a full list of models.UsageUsage with spaCy (recommended)The recommended way of using benepar is through its integration with spaCy:>>>importbenepar,spacy>>>nlp=spacy.load('en_core_web_md')>>>ifspacy.__version__.startswith('2'):nlp.add_pipe(benepar.BeneparComponent("benepar_en3"))else:nlp.add_pipe("benepar",config={"model":"benepar_en3"})>>>doc=nlp("The time for action is now. It's never too late to do something.")>>>sent=list(doc.sents)[0]>>>print(sent._.parse_string)(S(NP(NP(DTThe)(NNtime))(PP(INfor)(NP(NNaction))))(VP(VBZis)(ADVP(RBnow)))(..))>>>sent._.labels('S',)>>>list(sent._.children)[0]ThetimeforactionSince spaCy does not provide an official constituency parsing API, all methods are accessible through the extension namespacesSpan._andToken._.The following extension properties are available:Span._.labels: a tuple of labels for the given span. A span may have multiple labels when there are unary chains in the parse tree.Span._.parse_string: a string representation of the parse tree for a given span.Span._.constituents: an iterator overSpanobjects for sub-constituents in a pre-order traversal of the parse tree.Span._.parent: the parentSpanin the parse tree.Span._.children: an iterator over childSpans in the parse tree.Token._.labels,Token._.parse_string,Token._.parent: these behave the same as calling the corresponding method on the length-one Span containing the token.These methods will raise an exception when called on a span that is not a constituent in the parse tree. Such errors can be avoided by traversing the parse tree starting at either sentence level (by iterating overdoc.sents) or with an individualTokenobject.Usage with NLTKThere is also an NLTK interface, which is designed for use with pre-tokenized datasets and treebanks, or when integrating the parser into an NLP pipeline that already performs (at minimum) tokenization and sentence splitting. For parsing starting with raw text, it isstrongly encouragedthat you use spaCy andbenepar.BeneparComponentinstead.Sample usage with NLTK:>>>importbenepar>>>parser=benepar.Parser("benepar_en3")>>>input_sentence=benepar.InputSentence(words=['"','Fly','safely','.','"'],space_after=[False,True,False,False,False],tags=['``','VB','RB','.',"''"],escaped_words=['``','Fly','safely','.',"''"],)>>>tree=parser.parse(input_sentence)>>>print(tree)(TOP(S(````)(VP(VBFly)(ADVP(RBsafely)))(..)('''')))Not all fields ofbenepar.InputSentenceare required, but at least one ofwordsandescaped_wordsmust be specified. The parser will attempt to guess the value for missing fields, for example:>>>input_sentence=benepar.InputSentence(words=['"','Fly','safely','.','"'],)>>>parser.parse(input_sentence)Useparse_sentsto parse multiple sentences.>>>input_sentence1=benepar.InputSentence(words=['The','time','for','action','is','now','.'],)>>>input_sentence2=benepar.InputSentence(words=['It',"'s",'never','too','late','to','do','something','.'],)>>>parser.parse_sents([input_sentence1,input_sentence2])Some parser models also allow Unicode text input for debugging/interactive use, but passing in raw text strings isstrongly discouragedfor any application where parsing accuracy matters.>>>parser.parse('"Fly safely."')# For debugging/interactive use only.When parsing from raw text, we recommend using spaCy andbenepar.BeneparComponentinstead. The reason is that parser models do not ship with a tokenizer or sentence splitter, and some models may not include a part-of-speech tagger either. A toolkit must be used to fill in these pipeline components, and spaCy outperforms NLTK in all of these areas (sometimes by a large margin).Available ModelsThe following trained parser models are available. To use spaCy integration, you will also need to install aspaCy model for the appropriate language.ModelLanguageInfobenepar_en3English95.40 F1 onrevisedWSJ test set. The training data uses revised tokenization and syntactic annotation based on the same guidelines as the English Web Treebank and OntoNotes, which better matches modern tokenization practices in libraries like spaCy. Based on T5-small.benepar_en3_largeEnglish96.29 F1 onrevisedWSJ test set. The training data uses revised tokenization and syntactic annotation based on the same guidelines as the English Web Treebank and OntoNotes, which better matches modern tokenization practices in libraries like spaCy. Based on T5-large.benepar_zh2Chinese92.56 F1 on CTB 5.1 test set. Usage with spaCy allows supports parsing from raw text, but the NLTK API only supports parsing previously tokenized sentences. Based on Chinese ELECTRA-180G-large.benepar_arArabic90.52 F1 on SPMRL2013/2014 test set. Only supports using the NLTK API for parsing previously tokenized sentences. Parsing from raw text and spaCy integration are not supported. Based on XLM-R.benepar_deGerman92.10 F1 on SPMRL2013/2014 test set. Based on XLM-R.benepar_euBasque93.36 F1 on SPMRL2013/2014 test set. Usage with spaCy first requires implementing Basque support in spaCy. Based on XLM-R.benepar_frFrench88.43 F1 on SPMRL2013/2014 test set. Based on XLM-R.benepar_heHebrew93.98 F1 on SPMRL2013/2014 test set. Only supports using the NLTK API for parsing previously tokenized sentences. Parsing from raw text and spaCy integration are not supported. Based on XLM-R.benepar_huHungarian96.19 F1 on SPMRL2013/2014 test set. Usage with spaCy requires aHungarian model for spaCy. The NLTK API only supports parsing previously tokenized sentences. Based on XLM-R.benepar_koKorean91.72 F1 on SPMRL2013/2014 test set. Can be used with spaCy'smulti-language sentence segmentation model(requires spaCy v3.0). The NLTK API only supports parsing previously tokenized sentences. Based on XLM-R.benepar_plPolish97.15 F1 on SPMRL2013/2014 test set. Based on XLM-R.benepar_svSwedish92.21 F1 on SPMRL2013/2014 test set. Can be used with spaCy'smulti-language sentence segmentation model(requires spaCy v3.0). Based on XLM-R.benepar_en3_wsjEnglishConsider usingbenepar_en3orbenepar_en3_largeinstead. 95.55 F1 oncanonicalWSJ test set used for decades of English constituency parsing publications. Based on BERT-large-uncased. We believe that the revised annotation guidelines used for trainingbenepar_en3/benepar_en3_largeare more suitable for downstream use because they better handle language usage in web text, and are more consistent with modern practices in dependency parsing and libraries like spaCy. Nevertheless, we provide thebenepar_en3_wsjmodel for cases where using the revised treebanking conventions are not appropriate, such as benchmarking different models on the same dataset.TrainingTraining requires cloning this repository from GitHub. While the model code insrc/beneparis distributed in thebeneparpackage on PyPI, the training and evaluation scripts directly undersrc/are not.Software Requirements for TrainingPython 3.7 or higher.PyTorch1.6.0, or any compatible version.All dependencies required by thebeneparpackage, including:NLTK3.2,torch-struct0.4,transformers4.3.0, or compatible.pytokenizations0.7.2 or compatible.EVALB. Before starting, runmakeinside theEVALB/directory to compile anevalbexecutable. This will be called from Python for evaluation. If training on the SPMRL datasets, you will need to runmakeinside theEVALB_SPMRL/directory instead.Training InstructionsA new model can be trained using the commandpython src/main.py train .... Some of the available arguments are:ArgumentDescriptionDefault--model-path-basePath base to use for saving modelsN/A--evalb-dirPath to EVALB directoryEVALB/--train-pathPath to training treesdata/wsj/train_02-21.LDC99T42--train-path-textOptional non-destructive tokenization of the training dataGuess raw text; see--text-processing--dev-pathPath to development treesdata/wsj/dev_22.LDC99T42--dev-path-textOptional non-destructive tokenization of the development dataGuess raw text; see--text-processing--text-processingHeuristics for guessing raw text from descructively tokenized tree files. Seeload_trees()insrc/treebanks.pyDefault rules for languages other than Arabic, Chinese, and Hebrew--subbatch-max-tokensMaximum number of tokens to process in parallel while training (a full batch may not fit in GPU memory)2000--parallelizeDistribute pre-trained model (e.g. T5) layers across multiple GPUs.Use at most one GPU--batch-sizeNumber of examples per training update32--checks-per-epochNumber of development evaluations per epoch4--numpy-seedNumPy random seedRandom--use-pretrainedUse pre-trained encoderDo not use pre-trained encoder--pretrained-modelModel to use if--use-pretrainedis passed. May be a path or a model id from theHuggingFace Model Hubbert-base-uncased--predict-tagsAdds a part-of-speech tagging component and auxiliary loss to the parserDo not predict tags--use-chars-lstmUse learned CharLSTM word representationsDo not use CharLSTM--use-encoderUse learned transformer layers on top of pre-trained model or CharLSTMDo not use extra transformer layers--num-layersNumber of transformer layers to use if--use-encoderis passed8--encoder-max-lenMaximum sentence length (in words) allowed for extra transformer layers512Additional arguments are available for other hyperparameters; seemake_hparams()insrc/main.py. These can be specified on the command line, such as--num-layers 2(for numerical parameters),--predict-tags(for boolean parameters that default to False), or--no-XXX(for boolean parameters that default to True).For each development evaluation, the F-score on the development set is computed and compared to the previous best. If the current model is better, the previous model will be deleted and the current model will be saved. The new filename will be derived from the provided model path base and the development F-score.Prior to training the parser, you will first need to obtain appropriate training data. We provideinstructions on how to process standard datasets like PTB, CTB, and the SMPRL 2013/2014 Shared Task data. After following the instructions for the English WSJ data, you can use the following command to train an English parser using the default hyperparameters:python src/main.py train --use-pretrained --model-path-base models/en_bert_baseSeeEXPERIMENTS.mdfor more examples of good hyperparameter choices.Evaluation InstructionsA saved model can be evaluated on a test corpus using the commandpython src/main.py test ...with the following arguments:ArgumentDescriptionDefault--model-pathPath of saved modelN/A--evalb-dirPath to EVALB directoryEVALB/--test-pathPath to test treesdata/23.auto.clean--test-path-textOptional non-destructive tokenization of the test dataGuess raw text; see--text-processing--text-processingHeuristics for guessing raw text from descructively tokenized tree files. Seeload_trees()insrc/treebanks.pyDefault rules for languages other than Arabic, Chinese, and Hebrew--test-path-rawAlternative path to test trees that is used for evalb only (used to double-check that evaluation against pre-processed trees does not contain any bugs)Compare to trees from--test-path--subbatch-max-tokensMaximum number of tokens to process in parallel (a GPU does not have enough memory to process the full dataset in one batch)500--parallelizeDistribute pre-trained model (e.g. T5) layers across multiple GPUs.Use at most one GPU--output-pathPath to write predicted trees to (use"-"for stdout).Do not save predicted trees--no-predict-tagsUse gold part-of-speech tags when running EVALB. This is the standard for publications, and omitting this flag may give erroneously high F1 scores.Use predicted part-of-speech tags for EVALB, if availableAs an example, you can evaluate a trained model using the following command:python src/main.py test --model-path models/en_bert_base_dev=*.ptExporting Models for InferenceThebeneparpackage can directly use saved checkpoints by replacing a model name likebenepar_en3with a path such asmodels/en_bert_base_dev_dev=95.67.pt. However, releasing the single-file checkpoints has a few shortcomings:Single-file checkpoints do not include the tokenizer or pre-trained model config. These can generally be downloaded automatically from the HuggingFace model hub, but this requires an Internet connection and may also (incidentally and unnecessarily) download pre-trained weights from the HuggingFace Model HubSingle-file checkpoints are 3x larger than necessary, because they save optimizer stateUsesrc/export.pyto convert a checkpoint file into a directory that encapsulates everything about a trained model. For example,python src/export.py export \
  --model-path models/en_bert_base_dev=*.pt \
  --output-dir=models/en_bert_baseWhen exporting, there is also a--compressoption that slightly adjusts model weights, so that the output directory can be compressed into a ZIP archive of much smaller size. We use this for our official model releases, because it's a hassle to distribute model weights that are 2GB+ in size. When using the--compressoption, it is recommended to specify a test set in order to verify that compression indeed has minimal impact on parsing accuracy. Using the development data for verification is not recommended, since the development data was already used for the model selection criterion during training.python src/export.py export \
  --model-path models/en_bert_base_dev=*.pt \
  --output-dir=models/en_bert_base \
  --test-path=data/wsj/test_23.LDC99T42Thesrc/export.pyscript also has atestsubcommand that's roughly similar topython src/main.py test, except that it supports exported models and has slightly different flags. We can run the following command to verify that our English parser using BERT-large-uncased indeed achieves 95.55 F1 on the canonical WSJ test set:python src/export.py test --model-path benepar_en3_wsj --test-path data/wsj/test_23.LDC99T42Reproducing ExperimentsSeeEXPERIMENTS.mdfor instructions on how to reproduce experiments reported in our ACL 2018 and 2019 papers.CitationIf you use this software for research, please cite our papers as follows:@inproceedings{kitaev-etal-2019-multilingual,
    title = "Multilingual Constituency Parsing with Self-Attention and Pre-Training",
    author = "Kitaev, Nikita  and
      Cao, Steven  and
      Klein, Dan",
    booktitle = "Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics",
    month = jul,
    year = "2019",
    address = "Florence, Italy",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/P19-1340",
    doi = "10.18653/v1/P19-1340",
    pages = "3499--3505",
}

@inproceedings{kitaev-klein-2018-constituency,
    title = "Constituency Parsing with a Self-Attentive Encoder",
    author = "Kitaev, Nikita  and
      Klein, Dan",
    booktitle = "Proceedings of the 56th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)",
    month = jul,
    year = "2018",
    address = "Melbourne, Australia",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/P18-1249",
    doi = "10.18653/v1/P18-1249",
    pages = "2676--2686",
}CreditsThe code in this repository and portions of this README are based onhttps://github.com/mitchellstern/minimal-span-parser